@dotaz/server 0.0.28 → 0.0.29

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/bin/dotaz.js CHANGED
@@ -1,46 +1,49 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var C=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function B(e){let t=e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"");return t==="localhost"||t==="::1"||/^127(\.\d{1,3}){3}$/.test(t)}function Rt(e,t=process.env){let n=B(e),r=Zn(t.DOTAZ_ALLOWED_HOSTS,(s)=>Pe(s.toLowerCase()));return{requireLoopbackHost:n,allowedHosts:r}}function ke(e,t){let n=Pe(Nt(e));if(t.requireLoopbackHost)return B(n)||t.allowedHosts.has(n);if(t.allowedHosts.size>0)return t.allowedHosts.has(n);return!0}function Q(e,t){if(!ke(e,t))return{ok:!1,status:403,reason:"Host not allowed"};if(!Gn(e))return{ok:!1,status:403,reason:"Cross-site requests are not allowed"};if(!Xn(e))return{ok:!1,status:403,reason:"Origin not allowed"};return{ok:!0}}function K(e,t){if(t==="json")return Response.json({error:e.reason},{status:e.status});return new Response(e.reason,{status:e.status})}function Gn(e){let t=e.headers.get("sec-fetch-site");return t===null||t==="same-origin"||t==="none"}function Xn(e){let t=e.headers.get("origin");if(t===null)return!0;let n;try{n=new URL(t)}catch{return!1}let r=Nt(e);if(n.host===r)return!0;return B(n.hostname)&&B(Pe(r))}function Nt(e){return(e.headers.get("host")??new URL(e.url).host).trim().toLowerCase()}function Pe(e){if(e.startsWith("[")){let t=e.indexOf("]");return t===-1?e:e.slice(1,t)}return e.split(":")[0]??e}function Zn(e,t){let n=new Set;if(!e)return n;for(let r of e.split(",")){let s=r.trim();if(s)n.add(t(s))}return n}function _t(e){return`"${e.replace(/"/g,'""')}"`}function q(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}function xt(e,t){let n=[...e];for(let r of t??[])if(!n.includes(r))n.push(r);return n}function er(e){if(e===null||e===void 0)return"";if(typeof e==="object")return JSON.stringify(e);return String(e)}function $e(e){if(e===null||e===void 0)return"NULL";if(typeof e==="number")return String(e);if(typeof e==="boolean")return e?"TRUE":"FALSE";if(typeof e==="string")return`'${e.replace(/'/g,"''")}'`;if(typeof e==="object")return`'${JSON.stringify(e).replace(/'/g,"''")}'`;return String(e)}function tr(e){if(e===null||e===void 0)return"NULL";if(typeof e==="object")return JSON.stringify(e);return String(e)}function It(e){return e.replace(/\|/g,"\\|").replace(/\n/g," ")}function Ue(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Ot(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function nr(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");if(!/^[a-zA-Z_]/.test(t))t="_"+t;return t}function rr(e,t,n){if(!e)return n(t);return`${n(e)}.${n(t)}`}function Lt(e){let t=e.quoteIdentifier??_t,n=e.qualifiedTableName??rr(e.schema,e.table,t);switch(e.format){case"csv":return new kt(e.delimiter??",",e.includeHeaders??!0);case"json":return new Pt;case"sql":return new Mt(n,e.batchSize??100,t);case"markdown":return new Ut;case"sql_update":if(!e.keyColumns||e.keyColumns.length===0)throw Error("SQL UPDATE export requires key columns");return new $t(n,t,e.keyColumns);case"html":return new qt;case"xml":return new Ft}}class kt{delimiter;includeHeaders;columns=null;constructor(e,t){this.delimiter=e;this.includeHeaders=t}preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=q(e);let n=this.columns,r=[];if(t&&this.includeHeaders)r.push(n.map((s)=>this.escapeField(s)).join(this.delimiter));for(let s of e){let i=n.map((o)=>this.escapeField(er(s[o])));r.push(i.join(this.delimiter))}return r.join(`
3
+ var T=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Y(e){let t=e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"");return t==="localhost"||t==="::1"||/^127(\.\d{1,3}){3}$/.test(t)}function qt(e,t=process.env){let n=Y(e),r=vr(t.DOTAZ_ALLOWED_HOSTS,(s)=>We(s.toLowerCase()));return{requireLoopbackHost:n,allowedHosts:r}}function Ke(e,t){let n=We(Ft(e));if(t.requireLoopbackHost)return Y(n)||t.allowedHosts.has(n);if(t.allowedHosts.size>0)return t.allowedHosts.has(n);return!0}function K(e,t){if(!Ke(e,t))return{ok:!1,status:403,reason:"Host not allowed"};if(!Tr(e))return{ok:!1,status:403,reason:"Cross-site requests are not allowed"};if(!Ar(e))return{ok:!1,status:403,reason:"Origin not allowed"};return{ok:!0}}function W(e,t){if(t==="json")return Response.json({error:e.reason},{status:e.status});return new Response(e.reason,{status:e.status})}function Tr(e){let t=e.headers.get("sec-fetch-site");return t===null||t==="same-origin"||t==="none"}function Ar(e){let t=e.headers.get("origin");if(t===null)return!0;let n;try{n=new URL(t)}catch{return!1}let r=Ft(e);if(n.host===r)return!0;return Y(n.hostname)&&Y(We(r))}function Ft(e){return(e.headers.get("host")??new URL(e.url).host).trim().toLowerCase()}function We(e){if(e.startsWith("[")){let t=e.indexOf("]");return t===-1?e:e.slice(1,t)}return e.split(":")[0]??e}function vr(e,t){let n=new Set;if(!e)return n;for(let r of e.split(",")){let s=r.trim();if(s)n.add(t(s))}return n}var b,D,Se,R,_;var P=T(()=>{b=class b extends Error{code;constructor(e,t,n){super(t,n);this.name="DatabaseError",this.code=e}};D=class D extends b{constructor(e,t,n){super(e,t,n);this.name="ConnectionError"}};Se=class Se extends b{constructor(e,t){super("AUTH_FAILED",e,t);this.name="AuthenticationError"}};R=class R extends b{constructor(e,t,n){super(e,t,n);this.name="QueryError"}};_=class _ extends b{constructor(e,t,n){super(e,t,n);this.name="ConstraintError"}}});function Bt(){return{type:"response",id:0,success:!1,error:"Invalid JSON"}}async function Qt(e,t){let n=e.id??0,r=t(e.method);if(!r)return{type:"response",id:n,success:!1,error:`Unknown method: ${e.method}`};try{let s=await r(e.params);return{type:"response",id:n,success:!0,payload:s}}catch(s){return{type:"response",id:n,success:!1,error:s instanceof Error?s.message:String(s),errorCode:s instanceof b?s.code:void 0}}}function Yt(e){let t=typeof e==="string"?e:new TextDecoder().decode(e),n;try{n=JSON.parse(t)}catch{return null}if(typeof n!=="object"||n===null||typeof n.method!=="string")return null;let{id:r,method:s,params:i}=n;return{id:r,method:s,params:i}}var Kt=T(()=>{P()});function Wt(e){return`"${e.replace(/"/g,'""')}"`}function F(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}function Gt(e,t){let n=[...e];for(let r of t??[])if(!n.includes(r))n.push(r);return n}function Rr(e){if(e===null||e===void 0)return"";if(typeof e==="object")return JSON.stringify(e);return String(e)}function Ge(e){if(e===null||e===void 0)return"NULL";if(typeof e==="number")return String(e);if(typeof e==="boolean")return e?"TRUE":"FALSE";if(typeof e==="string")return`'${e.replace(/'/g,"''")}'`;if(typeof e==="object")return`'${JSON.stringify(e).replace(/'/g,"''")}'`;return String(e)}function Nr(e){if(e===null||e===void 0)return"NULL";if(typeof e==="object")return JSON.stringify(e);return String(e)}function jt(e){return e.replace(/\|/g,"\\|").replace(/\n/g," ")}function ze(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function zt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Dr(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");if(!/^[a-zA-Z_]/.test(t))t="_"+t;return t}function _r(e,t,n){if(!e)return n(t);return`${n(e)}.${n(t)}`}function Vt(e){let t=e.quoteIdentifier??Wt,n=e.qualifiedTableName??_r(e.schema,e.table,t);switch(e.format){case"csv":return new Jt(e.delimiter??",",e.includeHeaders??!0);case"json":return new Xt;case"sql":return new Zt(n,e.batchSize??100,t);case"markdown":return new en;case"sql_update":if(!e.keyColumns||e.keyColumns.length===0)throw Error("SQL UPDATE export requires key columns");return new tn(n,t,e.keyColumns);case"html":return new nn;case"xml":return new rn}}class Jt{delimiter;includeHeaders;columns=null;constructor(e,t){this.delimiter=e;this.includeHeaders=t}preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let n=this.columns,r=[];if(t&&this.includeHeaders)r.push(n.map((s)=>this.escapeField(s)).join(this.delimiter));for(let s of e){let i=n.map((o)=>this.escapeField(Rr(s[o])));r.push(i.join(this.delimiter))}return r.join(`
4
4
  `)+`
5
5
  `}epilogue(){return""}escapeField(e){if(e.includes(this.delimiter)||e.includes('"')||e.includes(`
6
- `)||e.includes("\r"))return`"${e.replace(/"/g,'""')}"`;return e}}class Pt{hasWritten=!1;preamble(){return`[
6
+ `)||e.includes("\r"))return`"${e.replace(/"/g,'""')}"`;return e}}class Xt{hasWritten=!1;preamble(){return`[
7
7
  `}formatBatch(e){if(e.length===0)return"";return e.map((n)=>{let r=this.hasWritten?`,
8
8
  `:"";return this.hasWritten=!0,r+" "+JSON.stringify(n)}).join("")}epilogue(){return`
9
9
  ]
10
- `}}class Mt{tableName;batchSize;quoteIdentifier;columns=null;constructor(e,t,n){this.tableName=e;this.batchSize=t;this.quoteIdentifier=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=q(e);let t=this.columns,r=t.map((i)=>this.quoteIdentifier(i)).join(", "),s=[];for(let i=0;i<e.length;i+=this.batchSize){let a=e.slice(i,i+this.batchSize).map((c)=>`(${t.map((l)=>$e(c[l])).join(", ")})`);s.push(`INSERT INTO ${this.tableName} (${r}) VALUES
10
+ `}}class Zt{tableName;batchSize;quoteIdentifier;columns=null;constructor(e,t,n){this.tableName=e;this.batchSize=t;this.quoteIdentifier=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let t=this.columns,r=t.map((i)=>this.quoteIdentifier(i)).join(", "),s=[];for(let i=0;i<e.length;i+=this.batchSize){let a=e.slice(i,i+this.batchSize).map((c)=>`(${t.map((l)=>Ge(c[l])).join(", ")})`);s.push(`INSERT INTO ${this.tableName} (${r}) VALUES
11
11
  ${a.join(`,
12
12
  `)};
13
13
  `)}return s.join(`
14
- `)}epilogue(){return""}}class Ut{columns=null;preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=q(e);let n=this.columns,r=[];if(t)r.push("| "+n.map(It).join(" | ")+" |"),r.push("| "+n.map(()=>"---").join(" | ")+" |");for(let s of e){let i=n.map((o)=>It(tr(s[o])));r.push("| "+i.join(" | ")+" |")}return r.join(`
14
+ `)}epilogue(){return""}}class en{columns=null;preamble(){return""}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let n=this.columns,r=[];if(t)r.push("| "+n.map(jt).join(" | ")+" |"),r.push("| "+n.map(()=>"---").join(" | ")+" |");for(let s of e){let i=n.map((o)=>jt(Nr(s[o])));r.push("| "+i.join(" | ")+" |")}return r.join(`
15
15
  `)+`
16
- `}epilogue(){return""}}class $t{tableName;quoteIdentifier;keyColumns;columns=null;constructor(e,t,n){this.tableName=e;this.quoteIdentifier=t;this.keyColumns=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=q(e);let t=this.columns,n=new Set(this.keyColumns),r=t.filter((i)=>!n.has(i)),s=[];for(let i of e){if(r.length===0)continue;for(let c of this.keyColumns){if(!Object.hasOwn(i,c))throw Error(`SQL UPDATE export key column "${c}" is missing from exported rows`);if(i[c]===null||i[c]===void 0)throw Error(`SQL UPDATE export key column "${c}" has no value`)}let o=r.map((c)=>`${this.quoteIdentifier(c)} = ${$e(i[c])}`).join(", "),a=this.keyColumns.map((c)=>`${this.quoteIdentifier(c)} = ${$e(i[c])}`).join(" AND ");s.push(`UPDATE ${this.tableName} SET ${o} WHERE ${a};
17
- `)}return s.join("")}epilogue(){return""}}class qt{columns=null;preamble(){return`<table>
18
- `}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=q(e);let n=this.columns,r=[];if(t){r.push(" <thead>"),r.push(" <tr>");for(let s of n)r.push(` <th>${Ue(s)}</th>`);r.push(" </tr>"),r.push(" </thead>"),r.push(" <tbody>")}for(let s of e){r.push(" <tr>");for(let i of n){let o=s[i],a=o===null||o===void 0?"":typeof o==="object"?Ue(JSON.stringify(o)):Ue(String(o));r.push(` <td>${a}</td>`)}r.push(" </tr>")}return r.join(`
16
+ `}epilogue(){return""}}class tn{tableName;quoteIdentifier;keyColumns;columns=null;constructor(e,t,n){this.tableName=e;this.quoteIdentifier=t;this.keyColumns=n}preamble(){return""}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let t=this.columns,n=new Set(this.keyColumns),r=t.filter((i)=>!n.has(i)),s=[];for(let i of e){if(r.length===0)continue;for(let c of this.keyColumns){if(!Object.hasOwn(i,c))throw Error(`SQL UPDATE export key column "${c}" is missing from exported rows`);if(i[c]===null||i[c]===void 0)throw Error(`SQL UPDATE export key column "${c}" has no value`)}let o=r.map((c)=>`${this.quoteIdentifier(c)} = ${Ge(i[c])}`).join(", "),a=this.keyColumns.map((c)=>`${this.quoteIdentifier(c)} = ${Ge(i[c])}`).join(" AND ");s.push(`UPDATE ${this.tableName} SET ${o} WHERE ${a};
17
+ `)}return s.join("")}epilogue(){return""}}class nn{columns=null;preamble(){return`<table>
18
+ `}formatBatch(e,t){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let n=this.columns,r=[];if(t){r.push(" <thead>"),r.push(" <tr>");for(let s of n)r.push(` <th>${ze(s)}</th>`);r.push(" </tr>"),r.push(" </thead>"),r.push(" <tbody>")}for(let s of e){r.push(" <tr>");for(let i of n){let o=s[i],a=o===null||o===void 0?"":typeof o==="object"?ze(JSON.stringify(o)):ze(String(o));r.push(` <td>${a}</td>`)}r.push(" </tr>")}return r.join(`
19
19
  `)+`
20
20
  `}epilogue(){return` </tbody>
21
21
  </table>
22
- `}}class Ft{columns=null;preamble(){return`<?xml version="1.0" encoding="UTF-8"?>
22
+ `}}class rn{columns=null;preamble(){return`<?xml version="1.0" encoding="UTF-8"?>
23
23
  <rows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
24
- `}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=q(e);let t=this.columns,n=[];for(let r of e){n.push(" <row>");for(let s of t){let i=r[s],o=nr(s);if(i===null||i===void 0)n.push(` <${o} xsi:nil="true"/>`);else{let a=typeof i==="object"?Ot(JSON.stringify(i)):Ot(String(i));n.push(` <${o}>${a}</${o}>`)}}n.push(" </row>")}return n.join(`
24
+ `}formatBatch(e){if(e.length===0)return"";if(!this.columns)this.columns=F(e);let t=this.columns,n=[];for(let r of e){n.push(" <row>");for(let s of t){let i=r[s],o=Dr(s);if(i===null||i===void 0)n.push(` <${o} xsi:nil="true"/>`);else{let a=typeof i==="object"?zt(JSON.stringify(i)):zt(String(i));n.push(` <${o}>${a}</${o}>`)}}n.push(" </row>")}return n.join(`
25
25
  `)+`
26
26
  `}epilogue(){return`</rows>
27
- `}}var Ht=()=>{};var ks;var k=C(()=>{ks=Object.freeze({__dotaz_sentinel:"DEFAULT"})});function fe(e,t){let n=t.getDriverType()==="mysql"?"CHAR":"TEXT";return`CAST(${e} AS ${n})`}function qe(e){return e.includes(".")}function Fe(e){let t=e.indexOf(".");return{table:e.substring(0,t),column:e.substring(t+1)}}function He(e,t){return(n)=>{if(qe(n)){let{table:r,column:s}=Fe(n),i=e.find((o)=>o.referencedTable===r);if(i)return`${t.quoteIdentifier(i.alias)}.${t.quoteIdentifier(s)}`}return`t0.${t.quoteIdentifier(n)}`}}function ge(e,t,n=0,r){if(!e||e.length===0)return{sql:"",params:[]};let s=[],i=[],o=n;for(let a of e){let c=r?r(a.column):t.quoteIdentifier(a.column);switch(a.operator){case"eq":o++,s.push(`${c} = ${t.placeholder(o)}`),i.push(a.value);break;case"neq":o++,s.push(`${c} != ${t.placeholder(o)}`),i.push(a.value);break;case"gt":o++,s.push(`${c} > ${t.placeholder(o)}`),i.push(a.value);break;case"gte":o++,s.push(`${c} >= ${t.placeholder(o)}`),i.push(a.value);break;case"lt":o++,s.push(`${c} < ${t.placeholder(o)}`),i.push(a.value);break;case"lte":o++,s.push(`${c} <= ${t.placeholder(o)}`),i.push(a.value);break;case"like":o++,s.push(`${c} LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"notLike":o++,s.push(`${c} NOT LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"in":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} IN (${l.join(", ")})`),i.push(...u);break}case"notIn":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} NOT IN (${l.join(", ")})`),i.push(...u);break}case"isNull":s.push(`${c} IS NULL`);break;case"isNotNull":s.push(`${c} IS NOT NULL`);break}}if(s.length===0)return{sql:"",params:[]};return{sql:`WHERE ${s.join(" AND ")}`,params:i}}function he(e,t,n){if(!e||e.length===0)return"";return`ORDER BY ${e.map((s)=>{let i=n?n(s.column):t.quoteIdentifier(s.column),o=s.direction==="desc"?"DESC":"ASC";return`${i} ${o}`}).join(", ")}`}function Be(e,t){return e.map((n)=>{let r=t.qualifyTable(n.referencedSchema,n.referencedTable),s=t.quoteIdentifier(n.alias),i;if(qe(n.fkColumn)){let{table:a,column:c}=Fe(n.fkColumn),u=e.find((l)=>l.referencedTable===a);if(u)i=`${t.quoteIdentifier(u.alias)}.${t.quoteIdentifier(c)}`;else i=`t0.${t.quoteIdentifier(n.fkColumn)}`}else i=`t0.${t.quoteIdentifier(n.fkColumn)}`;let o=`${s}.${t.quoteIdentifier(n.referencedColumn)}`;return`LEFT JOIN ${r} AS ${s} ON ${i} = ${o}`}).join(" ")}var ye=C(()=>{k()});async function Qe(e,t,n,r,s){let i=ur(t.format==="csv"?t.encoding:void 0),o=Kt(t,e),a=0;if(t.format==="csv"&&t.utf8Bom&&(t.encoding??"utf-8")==="utf-8")await n.write(new Uint8Array([239,187,191]));let c=o.preamble();if(c)await n.write(i(c));let{sql:u,params:l}=Ee(t,e),d=t.batchSize??ir,p=e.iterate(u,l,d,r),h=!0;for await(let g of p){let y=g;if(t.limit!==void 0){let f=t.limit-a;if(f<=0)break;if(y.length>f)y=y.slice(0,f)}let E=o.formatBatch(y,h);if(await n.write(i(E)),a+=y.length,s?.(a),h=!1,t.limit!==void 0&&a>=t.limit)break}let m=o.epilogue();if(m)await n.write(i(m));return await n.end(),{rowCount:a}}async function Bt(e,t,n,r,s){let o=Bun.file(n).writer(),a={write(c){o.write(c)},async end(){await o.end()}};try{let c=await Qe(e,t,a,r,s),u=await Bun.file(n).stat();return{rowCount:c.rowCount,sizeBytes:u?.size??0}}catch(c){await o.end();try{let{unlink:u}=await import("fs/promises");await u(n)}catch{}throw c}}async function Qt(e,t){let n=t.limit??10,{sql:r,params:s}=Ee(t,e),i=s.length;i++;let o=e.placeholder(i),a=`${r} LIMIT ${o}`,u=(await e.execute(a,[...s,n])).rows,l=Kt(t,e),d=[],p=l.preamble();if(p)d.push(p);d.push(l.formatBatch(u,!0));let h=l.epilogue();if(h)d.push(h);return d.join("")}function Ee(e,t){let n=e.autoJoins,r=n&&n.length>0,s=or(e),i=t.qualifyTable(e.schema,e.table),o=r?He(n,t):void 0,a=ge(e.filters,t,0,o),c=he(e.sort,t,o);if(r){let d=Be(n,t),p="t0.*";if(s&&s.length>0)p=s.map((m)=>{if(m.includes("."))return`${o(m)} AS ${t.quoteIdentifier(m)}`;return`t0.${t.quoteIdentifier(m)}`}).join(", ");let h=[`SELECT ${p} FROM ${i} AS t0 ${d}`];if(a.sql)h.push(a.sql);if(c)h.push(c);return{sql:h.join(" "),params:[...a.params]}}let l=[`SELECT ${s&&s.length>0?s.map((d)=>t.quoteIdentifier(d)).join(", "):"*"} FROM ${i}`];if(a.sql)l.push(a.sql);if(c)l.push(c);return{sql:l.join(" "),params:[...a.params]}}function or(e){if(e.format!=="sql_update"||!e.columns||e.columns.length===0||!e.keyColumns)return e.columns;return xt(e.columns,e.keyColumns)}function Kt(e,t){return Lt({format:e.format,schema:e.schema,table:e.table,delimiter:e.delimiter,includeHeaders:e.includeHeaders,batchSize:e.batchSize,qualifiedTableName:t.qualifyTable(e.schema,e.table),quoteIdentifier:(n)=>t.quoteIdentifier(n),keyColumns:e.keyColumns})}function cr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t[n]=r<=255?r:63}return t}function lr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=255)t[n]=r;else t[n]=ar[r]??63}return t}function ur(e){switch(e){case"iso-8859-1":return cr;case"windows-1252":return lr;default:return(t)=>t}}var ir=1000,ar;var Ke=C(()=>{Ht();ye();ar={8364:128,8218:130,402:131,8222:132,8230:133,8224:134,8225:135,710:136,8240:137,352:138,8249:139,338:140,381:142,8216:145,8217:146,8220:147,8221:148,8226:149,8211:150,8212:151,732:152,8482:153,353:154,8250:155,339:156,382:158,376:159}});async function*Ye(e,t){let{delimiter:n,hasHeader:r,batchSize:s,maxRows:i,maxBufferSize:o=67108864}=t,a=new TextDecoder("utf-8"),c=e.getReader(),u="",l=0,d=!1,p="",h=[],m=1,g=null,y=0,E=[],f=!1;function S(w){if(w.length===1&&w[0]==="")return 0;if(g===null){if(r)return g=w,0;g=w.map((b,R)=>`col${R+1}`)}if(E.push(dr(w,g)),y++,i!==void 0&&y>=i)return 2;if(E.length>=s)return 1;return 0}try{while(!f){let w=await c.read();if(w.done)u+=a.decode(new Uint8Array(0),{stream:!1}),f=!0;else u+=a.decode(w.value,{stream:!0});if(u.length>o)throw new Se(`buffer size exceeded ${o/1048576}MB \u2014 possible malformed input or extremely large field`,m);while(l<u.length){let b=u[l];if(d)if(b==='"')if(l+1<u.length)if(u[l+1]==='"')p+='"',l+=2;else d=!1,l++;else if(f)d=!1,l++;else break;else{if(b===`
28
- `)m++;else if(b==="\r"){if(m++,l+1<u.length){if(u[l+1]===`
29
- `){p+=`\r
30
- `,l+=2;continue}}else if(!f)break}p+=b,l++}else if(b==='"')d=!0,l++;else if(b===n)h.push(p),p="",l++;else if(b==="\r"||b===`
31
- `){if(b==="\r")if(l+1<u.length){if(l++,u[l]===`
32
- `)l++}else if(f)l++;else break;else l++;h.push(p),p="",m++;let R=S(h);switch(h=[],R){case 2:if(E.length>0)yield{columns:g,rows:E},E=[];return;case 1:yield{columns:g,rows:E},E=[];break}}else p+=b,l++}if(l>0)u=u.slice(l),l=0}if(d)throw new Se("Unclosed quote",m);if(p!==""||h.length>0)h.push(p),S(h);if(E.length>0)yield{columns:g??[],rows:E}}finally{c.releaseLock()}}function dr(e,t){let n={};for(let r=0;r<t.length;r++){let s=r<e.length?e[r]:null;n[t[r]]=s===""?null:mr(s)}return n}function mr(e){if(e===null||e==="")return null;let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+$/.test(e)){let n=parseInt(e,10);if(Number.isSafeInteger(n))return n}if(/^-?\d+\.\d+$/.test(e)){let n=parseFloat(e);if(Number.isFinite(n))return n}return e}var Se;var Yt=C(()=>{Se=class Se extends Error{lineNumber;constructor(e,t){super(`CSV parse error at line ${t}: ${e}`);this.name="CsvParseError",this.lineNumber=t}}});async function be(e,t,n,r,s){let i=n.mappings.filter((d)=>d.tableColumn!==null);if(i.length===0)throw Error("No columns mapped for import");if(n.format==="json")return pr(e,t,n,i,r,s);let o=e.qualifyTable(n.schema,n.table),a=i.map((d)=>d.tableColumn),c=n.batchSize??jt,u={delimiter:n.delimiter??",",hasHeader:n.hasHeader??!0,batchSize:c},l=`__import_${crypto.randomUUID()}`;await e.reserveSession(l);try{await e.beginTransaction(l);let d=0;for await(let{rows:p}of Ye(t,u)){if(r?.aborted)throw Error("Import cancelled");let h=p.map((m)=>Jt(m,i));await e.importBatch(o,a,h,l),d+=p.length,s?.(d)}return await e.commit(l),{rowCount:d}}catch(d){try{await e.rollback(l)}catch(p){console.debug("Rollback after import error failed:",p instanceof Error?p.message:p)}throw d}finally{await e.releaseSession(l)}}async function Wt(e,t){let n=t.limit??20;if(t.format==="json")return fr(e);let r={delimiter:t.delimiter??",",hasHeader:t.hasHeader??!0,batchSize:n,maxRows:n},s=[],i=[];for await(let o of Ye(e,r))i=o.columns,s.push(...o.rows);return{fileColumns:i,rows:s.slice(0,n),totalRows:void 0}}async function pr(e,t,n,r,s,i){let o=await Vt(t),a=zt(o),c=e.qualifyTable(n.schema,n.table),u=r.map((p)=>p.tableColumn),l=n.batchSize??jt,d=`__import_${crypto.randomUUID()}`;await e.reserveSession(d);try{await e.beginTransaction(d);let p=0;for(let h=0;h<a.length;h+=l){if(s?.aborted)throw Error("Import cancelled");let m=a.slice(h,h+l),g=m.map((y)=>Jt(y,r));await e.importBatch(c,u,g,d),p+=m.length,i?.(p)}return await e.commit(d),{rowCount:p}}catch(p){try{await e.rollback(d)}catch(h){console.debug("Rollback after import error failed:",h instanceof Error?h.message:h)}throw p}finally{await e.releaseSession(d)}}async function fr(e){let t=await Vt(e),n=zt(t);return{fileColumns:gr(n),rows:n.slice(0,20),totalRows:n.length}}function zt(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error("JSON import expects an array of objects");let n=[];for(let r of t){if(typeof r!=="object"||r===null||Array.isArray(r))throw Error("Each JSON array element must be an object");n.push(r)}return n}function Jt(e,t){let n={};for(let r of t)n[r.tableColumn]=e[r.fileColumn]??null;return n}function gr(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}async function Vt(e){let t=e.getReader(),n=new TextDecoder("utf-8"),r="";while(!0){let{done:s,value:i}=await t.read();if(s)break;r+=n.decode(i,{stream:!0})}return r+=n.decode(new Uint8Array(0),{stream:!1}),t.releaseLock(),r}var jt=100;var je=C(()=>{Yt()});var T,D,we,N,_;var P=C(()=>{T=class T extends Error{code;constructor(e,t,n){super(t,n);this.name="DatabaseError",this.code=e}};D=class D extends T{constructor(e,t,n){super(e,t,n);this.name="ConnectionError"}};we=class we extends T{constructor(e,t){super("AUTH_FAILED",e,t);this.name="AuthenticationError"}};N=class N extends T{constructor(e,t,n){super(e,t,n);this.name="QueryError"}};_=class _ extends T{constructor(e,t,n){super(e,t,n);this.name="ConstraintError"}}});function Y(e){let t=[],n="",r=0;while(r<e.length){let i=e[r],o=r+1<e.length?e[r+1]:"";if(i==="-"&&o==="-"){let a=e.indexOf(`
33
- `,r);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+1),r=a+1;continue}if(i==="/"&&o==="*"){let a=e.indexOf("*/",r+2);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+2),r=a+2;continue}if(i==="$"){let a=e.slice(r).match(/^(\$[a-zA-Z0-9_]*\$)/);if(a){let c=a[1],u=e.indexOf(c,r+c.length);if(u===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,u+c.length),r=u+c.length;continue}}if(i==="'"){n+=i,r++;while(r<e.length)if(e[r]==="'")if(n+=e[r],r++,r<e.length&&e[r]==="'")n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i==='"'){n+=i,r++;while(r<e.length)if(e[r]==='"')if(n+=e[r],r++,r<e.length&&e[r]==='"')n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i===";"){let a=n.trim();if(a.length>0)t.push(a);n="",r++;continue}n+=i,r++}let s=n.trim();if(s.length>0)t.push(s);return t}function Ce(e,t){let n=1,r=1,s=Math.min(t-1,e.length);for(let i=0;i<s;i++)if(e[i]===`
34
- `)n++,r=1;else r++;return{line:n,column:r}}function te(e){let t="",n=0;while(n<e.length){let r=e[n],s=n+1<e.length?e[n+1]:"";if(r==="-"&&s==="-"){let i=e.indexOf(`
35
- `,n);t+=" ",n=i===-1?e.length:i+1;continue}if(r==="/"&&s==="*"){let i=e.indexOf("*/",n+2);t+=" ",n=i===-1?e.length:i+2;continue}if(r==="$"){let i=e.slice(n).match(/^(\$[a-zA-Z0-9_]*\$)/);if(i){let o=i[1],a=e.indexOf(o,n+o.length);t+=" ",n=a===-1?e.length:a+o.length;continue}}if(r==="'"){t+=" ",n++;while(n<e.length)if(e[n]==="'")if(n++,n<e.length&&e[n]==="'")n++;else break;else n++;continue}if(r==='"'){t+=" ",n++;while(n<e.length)if(e[n]==='"')if(n++,n<e.length&&e[n]==='"')n++;else break;else n++;continue}t+=r,n++}return t}function Te(e,t){if(!e||typeof e!=="object")return;let n=e;if(n.position!=null){let r=Number(n.position);if(!Number.isNaN(r)&&r>0){let{line:s,column:i}=Ce(t,r);return{line:s,column:i,offset:r}}}if(e instanceof Error){let r=e.message.match(/at offset (\d+)/);if(r){let s=Number(r[1])+1,{line:i,column:o}=Ce(t,s);return{line:i,column:o,offset:s}}}return}async function ne(e,t){let n=`__ephemeral_${crypto.randomUUID()}`;await e.reserveSession(n);try{return await t(n)}finally{try{await e.cancel(n)}catch{}try{await e.releaseSession(n)}catch{}}}class Gt{logs=new Map;pendingCounts=new Map;key(e,t){return t?`${e}:${t}`:e}pendingKey(e,t,n){let r=this.key(e,t);return n?`${r}:${n}`:r}add(e,t,n,r,s,i,o,a){let c=this.key(e,o);if(!this.logs.has(c))this.logs.set(c,[]);this.logs.get(c).push({id:crypto.randomUUID(),sql:t,status:n,durationMs:r,rowCount:s,errorMessage:i,executedAt:new Date().toISOString()});let u=this.pendingKey(e,o,a);this.pendingCounts.set(u,(this.pendingCounts.get(u)??0)+1);let l=t.trim().toUpperCase();if(/^(COMMIT|END|ROLLBACK)\b/.test(l)&&!/^ROLLBACK\s+TO\b/.test(l))this.resetPendingCount(e,o,a);else if(/^(BEGIN|START\s+TRANSACTION)\b/.test(l))this.resetPendingCount(e,o,a)}getEntries(e,t){return this.logs.get(this.key(e,t))??[]}getPendingCount(e,t,n){return this.pendingCounts.get(this.pendingKey(e,t,n))??0}resetPendingCount(e,t,n){this.pendingCounts.delete(this.pendingKey(e,t,n))}clear(e,t){let n=this.key(e,t);this.logs.delete(n),this.pendingCounts.delete(n);let r=`${n}:`;for(let s of this.pendingCounts.keys())if(s.startsWith(r))this.pendingCounts.delete(s)}}function vr(e){let t=te(e).replace(/\s+/g," ").trim().toUpperCase();return/^(BEGIN|START TRANSACTION|COMMIT|END|ROLLBACK|ABORT)\b/.test(t)&&!/^ROLLBACK TO\b/.test(t)&&!/^(COMMIT|ROLLBACK) PREPARED\b/.test(t)}class re{connectionManager;runningQueries=new Map;defaultTimeoutMs;appDb;sessionLog=new Gt;constructor(e,t=30000,n){this.connectionManager=e,this.defaultTimeoutMs=t,this.appDb=n}async executeQuery(e,t,n,r,s,i,o,a){let c=this.connectionManager.getDriver(e,i),u=Y(t);if(u.length===0)return[];if(!o&&u.some(vr))return[{columns:[],rows:[],rowCount:0,durationMs:0,error:"Transaction control statements (BEGIN, COMMIT, ROLLBACK) require a session. Open a session tab to use manual transactions."}];let l=async(d)=>{let p=s??crypto.randomUUID(),h={queryId:p,connectionId:e,database:i,cancelled:!1,sessionId:d};this.runningQueries.set(p,h);let m=r??this.defaultTimeoutMs,g=[],y;try{if(a&&d!==void 0){y=(await c.execute("SHOW search_path",void 0,d)).rows[0]?.search_path;let f=Ae(a,c);await c.execute(`SET search_path TO ${f}`,void 0,d)}for(let E of u){if(h.cancelled){g.push(We());break}let f=await this.executeSingle(c,E,u.length===1?n:void 0,m,h,d);if(g.push(f),f.error)break}}finally{if(y!==void 0&&d!==void 0)try{let E=Ae(y,c);await c.execute(`SET search_path TO ${E}`,void 0,d)}catch{}this.runningQueries.delete(p),this.logHistory(e,t,g,i,o)}return g};if(!o&&(u.length>1||a))return ne(c,l);return l(o)}async cancelQuery(e){let t=this.runningQueries.get(e);if(!t)return!1;t.cancelled=!0;try{let n=this.connectionManager.getDriver(t.connectionId,t.database);if(t.sessionId!==void 0)await n.cancel(t.sessionId);else await n.cancel(void 0,t.poolQueryKey)}catch(n){console.debug("Cancel query failed (driver may have completed):",n instanceof Error?n.message:n)}return!0}async cancelAllForConnection(e){let t=[];for(let[r,s]of this.runningQueries)if(s.connectionId===e)t.push(r);let n=0;for(let r of t)if(await this.cancelQuery(r))n++;return n}getRunningQueryIds(){return[...this.runningQueries.keys()]}async explainQuery(e,t,n,r,s,i){let o=this.connectionManager.getDriver(e,r),a=o.getDriverType(),c=performance.now(),u=async(l)=>{let d;try{if(i&&l!==void 0){d=(await o.execute("SHOW search_path",void 0,l)).rows[0]?.search_path;let R=Ae(i,o);await o.execute(`SET search_path TO ${R}`,void 0,l)}if(a==="sqlite"){let b=l!==void 0?await o.execute(`EXPLAIN QUERY PLAN ${t}`,void 0,l):await o.execute(`EXPLAIN QUERY PLAN ${t}`),R=Math.round(performance.now()-c),v=Rr(b.rows),x=b.rows.map((U)=>`${U.id}|${U.parent}|${U.notused??0}|${U.detail}`).join(`
36
- `);return{nodes:v,rawText:x,durationMs:R}}let p=a==="mysql",h=p?n?"EXPLAIN ANALYZE":"EXPLAIN FORMAT=JSON":n?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",m=l!==void 0?await o.execute(`${h} ${t}`,void 0,l):await o.execute(`${h} ${t}`),g=Math.round(performance.now()-c),y,E,f;if(p&&n)return f=m.rows.map((b)=>Object.values(b)[0]).join(`
37
- `),E=[{operation:f,children:[]}],{nodes:E,rawText:f,durationMs:g};let S=m.rows[0]?.["QUERY PLAN"]??m.rows[0]?.EXPLAIN??JSON.stringify(m.rows);if(y=typeof S==="string"?JSON.parse(S):S,E=(Array.isArray(y)?y:[y]).map((b)=>Xt(b.Plan??b)),n)f=JSON.stringify(y,null,2);else try{f=(l!==void 0?await o.execute(`EXPLAIN ${t}`,void 0,l):await o.execute(`EXPLAIN ${t}`)).rows.map((v)=>Object.values(v)[0]).join(`
38
- `)}catch{f=JSON.stringify(y,null,2)}return{nodes:E,rawText:f,durationMs:g}}catch(p){let h=Math.round(performance.now()-c);return{nodes:[],rawText:"",durationMs:h,error:p instanceof Error?p.message:String(p)}}finally{if(d!==void 0&&l!==void 0)try{let p=Ae(d,o);await o.execute(`SET search_path TO ${p}`,void 0,l)}catch{}}};if(!s&&i)return ne(o,u);return u(s)}async executeSingle(e,t,n,r,s,i){let o=performance.now(),c=r===0?null:this.createTimeout(r),u=i===void 0?Symbol():void 0;s.poolQueryKey=u;try{let l=i!==void 0?e.execute(t,n,i):e.execute(t,n,void 0,u),d=c?await Promise.race([l,c.promise]):await l;if(s.cancelled)return We(performance.now()-o);return{...d,durationMs:Math.round(performance.now()-o)}}catch(l){let d=Math.round(performance.now()-o);if(c?.fired)try{if(i!==void 0)await e.cancel(i);else await e.cancel(void 0,u)}catch{}if(s.cancelled)return We(d);if(c?.fired){let m=t.trim().toUpperCase();if(/^(COMMIT|END)\b/.test(m))return{columns:[],rows:[],rowCount:0,durationMs:d,errorCode:"COMMIT_UNCERTAIN",error:"Connection lost or timed out during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying."};if(/^(INSERT|UPDATE|DELETE|MERGE)\b/.test(m))return{columns:[],rows:[],rowCount:0,durationMs:d,errorCode:"STATEMENT_UNCERTAIN",error:"Statement timed out but may have been executed by the server. Verify your data before retrying."}}let p=Te(l,t),h=l instanceof T?l.code:void 0;return{columns:[],rows:[],rowCount:0,durationMs:d,error:l instanceof Error?l.message:String(l),errorCode:h,errorPosition:p}}finally{c?.cancel()}}createTimeout(e){let t,n=!1;return{promise:new Promise((s,i)=>{t=setTimeout(()=>{n=!0,i(Error(`Query timed out after ${e}ms`))},e)}),cancel:()=>clearTimeout(t),get fired(){return n}}}logHistory(e,t,n,r,s){let i=n.some((u)=>u.error),o=n.reduce((u,l)=>u+(l.durationMs??0),0),a=n.reduce((u,l)=>u+(l.affectedRows??l.rowCount),0),c=n.find((u)=>u.error)?.error;if(this.sessionLog.add(e,t,i?"error":"success",Math.round(o),a,c,r,s),!this.appDb)return;try{this.appDb.addHistory({connectionId:e,database:r,sql:t,status:i?"error":"success",durationMs:Math.round(o),rowCount:a,errorMessage:c})}catch(u){console.debug("History logging failed:",u instanceof Error?u.message:u)}}}function We(e=0){return{columns:[],rows:[],rowCount:0,durationMs:Math.round(e),error:"Query was cancelled"}}function Ae(e,t){return e.split(",").map((n)=>{let r=n.trim();if(r.startsWith('"')&&r.endsWith('"'))r=r.slice(1,-1).replace(/""/g,'"');return t.quoteIdentifier(r)}).join(", ")}function Xt(e){let t=e.Plans??[],{"Node Type":n,"Relation Name":r,Plans:s,...i}=e;return{operation:String(e["Node Type"]??"Unknown"),relation:e["Relation Name"]?String(e["Relation Name"]):void 0,cost:typeof e["Total Cost"]==="number"?e["Total Cost"]:void 0,actualTime:typeof e["Actual Total Time"]==="number"?e["Actual Total Time"]:void 0,estimatedRows:typeof e["Plan Rows"]==="number"?e["Plan Rows"]:void 0,actualRows:typeof e["Actual Rows"]==="number"?e["Actual Rows"]:void 0,extra:Object.keys(i).length>0?i:void 0,children:t.map((o)=>Xt(o))}}function Rr(e){let t=new Map,n=new Map;for(let r of e){let s=Number(r.id??r.selectid??0),i=Number(r.parent??0),o=String(r.detail??""),a={operation:o,children:[]},c=o.match(/^(SCAN|SEARCH|USE TEMP B-TREE)\s+(.*)/i);if(c){a.operation=c[1];let l=c[2].match(/^(\S+)/);if(l)a.relation=l[1]}if(t.set(s,a),!n.has(i))n.set(i,[]);n.get(i).push(a)}for(let[r,s]of t)s.children=n.get(r)??[];return n.get(0)??[...t.values()].filter((r,s)=>{let i=e[s],o=Number(i?.parent??0);return!t.has(o)})}var ze=C(()=>{P();ye()});function j(e){switch(e.type){case"postgresql":return e.database;case"sqlite":return e.path;case"mysql":return e.database}}function L(e){return M[e.type].hasHost}function Zt(e){if(!L(e))return e;let t={...e,password:""};if(t.type==="postgresql"&&t.sshTunnel)t.sshTunnel={...t.sshTunnel,password:t.sshTunnel.password!==void 0?"":void 0,keyPassphrase:t.sshTunnel.keyPassphrase!==void 0?"":void 0};return t}function en(e,t){if(!L(e))return e;let n={...e,password:t.password??e.password??""};if(n.type==="postgresql"&&n.sshTunnel)n.sshTunnel={...n.sshTunnel,password:t.sshPassword??n.sshTunnel.password,keyPassphrase:t.sshKeyPassphrase??n.sshTunnel.keyPassphrase};return n}var M;var se=C(()=>{M={postgresql:{label:"PostgreSQL",hasPassword:!0,hasHost:!0,defaultPort:5432,supportsMultiDatabase:!0},sqlite:{label:"SQLite",hasPassword:!1,hasHost:!1,supportsMultiDatabase:!1},mysql:{label:"MySQL",hasPassword:!0,hasHost:!0,defaultPort:3306,supportsMultiDatabase:!0}}});import{createCipheriv as Nr,createDecipheriv as Dr,hkdfSync as si,randomBytes as _r}from"crypto";class Ge{keyPromise;constructor(e){this.keyPromise=Or(e)}async encrypt(e){let t=await this.keyPromise,n=crypto.getRandomValues(new Uint8Array(Je)),r=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:Ve,iv:n},t,r),i=new Uint8Array(n.length+s.byteLength);return i.set(n,0),i.set(new Uint8Array(s),n.length),Buffer.from(i).toString("base64")}async decrypt(e){let t=await this.keyPromise,n=new Uint8Array(Buffer.from(e,"base64")),r=n.slice(0,Je),s=n.slice(Je),i=await crypto.subtle.decrypt({name:Ve,iv:r},t,s);return new TextDecoder().decode(i)}}async function Or(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new TextEncoder().encode("dotaz-encryption-salt"),info:new TextEncoder().encode("dotaz-aes-key")},n,{name:Ve,length:Ir},!1,["encrypt","decrypt"])}function W(e,t){let n=new Uint8Array(_r(ie)),r=Nr("aes-256-gcm",t,n),s=r.update(e,"utf8"),i=r.final(),o=new Uint8Array(r.getAuthTag()),a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length);let c=new Uint8Array(n.length+o.length+a.length);return c.set(n,0),c.set(o,n.length),c.set(a,n.length+o.length),ve+Buffer.from(c).toString("base64")}function xr(e,t){if(!e.startsWith(ve))return e;let n=new Uint8Array(Buffer.from(e.slice(ve.length),"base64")),r=n.subarray(0,ie),s=n.subarray(ie,ie+tn),i=n.subarray(ie+tn),o=Dr("aes-256-gcm",t,r);return o.setAuthTag(s),o.update(i).toString("utf8")+o.final("utf8")}function oe(e){return e.startsWith(ve)}function Re(e,t){try{return xr(e,t)}catch{return null}}var Ve="AES-GCM",Je=12,Ir=256,ve="enc:v1:",ie=12,tn=16;var Xe=()=>{};function kr(e){e.run(`
27
+ `}}var sn=()=>{};var Ii;var M=T(()=>{Ii=Object.freeze({__dotaz_sentinel:"DEFAULT"})});function we(e,t){let n=t.getDriverType()==="mysql"?"CHAR":"TEXT";return`CAST(${e} AS ${n})`}function Ve(e){return e.includes(".")}function Je(e){let t=e.indexOf(".");return{table:e.substring(0,t),column:e.substring(t+1)}}function Xe(e,t){return(n)=>{if(Ve(n)){let{table:r,column:s}=Je(n),i=e.find((o)=>o.referencedTable===r);if(i)return`${t.quoteIdentifier(i.alias)}.${t.quoteIdentifier(s)}`}return`t0.${t.quoteIdentifier(n)}`}}function Ee(e,t,n=0,r){if(!e||e.length===0)return{sql:"",params:[]};let s=[],i=[],o=n;for(let a of e){let c=r?r(a.column):t.quoteIdentifier(a.column);switch(a.operator){case"eq":o++,s.push(`${c} = ${t.placeholder(o)}`),i.push(a.value);break;case"neq":o++,s.push(`${c} != ${t.placeholder(o)}`),i.push(a.value);break;case"gt":o++,s.push(`${c} > ${t.placeholder(o)}`),i.push(a.value);break;case"gte":o++,s.push(`${c} >= ${t.placeholder(o)}`),i.push(a.value);break;case"lt":o++,s.push(`${c} < ${t.placeholder(o)}`),i.push(a.value);break;case"lte":o++,s.push(`${c} <= ${t.placeholder(o)}`),i.push(a.value);break;case"like":o++,s.push(`${c} LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"notLike":o++,s.push(`${c} NOT LIKE ${t.placeholder(o)}`),i.push(a.value);break;case"in":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} IN (${l.join(", ")})`),i.push(...u);break}case"notIn":{let u=Array.isArray(a.value)?a.value:[a.value],l=u.map(()=>(o++,t.placeholder(o)));s.push(`${c} NOT IN (${l.join(", ")})`),i.push(...u);break}case"isNull":s.push(`${c} IS NULL`);break;case"isNotNull":s.push(`${c} IS NOT NULL`);break}}if(s.length===0)return{sql:"",params:[]};return{sql:`WHERE ${s.join(" AND ")}`,params:i}}function be(e,t,n){if(!e||e.length===0)return"";return`ORDER BY ${e.map((s)=>{let i=n?n(s.column):t.quoteIdentifier(s.column),o=s.direction==="desc"?"DESC":"ASC";return`${i} ${o}`}).join(", ")}`}function Ze(e,t){return e.map((n)=>{let r=t.qualifyTable(n.referencedSchema,n.referencedTable),s=t.quoteIdentifier(n.alias),i;if(Ve(n.fkColumn)){let{table:a,column:c}=Je(n.fkColumn),u=e.find((l)=>l.referencedTable===a);if(u)i=`${t.quoteIdentifier(u.alias)}.${t.quoteIdentifier(c)}`;else i=`t0.${t.quoteIdentifier(n.fkColumn)}`}else i=`t0.${t.quoteIdentifier(n.fkColumn)}`;let o=`${s}.${t.quoteIdentifier(n.referencedColumn)}`;return`LEFT JOIN ${r} AS ${s} ON ${i} = ${o}`}).join(" ")}var Ce=T(()=>{M()});async function et(e,t,n,r,s){let i=Mr(t.format==="csv"?t.encoding:void 0),o=cn(t,e),a=0;if(t.format==="csv"&&t.utf8Bom&&(t.encoding??"utf-8")==="utf-8")await n.write(new Uint8Array([239,187,191]));let c=o.preamble();if(c)await n.write(i(c));let{sql:u,params:l}=Te(t,e),m=t.batchSize??Ir,f=e.iterate(u,l,m,r),g=!0;for await(let h of f){let y=h;if(t.limit!==void 0){let p=t.limit-a;if(p<=0)break;if(y.length>p)y=y.slice(0,p)}let w=o.formatBatch(y,g);if(await n.write(i(w)),a+=y.length,s?.(a),g=!1,t.limit!==void 0&&a>=t.limit)break}let d=o.epilogue();if(d)await n.write(i(d));return await n.end(),{rowCount:a}}async function on(e,t,n,r,s){let o=Bun.file(n).writer(),a={write(c){o.write(c)},async end(){await o.end()}};try{let c=await et(e,t,a,r,s),u=await Bun.file(n).stat();return{rowCount:c.rowCount,sizeBytes:u?.size??0}}catch(c){await o.end();try{let{unlink:u}=await import("fs/promises");await u(n)}catch{}throw c}}async function an(e,t){let n=t.limit??10,{sql:r,params:s}=Te(t,e),i=s.length;i++;let o=e.placeholder(i),a=`${r} LIMIT ${o}`,u=(await e.execute(a,[...s,n])).rows,l=cn(t,e),m=[],f=l.preamble();if(f)m.push(f);m.push(l.formatBatch(u,!0));let g=l.epilogue();if(g)m.push(g);return m.join("")}function Te(e,t){let n=e.autoJoins,r=n&&n.length>0,s=xr(e),i=t.qualifyTable(e.schema,e.table),o=r?Xe(n,t):void 0,a=Ee(e.filters,t,0,o),c=be(e.sort,t,o);if(r){let m=Ze(n,t),f="t0.*";if(s&&s.length>0)f=s.map((d)=>{if(d.includes("."))return`${o(d)} AS ${t.quoteIdentifier(d)}`;return`t0.${t.quoteIdentifier(d)}`}).join(", ");let g=[`SELECT ${f} FROM ${i} AS t0 ${m}`];if(a.sql)g.push(a.sql);if(c)g.push(c);return{sql:g.join(" "),params:[...a.params]}}let l=[`SELECT ${s&&s.length>0?s.map((m)=>t.quoteIdentifier(m)).join(", "):"*"} FROM ${i}`];if(a.sql)l.push(a.sql);if(c)l.push(c);return{sql:l.join(" "),params:[...a.params]}}function xr(e){if(e.format!=="sql_update"||!e.columns||e.columns.length===0||!e.keyColumns)return e.columns;return Gt(e.columns,e.keyColumns)}function cn(e,t){return Vt({format:e.format,schema:e.schema,table:e.table,delimiter:e.delimiter,includeHeaders:e.includeHeaders,batchSize:e.batchSize,qualifiedTableName:t.qualifyTable(e.schema,e.table),quoteIdentifier:(n)=>t.quoteIdentifier(n),keyColumns:e.keyColumns})}function Pr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t[n]=r<=255?r:63}return t}function kr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<=255)t[n]=r;else t[n]=Lr[r]??63}return t}function Mr(e){switch(e){case"iso-8859-1":return Pr;case"windows-1252":return kr;default:return(t)=>t}}var Ir=1000,Lr;var tt=T(()=>{sn();Ce();Lr={8364:128,8218:130,402:131,8222:132,8230:133,8224:134,8225:135,710:136,8240:137,352:138,8249:139,338:140,381:142,8216:145,8217:146,8220:147,8221:148,8226:149,8211:150,8212:151,732:152,8482:153,353:154,8250:155,339:156,382:158,376:159}});async function*nt(e,t){let{delimiter:n,hasHeader:r,batchSize:s,maxRows:i,maxBufferSize:o=67108864}=t,a=new TextDecoder("utf-8"),c=e.getReader(),u="",l=0,m=!1,f="",g=[],d=1,h=null,y=0,w=[],p=!1;function S(E){if(E.length===1&&E[0]==="")return 0;if(h===null){if(r)return h=E,0;h=E.map((C,N)=>`col${N+1}`)}if(w.push(Ur(E,h)),y++,i!==void 0&&y>=i)return 2;if(w.length>=s)return 1;return 0}try{while(!p){let E=await c.read();if(E.done)u+=a.decode(new Uint8Array(0),{stream:!1}),p=!0;else u+=a.decode(E.value,{stream:!0});if(u.length>o)throw new Ae(`buffer size exceeded ${o/1048576}MB \u2014 possible malformed input or extremely large field`,d);while(l<u.length){let C=u[l];if(m)if(C==='"')if(l+1<u.length)if(u[l+1]==='"')f+='"',l+=2;else m=!1,l++;else if(p)m=!1,l++;else break;else{if(C===`
28
+ `)d++;else if(C==="\r"){if(d++,l+1<u.length){if(u[l+1]===`
29
+ `){f+=`\r
30
+ `,l+=2;continue}}else if(!p)break}f+=C,l++}else if(C==='"')m=!0,l++;else if(C===n)g.push(f),f="",l++;else if(C==="\r"||C===`
31
+ `){if(C==="\r")if(l+1<u.length){if(l++,u[l]===`
32
+ `)l++}else if(p)l++;else break;else l++;g.push(f),f="",d++;let N=S(g);switch(g=[],N){case 2:if(w.length>0)yield{columns:h,rows:w},w=[];return;case 1:yield{columns:h,rows:w},w=[];break}}else f+=C,l++}if(l>0)u=u.slice(l),l=0}if(m)throw new Ae("Unclosed quote",d);if(f!==""||g.length>0)g.push(f),S(g);if(w.length>0)yield{columns:h??[],rows:w}}finally{c.releaseLock()}}function Ur(e,t){let n={};for(let r=0;r<t.length;r++){let s=r<e.length?e[r]:null;n[t[r]]=s===""?null:$r(s)}return n}function $r(e){if(e===null||e==="")return null;let t=e.toLowerCase();if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+$/.test(e)){let n=parseInt(e,10);if(Number.isSafeInteger(n))return n}if(/^-?\d+\.\d+$/.test(e)){let n=parseFloat(e);if(Number.isFinite(n))return n}return e}var Ae;var ln=T(()=>{Ae=class Ae extends Error{lineNumber;constructor(e,t){super(`CSV parse error at line ${t}: ${e}`);this.name="CsvParseError",this.lineNumber=t}}});async function ve(e,t,n,r,s){let i=n.mappings.filter((m)=>m.tableColumn!==null);if(i.length===0)throw Error("No columns mapped for import");if(n.format==="json")return qr(e,t,n,i,r,s);let o=e.qualifyTable(n.schema,n.table),a=i.map((m)=>m.tableColumn),c=n.batchSize??un,u={delimiter:n.delimiter??",",hasHeader:n.hasHeader??!0,batchSize:c},l=`__import_${crypto.randomUUID()}`;await e.reserveSession(l);try{await e.beginTransaction(l);let m=0;for await(let{rows:f}of nt(t,u)){if(r?.aborted)throw Error("Import cancelled");let g=f.map((d)=>pn(d,i));await e.importBatch(o,a,g,l),m+=f.length,s?.(m)}return await e.commit(l),{rowCount:m}}catch(m){try{await e.rollback(l)}catch(f){console.debug("Rollback after import error failed:",f instanceof Error?f.message:f)}throw m}finally{await e.releaseSession(l)}}async function dn(e,t){let n=t.limit??20;if(t.format==="json")return Fr(e);let r={delimiter:t.delimiter??",",hasHeader:t.hasHeader??!0,batchSize:n,maxRows:n},s=[],i=[];for await(let o of nt(e,r))i=o.columns,s.push(...o.rows);return{fileColumns:i,rows:s.slice(0,n),totalRows:void 0}}async function qr(e,t,n,r,s,i){let o=await fn(t),a=mn(o),c=e.qualifyTable(n.schema,n.table),u=r.map((f)=>f.tableColumn),l=n.batchSize??un,m=`__import_${crypto.randomUUID()}`;await e.reserveSession(m);try{await e.beginTransaction(m);let f=0;for(let g=0;g<a.length;g+=l){if(s?.aborted)throw Error("Import cancelled");let d=a.slice(g,g+l),h=d.map((y)=>pn(y,r));await e.importBatch(c,u,h,m),f+=d.length,i?.(f)}return await e.commit(m),{rowCount:f}}catch(f){try{await e.rollback(m)}catch(g){console.debug("Rollback after import error failed:",g instanceof Error?g.message:g)}throw f}finally{await e.releaseSession(m)}}async function Fr(e){let t=await fn(e),n=mn(t);return{fileColumns:Hr(n),rows:n.slice(0,20),totalRows:n.length}}function mn(e){let t=JSON.parse(e);if(!Array.isArray(t))throw Error("JSON import expects an array of objects");let n=[];for(let r of t){if(typeof r!=="object"||r===null||Array.isArray(r))throw Error("Each JSON array element must be an object");n.push(r)}return n}function pn(e,t){let n={};for(let r of t)n[r.tableColumn]=e[r.fileColumn]??null;return n}function Hr(e){let t=new Set,n=[];for(let r of e)for(let s of Object.keys(r))if(!t.has(s))t.add(s),n.push(s);return n}async function fn(e){let t=e.getReader(),n=new TextDecoder("utf-8"),r="";while(!0){let{done:s,value:i}=await t.read();if(s)break;r+=n.decode(i,{stream:!0})}return r+=n.decode(new Uint8Array(0),{stream:!1}),t.releaseLock(),r}var un=100;var rt=T(()=>{ln()});function Re(e){return e.columns.length>0?e.rowCount:e.affectedRows??e.rowCount}function j(e){if(e===void 0||e==="")return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t>=128}function H(e){let t=[],n="",r=0;while(r<e.length){let i=e[r],o=r+1<e.length?e[r+1]:"";if(i==="-"&&o==="-"){let a=e.indexOf(`
33
+ `,r);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+1),r=a+1;continue}if(i==="/"&&o==="*"){let a=e.indexOf("*/",r+2);if(a===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,a+2),r=a+2;continue}if(i==="$"&&!j(e[r-1])){let a=e.slice(r).match(/^(\$[a-zA-Z0-9_]*\$)/);if(a){let c=a[1],u=e.indexOf(c,r+c.length);if(u===-1)n+=e.slice(r),r=e.length;else n+=e.slice(r,u+c.length),r=u+c.length;continue}}if(i==="'"){n+=i,r++;while(r<e.length)if(e[r]==="'")if(n+=e[r],r++,r<e.length&&e[r]==="'")n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i==='"'){n+=i,r++;while(r<e.length)if(e[r]==='"')if(n+=e[r],r++,r<e.length&&e[r]==='"')n+=e[r],r++;else break;else n+=e[r],r++;continue}if(i===";"){let a=n.trim();if(a.length>0)t.push(a);n="",r++;continue}n+=i,r++}let s=n.trim();if(s.length>0)t.push(s);return t}function Ne(e,t){let n=1,r=1,s=Math.min(t-1,e.length);for(let i=0;i<s;i++)if(e[i]===`
34
+ `)n++,r=1;else r++;return{line:n,column:r}}function z(e){let t="",n=0;while(n<e.length){let r=e[n],s=n+1<e.length?e[n+1]:"";if(r==="-"&&s==="-"){let i=e.indexOf(`
35
+ `,n);t+=" ",n=i===-1?e.length:i+1;continue}if(r==="/"&&s==="*"){let i=e.indexOf("*/",n+2);t+=" ",n=i===-1?e.length:i+2;continue}if(r==="$"&&!j(e[n-1])){let i=e.slice(n).match(/^(\$[a-zA-Z0-9_]*\$)/);if(i){let o=i[1],a=e.indexOf(o,n+o.length);t+=" ",n=a===-1?e.length:a+o.length;continue}}if(r==="'"){t+=" ",n++;while(n<e.length)if(e[n]==="'")if(n++,n<e.length&&e[n]==="'")n++;else break;else n++;continue}if(r==='"'){t+=" ",n++;while(n<e.length)if(e[n]==='"')if(n++,n<e.length&&e[n]==='"')n++;else break;else n++;continue}t+=r,n++}return t}function jr(e){return st(zr(e))}function gn(e){let t=H(e);if(t.length===0)return!1;return t.every((n)=>jr(n)==="read")}function zr(e){return z(e).replace(/\s+/g," ").trim().toUpperCase()}function st(e){let t=e.replace(/^[(\s]+/,""),n=t.match(/^[A-Z_]+/)?.[0];if(!n)return"unknown";if(/\bSET_CONFIG\s*\(/.test(t))return"unknown";if(n==="WITH"){let r=Gr(t);if(r===null)return"unknown";let s=Vr(t.slice(0,r));if(s!=="read")return s;return st(t.slice(r))}if(n==="EXPLAIN")return Xr(t);if(n==="PRAGMA")return Jr(t);if(n==="COPY")return/\bFROM\b/.test(t)?"write":"unknown";if(n==="SELECT"&&/\bINTO\b/.test(t))return"unknown";if(Br.has(n))return"read";if(Qr.has(n))return"write";if(hn.has(n))return"ddl";return"unknown"}function Gr(e){let t=0,n=-1;for(let r=0;r<=e.length;r++){let s=r<e.length?e[r]:" ";if(s==="("||s===")"){t+=s==="("?1:-1,n=-1;continue}if(/[A-Z0-9_]/.test(s)){if(n===-1)n=r;continue}if(n!==-1&&t===0&&Yr.has(e.slice(n,r)))return n;n=-1}return null}function Vr(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===")"){t--;continue}if(r!=="(")continue;if(t++,t!==1)continue;let s=e.slice(n+1).match(/^\s*([A-Z_]+)/)?.[1];if(!s)continue;if(Kr.has(s))return"write";if(hn.has(s))return"ddl";if(s==="WITH")return"unknown"}return"read"}function Jr(e){if(e.includes("="))return"unknown";let t=e.match(/^PRAGMA\s+(?:[A-Z0-9_]+\s*\.\s*)?([A-Z0-9_]+)\s*(\()?/);if(!t)return"unknown";if(!t[2])return"read";return Wr.has(t[1])?"read":"unknown"}function Xr(e){let t=e.slice(7).trim(),n=!1;if(t.startsWith("(")){let r=Zr(t);if(r===-1)return"unknown";let s=t.slice(1,r);n=/\bANALYZE\b/.test(s)&&!/\bANALYZE\s+(FALSE|OFF|0)\b/.test(s),t=t.slice(r+1).trim()}else while(!0){let r=t.match(/^(ANALYZE|VERBOSE|QUERY PLAN|EXTENDED|PARTITIONS|FORMAT\s*=\s*[A-Z]+)\b\s*/);if(!r)break;if(r[1]==="ANALYZE")n=!0;t=t.slice(r[0].length)}if(!n)return"read";if(t.length===0)return"unknown";return st(t)}function Zr(e){let t=0;for(let n=0;n<e.length;n++)if(e[n]==="(")t++;else if(e[n]===")"&&--t===0)return n;return-1}function De(e,t){if(!e||typeof e!=="object")return;let n=e;if(n.position!=null){let r=Number(n.position);if(!Number.isNaN(r)&&r>0){let{line:s,column:i}=Ne(t,r);return{line:s,column:i,offset:r}}}if(e instanceof Error){let r=e.message.match(/at offset (\d+)/);if(r){let s=Number(r[1])+1,{line:i,column:o}=Ne(t,s);return{line:i,column:o,offset:s}}}return}var Br,Qr,hn,Yr,Kr,Wr;var G=T(()=>{Br=new Set(["SELECT","SHOW","DESCRIBE","DESC","VALUES","TABLE"]),Qr=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE","TRUNCATE","CALL","DO"]),hn=new Set(["CREATE","ALTER","DROP","GRANT","REVOKE","VACUUM","REINDEX","ATTACH","DETACH"]),Yr=new Set(["SELECT","INSERT","UPDATE","DELETE","MERGE","REPLACE","VALUES","TABLE"]),Kr=new Set(["INSERT","UPDATE","DELETE","MERGE","REPLACE"]),Wr=new Set(["TABLE_INFO","TABLE_XINFO","TABLE_LIST","INDEX_LIST","INDEX_INFO","INDEX_XINFO","FOREIGN_KEY_LIST","FOREIGN_KEY_CHECK","DATABASE_LIST","COLLATION_LIST","FUNCTION_LIST","MODULE_LIST","PRAGMA_LIST","COMPILE_OPTIONS","INTEGRITY_CHECK","QUICK_CHECK"])});function _e(e,t){if(t===void 0)return Sn.every((r)=>_e(e,r));let n=wn(e,t,{allowComments:!0});if(n===null)return!1;for(let r=0;r<n.length;r++){if(n[r]!==";")continue;for(let s=r+1;s<n.length;s++){let i=n[s];if(i===";"||i===" "||i==="\t"||i===`
36
+ `||i==="\r"||i==="\f"||i==="\v")continue;return!1}return!0}return!0}function ot(e,t){if(t===void 0)return Sn.every((s)=>ot(e,s));let n=wn(e,t,{allowComments:!1});if(n===null)return!1;let r=0;for(let s of n){if(s===";")return!1;if(s==="(")r++;if(s===")"&&--r<0)return!1}return r===0}function wn(e,t,n){let r=t==="mysql",s=t==="postgresql",i=t==="sqlite",o=r||s,a=r,c=s,u=r||i,l=i,m=r,f=r,g="",d=0,h=e.length;while(d<h){let y=e[d],w=d+1<h?e[d+1]:"";if(y==="-"&&w==="-"){let p=!0;if(f&&d+2<h){let S=e.charCodeAt(d+2);if(S>127)return null;p=S<=32||S===127}if(p){if(!n.allowComments)return null;let S=yn(e,d);if(S===null)return null;g+=" ",d=S;continue}}if(y==="#"&&m){if(!n.allowComments)return null;let p=yn(e,d);if(p===null)return null;g+=" ",d=p;continue}if(y==="/"&&w==="*"){if(!n.allowComments)return null;if(r&&/^[!+]|^[Mm]!/.test(e.slice(d+2,d+4)))return null;if(s){let S=0,E=d;while(E<h)if(e[E]==="/"&&e[E+1]==="*")S++,E+=2;else if(e[E]==="*"&&e[E+1]==="/"){if(S--,E+=2,S===0)break}else E++;if(S!==0)return null;g+=" ",d=E;continue}let p=e.indexOf("*/",d+2);g+=" ",d=p===-1?h:p+2;continue}if(y==="$"&&c){let p=es(e,d);if(p){let S=d>0?e[d-1]:"";if(j(S)||S==="$")return null;let E=e.indexOf(p,d+p.length);if(E===-1)return null;g+=" ",d=E+p.length;continue}}if(i&&(y==="$"||y==="@"||y===":"||y==="#")){let p=d+1,S=0;while(p<h)if(j(e[p])||e[p]==="$")S++,p++;else if(e[p]===":"&&e[p+1]===":")p+=2;else break;if(e[p]==="("&&S>0)return null}if(y==="'"){let p=it(e,d,"'",o);if(p===-1)return null;g+=" ",d=p;continue}if(y==='"'){let p=it(e,d,'"',a);if(p===-1)return null;g+=" ",d=p;continue}if(y==="`"&&u){let p=it(e,d,"`",!1);if(p===-1)return null;g+=" ",d=p;continue}if(y==="["&&l){let p=e.indexOf("]",d+1);if(p===-1)return null;g+=" ",d=p+1;continue}g+=y,d++}return g}function yn(e,t){for(let n=t;n<e.length;n++){if(e[n]===`
37
+ `)return n+1;if(e[n]==="\r"&&e[n+1]!==`
38
+ `)return null}return e.length}function es(e,t){if(e[t]!=="$")return null;let n=e.charCodeAt(t+1);if(n>=48&&n<=57)return null;let r=t+1;while(r<e.length&&j(e[r]))r++;if(e[r]!=="$")return null;return e.slice(t,r+1)}function it(e,t,n,r){let s=t+1;while(s<e.length){let i=e[s];if(r&&i==="\\")return-1;if(i===n){if(e[s+1]===n){s+=2;continue}return s+1}s++}return-1}var Sn;var at=T(()=>{G();Sn=["postgresql","mysql","sqlite"]});async function ae(e,t){let n=`__ephemeral_${crypto.randomUUID()}`;await e.reserveSession(n);try{return await t(n)}finally{try{await e.cancel(n)}catch{}try{await e.releaseSession(n)}catch{}}}class bn{logs=new Map;pendingCounts=new Map;key(e,t){return t?`${e}:${t}`:e}pendingKey(e,t,n){let r=this.key(e,t);return n?`${r}:${n}`:r}add(e,t,n,r,s,i,o,a){let c=this.key(e,o);if(!this.logs.has(c))this.logs.set(c,[]);this.logs.get(c).push({id:crypto.randomUUID(),sql:t,status:n,durationMs:r,rowCount:s,errorMessage:i,executedAt:new Date().toISOString()});let u=this.pendingKey(e,o,a);this.pendingCounts.set(u,(this.pendingCounts.get(u)??0)+1);let l=t.trim().toUpperCase();if(/^(COMMIT|END|ROLLBACK)\b/.test(l)&&!/^ROLLBACK\s+TO\b/.test(l))this.resetPendingCount(e,o,a);else if(/^(BEGIN|START\s+TRANSACTION)\b/.test(l))this.resetPendingCount(e,o,a)}getEntries(e,t){return this.logs.get(this.key(e,t))??[]}getPendingCount(e,t,n){return this.pendingCounts.get(this.pendingKey(e,t,n))??0}resetPendingCount(e,t,n){this.pendingCounts.delete(this.pendingKey(e,t,n))}clear(e,t){let n=this.key(e,t);this.logs.delete(n),this.pendingCounts.delete(n);let r=`${n}:`;for(let s of this.pendingCounts.keys())if(s.startsWith(r))this.pendingCounts.delete(s)}}function us(e){let t=z(e).replace(/\s+/g," ").trim().toUpperCase();return/^(BEGIN|START TRANSACTION|COMMIT|END|ROLLBACK|ABORT)\b/.test(t)&&!/^ROLLBACK TO\b/.test(t)&&!/^(COMMIT|ROLLBACK) PREPARED\b/.test(t)}function Ie(e,t,n){if(n===void 0||!e.isSessionReadOnly(n))return;if(!_e(t,e.getDriverType()))throw new b("READ_ONLY_SESSION",En);if(gn(t))return;throw new b("READ_ONLY_SESSION",En)}class ce{connectionManager;runningQueries=new Map;defaultTimeoutMs;appDb;sessionLog=new bn;constructor(e,t=30000,n){this.connectionManager=e,this.defaultTimeoutMs=t,this.appDb=n}async executeQuery(e,t,n,r,s,i,o,a){let c=this.connectionManager.getDriver(e,i),u=H(t);if(u.length===0)return[];if(Ie(c,t,o),!o&&u.some(us))return[{columns:[],rows:[],rowCount:0,durationMs:0,error:"Transaction control statements (BEGIN, COMMIT, ROLLBACK) require a session. Open a session tab to use manual transactions."}];let l=async(m)=>{let f=s??crypto.randomUUID(),g={queryId:f,connectionId:e,database:i,cancelled:!1,sessionId:m};this.runningQueries.set(f,g);let d=r??this.defaultTimeoutMs,h=[],y;try{if(a&&m!==void 0){y=(await c.execute("SHOW search_path",void 0,m)).rows[0]?.search_path;let p=Oe(a,c);await c.execute(`SET search_path TO ${p}`,void 0,m)}for(let w of u){if(g.cancelled){h.push(ct());break}let p=await this.executeSingle(c,w,u.length===1?n:void 0,d,g,m);if(h.push(p),p.error)break}}finally{if(y!==void 0&&m!==void 0)try{let w=Oe(y,c);await c.execute(`SET search_path TO ${w}`,void 0,m)}catch{}this.runningQueries.delete(f),this.logHistory(e,t,h,i,o)}return h};if(!o&&(u.length>1||a))return ae(c,l);return l(o)}async cancelQuery(e){let t=this.runningQueries.get(e);if(!t)return!1;t.cancelled=!0;try{let n=this.connectionManager.getDriver(t.connectionId,t.database);if(t.sessionId!==void 0)await n.cancel(t.sessionId);else await n.cancel(void 0,t.poolQueryKey)}catch(n){console.debug("Cancel query failed (driver may have completed):",n instanceof Error?n.message:n)}return!0}async cancelAllForConnection(e){let t=[];for(let[r,s]of this.runningQueries)if(s.connectionId===e)t.push(r);let n=0;for(let r of t)if(await this.cancelQuery(r))n++;return n}getRunningQueryIds(){return[...this.runningQueries.keys()]}async explainQuery(e,t,n,r,s,i){let o=this.connectionManager.getDriver(e,r),a=o.getDriverType();if(!_e(t,a))throw Error("EXPLAIN takes a single statement \u2014 select the one to explain");Ie(o,`EXPLAIN ${n?"ANALYZE ":""}${t}`,s);let c=performance.now(),u=async(l)=>{let m;try{if(i&&l!==void 0){m=(await o.execute("SHOW search_path",void 0,l)).rows[0]?.search_path;let N=Oe(i,o);await o.execute(`SET search_path TO ${N}`,void 0,l)}if(a==="sqlite"){let C=l!==void 0?await o.execute(`EXPLAIN QUERY PLAN ${t}`,void 0,l):await o.execute(`EXPLAIN QUERY PLAN ${t}`),N=Math.round(performance.now()-c),v=ds(C.rows),L=C.rows.map((q)=>`${q.id}|${q.parent}|${q.notused??0}|${q.detail}`).join(`
39
+ `);return{nodes:v,rawText:L,durationMs:N}}let f=a==="mysql",g=f?n?"EXPLAIN ANALYZE":"EXPLAIN FORMAT=JSON":n?"EXPLAIN (ANALYZE, FORMAT JSON)":"EXPLAIN (FORMAT JSON)",d=l!==void 0?await o.execute(`${g} ${t}`,void 0,l):await o.execute(`${g} ${t}`),h=Math.round(performance.now()-c),y,w,p;if(f&&n)return p=d.rows.map((C)=>Object.values(C)[0]).join(`
40
+ `),w=[{operation:p,children:[]}],{nodes:w,rawText:p,durationMs:h};let S=d.rows[0]?.["QUERY PLAN"]??d.rows[0]?.EXPLAIN??JSON.stringify(d.rows);if(y=typeof S==="string"?JSON.parse(S):S,w=(Array.isArray(y)?y:[y]).map((C)=>Cn(C.Plan??C)),n)p=JSON.stringify(y,null,2);else try{p=(l!==void 0?await o.execute(`EXPLAIN ${t}`,void 0,l):await o.execute(`EXPLAIN ${t}`)).rows.map((v)=>Object.values(v)[0]).join(`
41
+ `)}catch{p=JSON.stringify(y,null,2)}return{nodes:w,rawText:p,durationMs:h}}catch(f){let g=Math.round(performance.now()-c);return{nodes:[],rawText:"",durationMs:g,error:f instanceof Error?f.message:String(f)}}finally{if(m!==void 0&&l!==void 0)try{let f=Oe(m,o);await o.execute(`SET search_path TO ${f}`,void 0,l)}catch{}}};if(!s&&i)return ae(o,u);return u(s)}async executeSingle(e,t,n,r,s,i){let o=performance.now(),c=r===0?null:this.createTimeout(r),u=i===void 0?Symbol():void 0;s.poolQueryKey=u;try{let l=i!==void 0?e.execute(t,n,i):e.execute(t,n,void 0,u),m=c?await Promise.race([l,c.promise]):await l;if(s.cancelled)return ct(performance.now()-o);return{...m,durationMs:Math.round(performance.now()-o)}}catch(l){let m=Math.round(performance.now()-o);if(c?.fired)try{if(i!==void 0)await e.cancel(i);else await e.cancel(void 0,u)}catch{}if(s.cancelled)return ct(m);if(c?.fired){let d=t.trim().toUpperCase();if(/^(COMMIT|END)\b/.test(d))return{columns:[],rows:[],rowCount:0,durationMs:m,errorCode:"COMMIT_UNCERTAIN",error:"Connection lost or timed out during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying."};if(/^(INSERT|UPDATE|DELETE|MERGE)\b/.test(d))return{columns:[],rows:[],rowCount:0,durationMs:m,errorCode:"STATEMENT_UNCERTAIN",error:"Statement timed out but may have been executed by the server. Verify your data before retrying."}}let f=De(l,t),g=l instanceof b?l.code:void 0;return{columns:[],rows:[],rowCount:0,durationMs:m,error:l instanceof Error?l.message:String(l),errorCode:g,errorPosition:f}}finally{c?.cancel()}}createTimeout(e){let t,n=!1;return{promise:new Promise((s,i)=>{t=setTimeout(()=>{n=!0,i(Error(`Query timed out after ${e}ms`))},e)}),cancel:()=>clearTimeout(t),get fired(){return n}}}logHistory(e,t,n,r,s){let i=n.some((u)=>u.error),o=n.reduce((u,l)=>u+(l.durationMs??0),0),a=n.reduce((u,l)=>u+Re(l),0),c=n.find((u)=>u.error)?.error;if(this.sessionLog.add(e,t,i?"error":"success",Math.round(o),a,c,r,s),!this.appDb)return;try{this.appDb.addHistory({connectionId:e,database:r,sql:t,status:i?"error":"success",durationMs:Math.round(o),rowCount:a,errorMessage:c})}catch(u){console.debug("History logging failed:",u instanceof Error?u.message:u)}}}function ct(e=0){return{columns:[],rows:[],rowCount:0,durationMs:Math.round(e),error:"Query was cancelled"}}function Oe(e,t){return e.split(",").map((n)=>{let r=n.trim();if(r.startsWith('"')&&r.endsWith('"'))r=r.slice(1,-1).replace(/""/g,'"');return t.quoteIdentifier(r)}).join(", ")}function Cn(e){let t=e.Plans??[],{"Node Type":n,"Relation Name":r,Plans:s,...i}=e;return{operation:String(e["Node Type"]??"Unknown"),relation:e["Relation Name"]?String(e["Relation Name"]):void 0,cost:typeof e["Total Cost"]==="number"?e["Total Cost"]:void 0,actualTime:typeof e["Actual Total Time"]==="number"?e["Actual Total Time"]:void 0,estimatedRows:typeof e["Plan Rows"]==="number"?e["Plan Rows"]:void 0,actualRows:typeof e["Actual Rows"]==="number"?e["Actual Rows"]:void 0,extra:Object.keys(i).length>0?i:void 0,children:t.map((o)=>Cn(o))}}function ds(e){let t=new Map,n=new Map;for(let r of e){let s=Number(r.id??r.selectid??0),i=Number(r.parent??0),o=String(r.detail??""),a={operation:o,children:[]},c=o.match(/^(SCAN|SEARCH|USE TEMP B-TREE)\s+(.*)/i);if(c){a.operation=c[1];let l=c[2].match(/^(\S+)/);if(l)a.relation=l[1]}if(t.set(s,a),!n.has(i))n.set(i,[]);n.get(i).push(a)}for(let[r,s]of t)s.children=n.get(r)??[];return n.get(0)??[...t.values()].filter((r,s)=>{let i=e[s],o=Number(i?.parent??0);return!t.has(o)})}var En="This session is read-only and cannot execute writes. Submit the statement with `dotaz propose` so it can be approved and run in the app.";var xe=T(()=>{at();G();P();Ce();G()});function V(e){switch(e.type){case"postgresql":return e.database;case"sqlite":return e.path;case"mysql":return e.database}}function k(e){return U[e.type].hasHost}function Tn(e){if(!k(e))return e;let t={...e,password:""};if(t.type==="postgresql"&&t.sshTunnel)t.sshTunnel={...t.sshTunnel,password:t.sshTunnel.password!==void 0?"":void 0,keyPassphrase:t.sshTunnel.keyPassphrase!==void 0?"":void 0};return t}function An(e,t){if(!k(e))return e;let n={...e,password:t.password??e.password??""};if(n.type==="postgresql"&&n.sshTunnel)n.sshTunnel={...n.sshTunnel,password:t.sshPassword??n.sshTunnel.password,keyPassphrase:t.sshKeyPassphrase??n.sshTunnel.keyPassphrase};return n}var U;var le=T(()=>{U={postgresql:{label:"PostgreSQL",hasPassword:!0,hasHost:!0,defaultPort:5432,supportsMultiDatabase:!0},sqlite:{label:"SQLite",hasPassword:!1,hasHost:!1,supportsMultiDatabase:!1},mysql:{label:"MySQL",hasPassword:!0,hasHost:!0,defaultPort:3306,supportsMultiDatabase:!0}}});import{createCipheriv as ms,createDecipheriv as ps,hkdfSync as io,randomBytes as fs}from"crypto";class dt{keyPromise;constructor(e){this.keyPromise=gs(e)}async encrypt(e){let t=await this.keyPromise,n=crypto.getRandomValues(new Uint8Array(lt)),r=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:ut,iv:n},t,r),i=new Uint8Array(n.length+s.byteLength);return i.set(n,0),i.set(new Uint8Array(s),n.length),Buffer.from(i).toString("base64")}async decrypt(e){let t=await this.keyPromise,n=new Uint8Array(Buffer.from(e,"base64")),r=n.slice(0,lt),s=n.slice(lt),i=await crypto.subtle.decrypt({name:ut,iv:r},t,s);return new TextDecoder().decode(i)}}async function gs(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new TextEncoder().encode("dotaz-encryption-salt"),info:new TextEncoder().encode("dotaz-aes-key")},n,{name:ut,length:hs},!1,["encrypt","decrypt"])}function J(e,t){let n=new Uint8Array(fs(ue)),r=ms("aes-256-gcm",t,n),s=r.update(e,"utf8"),i=r.final(),o=new Uint8Array(r.getAuthTag()),a=new Uint8Array(s.length+i.length);a.set(s,0),a.set(i,s.length);let c=new Uint8Array(n.length+o.length+a.length);return c.set(n,0),c.set(o,n.length),c.set(a,n.length+o.length),Le+Buffer.from(c).toString("base64")}function ys(e,t){if(!e.startsWith(Le))return e;let n=new Uint8Array(Buffer.from(e.slice(Le.length),"base64")),r=n.subarray(0,ue),s=n.subarray(ue,ue+vn),i=n.subarray(ue+vn),o=ps("aes-256-gcm",t,r);return o.setAuthTag(s),o.update(i).toString("utf8")+o.final("utf8")}function de(e){return e.startsWith(Le)}function Pe(e,t){try{return ys(e,t)}catch{return null}}var ut="AES-GCM",lt=12,hs=256,Le="enc:v1:",ue=12,vn=16;var mt=()=>{};function ws(e){e.run(`
39
42
  CREATE TABLE IF NOT EXISTS schema_version (
40
43
  version INTEGER PRIMARY KEY,
41
44
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
42
45
  )
43
- `)}function Pr(e){return e.prepare("SELECT MAX(version) as version FROM schema_version").get()?.version??0}function nn(e){kr(e);let t=Pr(e),n=Lr.filter((r)=>r.version>t);for(let r of n){if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = OFF");e.run("BEGIN");try{r.up(e),e.run("INSERT INTO schema_version (version) VALUES (?)",[r.version]),e.run("COMMIT")}catch(s){throw e.run("ROLLBACK"),s}if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = ON")}return n.length}var Lr;var rn=C(()=>{Lr=[{version:1,description:"Create connections, query_history, saved_views, settings tables",up:(e)=>{e.run(`
46
+ `)}function Es(e){return e.prepare("SELECT MAX(version) as version FROM schema_version").get()?.version??0}function Rn(e){ws(e);let t=Es(e),n=Ss.filter((r)=>r.version>t);for(let r of n){if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = OFF");e.run("BEGIN");try{r.up(e),e.run("INSERT INTO schema_version (version) VALUES (?)",[r.version]),e.run("COMMIT")}catch(s){throw e.run("ROLLBACK"),s}if(r.disableForeignKeys)e.run("PRAGMA foreign_keys = ON")}return n.length}var Ss;var Nn=T(()=>{Ss=[{version:1,description:"Create connections, query_history, saved_views, settings tables",up:(e)=>{e.run(`
44
47
  CREATE TABLE connections (
45
48
  id TEXT PRIMARY KEY,
46
49
  name TEXT NOT NULL,
@@ -111,8 +114,8 @@ ${a.join(`,
111
114
  INSERT INTO connections_new (id, name, type, config, created_at, updated_at, read_only, color, group_name)
112
115
  SELECT id, name, type, config, created_at, updated_at, read_only, color, group_name
113
116
  FROM connections
114
- `),e.run("DROP TABLE connections"),e.run("ALTER TABLE connections_new RENAME TO connections")}}]});import Mr from"bun:sqlite";class ce{db;localKey=null;constructor(e){this.db=new Mr(e,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),nn(this.db)}static getInstance(e){if(!z){let t=e??Ur();z=new ce(t)}return z}static create(e){return new ce(e)}close(){this.db.close()}transaction(e){return this.db.transaction(e)()}static resetInstance(){if(z)z.db.close(),z=null}setLocalKey(e,t){this.localKey=e,this.migratePasswords(t??null)}encryptConfigJson(e){if(this.localKey&&L(e)){let t={...e,password:W(e.password,this.localKey)};if(e.type==="postgresql"&&e.sshTunnel){let n={...e.sshTunnel};if(n.password)n.password=W(n.password,this.localKey);if(n.keyPassphrase)n.keyPassphrase=W(n.keyPassphrase,this.localKey);t={...t,sshTunnel:n}}return JSON.stringify(t)}return JSON.stringify(e)}decryptConfig(e){if(this.localKey&&L(e)&&oe(e.password)){let t=(r)=>Re(r,this.localKey)??"",n={...e,password:t(e.password)};if(e.type==="postgresql"&&e.sshTunnel){let r={...e.sshTunnel};if(r.password&&oe(r.password))r.password=t(r.password);if(r.keyPassphrase&&oe(r.keyPassphrase))r.keyPassphrase=t(r.keyPassphrase);n={...n,sshTunnel:r}}return n}return e}migratePasswords(e){if(!this.localKey)return;let t=this.localKey,n=(r)=>{if(!oe(r))return{value:W(r,t),changed:!0};if(Re(r,t)!==null)return{value:r,changed:!1};if(e){let s=Re(r,e);if(s!==null)return{value:W(s,t),changed:!0}}return{value:r,changed:!1}};this.transaction(()=>{let r=this.db.prepare("SELECT id, config FROM connections").all(),s=this.db.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let i of r)try{let o=JSON.parse(i.config);if(!L(o))continue;let a=!1,c={...o},u=n(o.password);if(u.changed)c={...c,password:u.value},a=!0;if(o.type==="postgresql"&&o.sshTunnel){let l={...o.sshTunnel},d=!1;if(l.password){let p=n(l.password);if(p.changed)l.password=p.value,d=!0}if(l.keyPassphrase){let p=n(l.keyPassphrase);if(p.changed)l.keyPassphrase=p.value,d=!0}if(d)c={...c,sshTunnel:l},a=!0}if(a)s.run(JSON.stringify(c),i.id)}catch{}})}toConnectionInfo(e){let t=an(e.config,`connection "${e.name}"`);return{id:e.id,name:e.name,config:this.decryptConfig(t),state:"disconnected",readOnly:e.read_only===1?!0:void 0,color:e.color??void 0,groupName:e.group_name??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}listConnections(){return this.db.prepare("SELECT * FROM connections ORDER BY group_name NULLS LAST, name").all().map((t)=>this.toConnectionInfo(t))}getConnectionById(e){let t=this.db.prepare("SELECT * FROM connections WHERE id = ?").get(e);return t?this.toConnectionInfo(t):null}createConnection(e){let t=crypto.randomUUID();return this.createConnectionWithId(t,e)}createConnectionWithId(e,t){let n=new Date().toISOString();return this.db.prepare("INSERT INTO connections (id, name, type, config, read_only, color, group_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e,t.name,t.config.type,this.encryptConfigJson(t.config),t.readOnly?1:0,t.color||null,t.groupName||null,n,n),this.getConnectionById(e)}updateConnection(e){let t=this.getConnectionById(e.id);if(!t)throw Error(`Connection not found: ${e.id}`);let n=new Date().toISOString();return this.db.prepare("UPDATE connections SET name = ?, type = ?, config = ?, read_only = ?, color = ?, group_name = ?, updated_at = ? WHERE id = ?").run(e.name,e.config.type,this.encryptConfigJson(e.config),e.readOnly??t.readOnly?1:0,e.color!==void 0?e.color||null:t.color??null,e.groupName!==void 0?e.groupName||null:t.groupName??null,n,e.id),this.getConnectionById(e.id)}setConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(t,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}listConnectionGroups(){return this.db.prepare("SELECT DISTINCT group_name FROM connections WHERE group_name IS NOT NULL ORDER BY group_name").all().map((t)=>t.group_name)}renameConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE group_name = ?").run(t,e)}deleteConnectionGroup(e){this.db.prepare("UPDATE connections SET group_name = NULL WHERE group_name = ?").run(e)}setConnectionReadOnly(e,t){this.db.prepare("UPDATE connections SET read_only = ? WHERE id = ?").run(t?1:0,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}deleteConnection(e){this.db.prepare("DELETE FROM connections WHERE id = ?").run(e)}getSetting(e){return this.db.prepare("SELECT value FROM settings WHERE key = ?").get(e)?.value??null}getNumberSetting(e){let t=this.getSetting(e)??ae[e]??null;if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}getBooleanSetting(e){let t=this.getSetting(e)??ae[e]??null;if(t===null)return null;if(t==="true")return!0;if(t==="false")return!1;return null}setSetting(e,t){this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,t)}getAllSettings(){let e=this.db.prepare("SELECT key, value FROM settings").all(),t={};for(let n of e)t[n.key]=n.value;return t}listSavedViews(e,t,n){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all(e,t,n).map(Ze)}createSavedView(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO saved_views (id, connection_id, schema_name, table_name, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.schemaName,e.tableName,e.name,JSON.stringify(e.config),n,n),this.getSavedViewById(t)}updateSavedView(e){let t=new Date().toISOString();this.db.prepare("UPDATE saved_views SET name = ?, config = ?, updated_at = ? WHERE id = ?").run(e.name,JSON.stringify(e.config),t,e.id);let n=this.getSavedViewById(e.id);if(!n)throw Error(`Saved view not found: ${e.id}`);return n}deleteSavedView(e){this.db.prepare("DELETE FROM saved_views WHERE id = ?").run(e)}listSavedViewsByConnection(e){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? ORDER BY table_name, name").all(e).map(Ze)}getSavedViewById(e){let t=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get(e);return t?Ze(t):null}addHistory(e){let t=this.db.prepare("INSERT INTO query_history (connection_id, database, sql, status, duration_ms, row_count, error_message) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *").get(e.connectionId,e.database??null,e.sql,e.status,e.durationMs??null,e.rowCount??null,e.errorMessage??null);return this.pruneHistory(),sn(t)}pruneHistory(){let e=this.getNumberSetting("maxHistoryEntries");if(e===null||e<=0)return;this.db.prepare("DELETE FROM query_history WHERE id NOT IN (SELECT id FROM query_history ORDER BY executed_at DESC, id DESC LIMIT ?)").run(e)}listHistory(e){let t=e.limit??100,n=e.offset??0,r=[],s=[];if(e.connectionId)r.push("connection_id = ?"),s.push(e.connectionId);if(e.search)r.push("sql LIKE ?"),s.push(`%${e.search}%`);if(e.startDate)r.push("executed_at >= ?"),s.push(e.startDate+" 00:00:00");if(e.endDate){let c=new Date(e.endDate+"T00:00:00Z");c.setUTCDate(c.getUTCDate()+1);let u=c.getUTCFullYear(),l=String(c.getUTCMonth()+1).padStart(2,"0"),d=String(c.getUTCDate()).padStart(2,"0");r.push("executed_at < ?"),s.push(`${u}-${l}-${d} 00:00:00`)}let o=`SELECT * FROM query_history ${r.length>0?`WHERE ${r.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return s.push(t,n),this.db.prepare(o).all(...s).map(sn)}clearHistory(e){if(e)this.db.prepare("DELETE FROM query_history WHERE connection_id = ?").run(e);else this.db.prepare("DELETE FROM query_history").run()}listBookmarks(e,t){if(t)return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? AND (name LIKE ? OR sql LIKE ?) ORDER BY name").all(e,`%${t}%`,`%${t}%`).map(et);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all(e).map(et)}createBookmark(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO query_bookmarks (id, connection_id, database, name, description, sql, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.database??null,e.name,e.description??"",e.sql,n,n),this.getBookmarkById(t)}updateBookmark(e){let t=new Date().toISOString();this.db.prepare("UPDATE query_bookmarks SET name = ?, description = ?, sql = ?, updated_at = ? WHERE id = ?").run(e.name,e.description??"",e.sql,t,e.id);let n=this.getBookmarkById(e.id);if(!n)throw Error(`Bookmark not found: ${e.id}`);return n}deleteBookmark(e){this.db.prepare("DELETE FROM query_bookmarks WHERE id = ?").run(e)}getBookmarkById(e){let t=this.db.prepare("SELECT * FROM query_bookmarks WHERE id = ?").get(e);return t?et(t):null}saveWorkspace(e){this.db.prepare("INSERT INTO workspace (id, data, updated_at) VALUES ('default', ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')").run(e)}loadWorkspace(){return this.db.prepare("SELECT data FROM workspace WHERE id = 'default'").get()?.data??null}}function an(e,t){try{return JSON.parse(e)}catch{throw Error(`Corrupted JSON in ${t}: ${e.slice(0,100)}`)}}function Ze(e){return{id:e.id,connectionId:e.connection_id,schemaName:e.schema_name,tableName:e.table_name,name:e.name,config:an(e.config,`saved view "${e.name}"`),createdAt:e.created_at,updatedAt:e.updated_at}}function et(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,name:e.name,description:e.description,sql:e.sql,createdAt:e.created_at,updatedAt:e.updated_at}}function sn(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,sql:e.sql,status:e.status,durationMs:e.duration_ms??void 0,rowCount:e.row_count??void 0,errorMessage:e.error_message??void 0,executedAt:e.executed_at}}function Ur(){if(!on)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return on()}var ae,z=null,on;var tt=C(()=>{se();Xe();rn();ae={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5",idleTransactionTimeoutMs:"300000","console.queryResponseTimeout":"300000"}});class nt{cm;appDb;sessions=new Map;labelCounters=new Map;pendingRestore=new Map;txFirstSeen=new Map;idleCheckTimer=null;idleCheckRunning=!1;onTransactionRollback;constructor(e,t,n){this.cm=e,this.appDb=t,this.onTransactionRollback=n,this.startIdleTransactionCheck()}dispose(){this.stopIdleTransactionCheck()}async createSession(e,t){let n=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(ae.maxSessionsPerConnection),s=this.sessions.get(e)?.size??0;if(n!==null&&s>=n)throw Error(`Maximum sessions per connection (${n}) reached. Destroy an existing session first.`);let i=crypto.randomUUID();await this.cm.getDriver(e,t).reserveSession(i);let a=(this.labelCounters.get(e)??0)+1;this.labelCounters.set(e,a);let c={sessionId:i,connectionId:e,database:t,label:`Session ${a}`,inTransaction:!1,txAborted:!1,createdAt:Date.now()};if(!this.sessions.has(e))this.sessions.set(e,new Map);return this.sessions.get(e).set(i,c),c}async destroySession(e){let t=this.findSession(e);if(!t)throw Error(`Session not found: ${e}`);let n=this.cm.getDriver(t.connectionId,t.database);try{await n.cancel(e)}catch{}await n.releaseSession(e),this.txFirstSeen.delete(e);let r=this.sessions.get(t.connectionId);if(r){if(r.delete(e),r.size===0)this.sessions.delete(t.connectionId)}}async destroySessionsForDatabase(e,t){let n=this.sessions.get(e);if(!n)return;for(let[r,s]of n)if(s.database===t){try{let i=this.cm.getDriver(s.connectionId,s.database);try{await i.cancel(r)}catch{}await i.releaseSession(r)}catch{}this.txFirstSeen.delete(r),n.delete(r)}if(n.size===0)this.sessions.delete(e)}listSessions(e){let t=this.sessions.get(e);if(!t)return[];let n=[];for(let r of t.values()){try{let s=this.cm.getDriver(r.connectionId,r.database);r.inTransaction=s.inTransaction(r.sessionId),r.txAborted=s.isTxAborted(r.sessionId)}catch{}n.push({...r})}return n}getSession(e){let t=this.findSession(e);if(!t)return;try{let n=this.cm.getDriver(t.connectionId,t.database);t.inTransaction=n.inTransaction(t.sessionId),t.txAborted=n.isTxAborted(t.sessionId)}catch{}return{...t}}handleSessionDead(e){let t=this.findSession(e);if(!t)return;this.txFirstSeen.delete(e);let n=this.sessions.get(t.connectionId);if(n){if(n.delete(e),n.size===0)this.sessions.delete(t.connectionId)}}handleConnectionLost(e){let t=this.sessions.get(e);if(t){for(let r of t.keys())this.txFirstSeen.delete(r);if(t.size>0)this.pendingRestore.set(e,Array.from(t.values()).map((r)=>({database:r.database,label:r.label})))}let n=`${cn}:${e}:`;for(let r of this.txFirstSeen.keys())if(r.startsWith(n))this.txFirstSeen.delete(r);this.sessions.delete(e)}async handleConnectionRestored(e){let t=this.pendingRestore.get(e);if(this.pendingRestore.delete(e),!t||t.length===0)return[];let n=[];for(let s of t){let i=!1,o,a;try{a=this.cm.getDriver(e,s.database),o=crypto.randomUUID(),await a.reserveSession(o),i=!0;let c={sessionId:o,connectionId:e,database:s.database,label:s.label,inTransaction:!1,txAborted:!1,createdAt:Date.now()};if(!this.sessions.has(e))this.sessions.set(e,new Map);this.sessions.get(e).set(o,c),n.push(c)}catch{if(i&&a&&o)try{await a.releaseSession(o)}catch{}}}let r=this.labelCounters.get(e)??0;for(let s of n){let i=s.label.match(/^Session (\d+)$/);if(i)r=Math.max(r,Number(i[1]))}return this.labelCounters.set(e,r),n}startIdleTransactionCheck(){this.idleCheckTimer=setInterval(()=>{this.checkIdleTransactions()},$r)}stopIdleTransactionCheck(){if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null}async checkIdleTransactions(){if(this.idleCheckRunning)return;this.idleCheckRunning=!0;try{let e=this.appDb.getNumberSetting("idleTransactionTimeoutMs")??Number(ae.idleTransactionTimeoutMs);if(!e||e<=0)return;let t=Date.now();for(let[,n]of this.sessions)for(let[r,s]of n){let i=!1,o=!1;try{let a=this.cm.getDriver(s.connectionId,s.database);i=a.inTransaction(r),o=a.isIterating(r)}catch{this.txFirstSeen.delete(r);continue}if(o)continue;if(i){if(!this.txFirstSeen.has(r))this.txFirstSeen.set(r,t);else if(t-this.txFirstSeen.get(r)>=e){try{await this.cm.getDriver(s.connectionId,s.database).rollback(r)}catch{}try{this.onTransactionRollback?.(s.connectionId,s.database,r)}catch{}this.txFirstSeen.delete(r)}}else this.txFirstSeen.delete(r)}for(let n of this.cm.listConnections()){if(n.state!=="connected")continue;let r=this.cm.getActiveDatabases(n.id);for(let s of r){let i=`${cn}:${n.id}:${s}`,o=!1,a=!1;try{let c=this.cm.getDriver(n.id,s);o=c.inTransaction(),a=c.isIterating()}catch{this.txFirstSeen.delete(i);continue}if(a)continue;if(o){if(!this.txFirstSeen.has(i))this.txFirstSeen.set(i,t);else if(t-this.txFirstSeen.get(i)>=e){try{await this.cm.getDriver(n.id,s).rollback()}catch{}try{this.onTransactionRollback?.(n.id,s)}catch{}this.txFirstSeen.delete(i)}}else this.txFirstSeen.delete(i)}}}finally{this.idleCheckRunning=!1}}findSession(e){for(let t of this.sessions.values()){let n=t.get(e);if(n)return n}return}}var $r=30000,cn="__default_tx__";var ln=C(()=>{tt()});function Hr(e){return Fr.includes(e)}function un(e){let t=(r)=>e[`${qr}${r}`],n=t("provider");return{provider:Hr(n)?n:Ne.provider,apiKey:t("apiKey")??Ne.apiKey,model:t("model")??Ne.model,endpoint:t("endpoint")??Ne.endpoint}}var Ne,qr="ai.",Fr;var dn=C(()=>{Ne={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},Fr=["anthropic","openai","custom"]});function mn(e,t=50){let n=[],r=0;for(let[s,i]of Object.entries(e.tables))for(let o of i){if(r>=t)break;r++;let a=e.columns[`${s}.${o.name}`]??[],c=e.foreignKeys[`${s}.${o.name}`]??[],u=a.map((d)=>{let p=[d.name,d.dataType];if(d.isPrimaryKey)p.push("PK");if(!d.nullable)p.push("NOT NULL");if(d.isAutoIncrement)p.push("AUTO_INCREMENT");return p.join(" ")}),l=s==="main"||s==="public"?o.name:`${s}.${o.name}`;n.push(`TABLE ${l} (${u.join(", ")})`);for(let d of c){let p=d.referencedSchema==="main"||d.referencedSchema==="public"?d.referencedTable:`${d.referencedSchema}.${d.referencedTable}`;n.push(` FK ${d.columns.join(",")} -> ${p}(${d.referencedColumns.join(",")})`)}}return n.join(`
115
- `)}async function Br(e,t){let r=`${e.endpoint||"https://api.anthropic.com"}/v1/messages`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:e.model,max_tokens:2048,system:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
117
+ `),e.run("DROP TABLE connections"),e.run("ALTER TABLE connections_new RENAME TO connections")}}]});import bs from"bun:sqlite";class me{db;localKey=null;constructor(e){this.db=new bs(e,{create:!0}),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA foreign_keys = ON"),Rn(this.db)}static getInstance(e){if(!X){let t=e??Cs();X=new me(t)}return X}static create(e){return new me(e)}close(){this.db.close()}transaction(e){return this.db.transaction(e)()}static resetInstance(){if(X)X.db.close(),X=null}setLocalKey(e,t){this.localKey=e,this.migratePasswords(t??null)}encryptConfigJson(e){if(this.localKey&&k(e)){let t={...e,password:J(e.password,this.localKey)};if(e.type==="postgresql"&&e.sshTunnel){let n={...e.sshTunnel};if(n.password)n.password=J(n.password,this.localKey);if(n.keyPassphrase)n.keyPassphrase=J(n.keyPassphrase,this.localKey);t={...t,sshTunnel:n}}return JSON.stringify(t)}return JSON.stringify(e)}decryptConfig(e){if(this.localKey&&k(e)&&de(e.password)){let t=(r)=>Pe(r,this.localKey)??"",n={...e,password:t(e.password)};if(e.type==="postgresql"&&e.sshTunnel){let r={...e.sshTunnel};if(r.password&&de(r.password))r.password=t(r.password);if(r.keyPassphrase&&de(r.keyPassphrase))r.keyPassphrase=t(r.keyPassphrase);n={...n,sshTunnel:r}}return n}return e}migratePasswords(e){if(!this.localKey)return;let t=this.localKey,n=(r)=>{if(!de(r))return{value:J(r,t),changed:!0};if(Pe(r,t)!==null)return{value:r,changed:!1};if(e){let s=Pe(r,e);if(s!==null)return{value:J(s,t),changed:!0}}return{value:r,changed:!1}};this.transaction(()=>{let r=this.db.prepare("SELECT id, config FROM connections").all(),s=this.db.prepare("UPDATE connections SET config = ? WHERE id = ?");for(let i of r)try{let o=JSON.parse(i.config);if(!k(o))continue;let a=!1,c={...o},u=n(o.password);if(u.changed)c={...c,password:u.value},a=!0;if(o.type==="postgresql"&&o.sshTunnel){let l={...o.sshTunnel},m=!1;if(l.password){let f=n(l.password);if(f.changed)l.password=f.value,m=!0}if(l.keyPassphrase){let f=n(l.keyPassphrase);if(f.changed)l.keyPassphrase=f.value,m=!0}if(m)c={...c,sshTunnel:l},a=!0}if(a)s.run(JSON.stringify(c),i.id)}catch{}})}toConnectionInfo(e){let t=On(e.config,`connection "${e.name}"`);return{id:e.id,name:e.name,config:this.decryptConfig(t),state:"disconnected",readOnly:e.read_only===1?!0:void 0,color:e.color??void 0,groupName:e.group_name??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}listConnections(){return this.db.prepare("SELECT * FROM connections ORDER BY group_name NULLS LAST, name").all().map((t)=>this.toConnectionInfo(t))}getConnectionById(e){let t=this.db.prepare("SELECT * FROM connections WHERE id = ?").get(e);return t?this.toConnectionInfo(t):null}createConnection(e){let t=crypto.randomUUID();return this.createConnectionWithId(t,e)}createConnectionWithId(e,t){let n=new Date().toISOString();return this.db.prepare("INSERT INTO connections (id, name, type, config, read_only, color, group_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e,t.name,t.config.type,this.encryptConfigJson(t.config),t.readOnly?1:0,t.color||null,t.groupName||null,n,n),this.getConnectionById(e)}updateConnection(e){let t=this.getConnectionById(e.id);if(!t)throw Error(`Connection not found: ${e.id}`);let n=new Date().toISOString();return this.db.prepare("UPDATE connections SET name = ?, type = ?, config = ?, read_only = ?, color = ?, group_name = ?, updated_at = ? WHERE id = ?").run(e.name,e.config.type,this.encryptConfigJson(e.config),e.readOnly??t.readOnly?1:0,e.color!==void 0?e.color||null:t.color??null,e.groupName!==void 0?e.groupName||null:t.groupName??null,n,e.id),this.getConnectionById(e.id)}setConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE id = ?").run(t,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}listConnectionGroups(){return this.db.prepare("SELECT DISTINCT group_name FROM connections WHERE group_name IS NOT NULL ORDER BY group_name").all().map((t)=>t.group_name)}renameConnectionGroup(e,t){this.db.prepare("UPDATE connections SET group_name = ? WHERE group_name = ?").run(t,e)}deleteConnectionGroup(e){this.db.prepare("UPDATE connections SET group_name = NULL WHERE group_name = ?").run(e)}setConnectionReadOnly(e,t){this.db.prepare("UPDATE connections SET read_only = ? WHERE id = ?").run(t?1:0,e);let n=this.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);return n}deleteConnection(e){this.db.prepare("DELETE FROM connections WHERE id = ?").run(e)}getSetting(e){return this.db.prepare("SELECT value FROM settings WHERE key = ?").get(e)?.value??null}getNumberSetting(e){let t=this.getSetting(e)??Z[e]??null;if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}getBooleanSetting(e){let t=this.getSetting(e)??Z[e]??null;if(t===null)return null;if(t==="true")return!0;if(t==="false")return!1;return null}setSetting(e,t){this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,t)}getAllSettings(){let e=this.db.prepare("SELECT key, value FROM settings").all(),t={};for(let n of e)t[n.key]=n.value;return t}listSavedViews(e,t,n){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? AND schema_name = ? AND table_name = ? ORDER BY name").all(e,t,n).map(pt)}createSavedView(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO saved_views (id, connection_id, schema_name, table_name, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.schemaName,e.tableName,e.name,JSON.stringify(e.config),n,n),this.getSavedViewById(t)}updateSavedView(e){let t=new Date().toISOString();this.db.prepare("UPDATE saved_views SET name = ?, config = ?, updated_at = ? WHERE id = ?").run(e.name,JSON.stringify(e.config),t,e.id);let n=this.getSavedViewById(e.id);if(!n)throw Error(`Saved view not found: ${e.id}`);return n}deleteSavedView(e){this.db.prepare("DELETE FROM saved_views WHERE id = ?").run(e)}listSavedViewsByConnection(e){return this.db.prepare("SELECT * FROM saved_views WHERE connection_id = ? ORDER BY table_name, name").all(e).map(pt)}getSavedViewById(e){let t=this.db.prepare("SELECT * FROM saved_views WHERE id = ?").get(e);return t?pt(t):null}addHistory(e){let t=this.db.prepare("INSERT INTO query_history (connection_id, database, sql, status, duration_ms, row_count, error_message) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *").get(e.connectionId,e.database??null,e.sql,e.status,e.durationMs??null,e.rowCount??null,e.errorMessage??null);return this.pruneHistory(),Dn(t)}pruneHistory(){let e=this.getNumberSetting("maxHistoryEntries");if(e===null||e<=0)return;this.db.prepare("DELETE FROM query_history WHERE id NOT IN (SELECT id FROM query_history ORDER BY executed_at DESC, id DESC LIMIT ?)").run(e)}listHistory(e){let t=e.limit??100,n=e.offset??0,r=[],s=[];if(e.connectionId)r.push("connection_id = ?"),s.push(e.connectionId);if(e.search)r.push("sql LIKE ?"),s.push(`%${e.search}%`);if(e.startDate)r.push("executed_at >= ?"),s.push(e.startDate+" 00:00:00");if(e.endDate){let c=new Date(e.endDate+"T00:00:00Z");c.setUTCDate(c.getUTCDate()+1);let u=c.getUTCFullYear(),l=String(c.getUTCMonth()+1).padStart(2,"0"),m=String(c.getUTCDate()).padStart(2,"0");r.push("executed_at < ?"),s.push(`${u}-${l}-${m} 00:00:00`)}let o=`SELECT * FROM query_history ${r.length>0?`WHERE ${r.join(" AND ")}`:""} ORDER BY executed_at DESC LIMIT ? OFFSET ?`;return s.push(t,n),this.db.prepare(o).all(...s).map(Dn)}clearHistory(e){if(e)this.db.prepare("DELETE FROM query_history WHERE connection_id = ?").run(e);else this.db.prepare("DELETE FROM query_history").run()}listBookmarks(e,t){if(t)return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? AND (name LIKE ? OR sql LIKE ?) ORDER BY name").all(e,`%${t}%`,`%${t}%`).map(ft);return this.db.prepare("SELECT * FROM query_bookmarks WHERE connection_id = ? ORDER BY name").all(e).map(ft)}createBookmark(e){let t=crypto.randomUUID(),n=new Date().toISOString();return this.db.prepare("INSERT INTO query_bookmarks (id, connection_id, database, name, description, sql, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(t,e.connectionId,e.database??null,e.name,e.description??"",e.sql,n,n),this.getBookmarkById(t)}updateBookmark(e){let t=new Date().toISOString();this.db.prepare("UPDATE query_bookmarks SET name = ?, description = ?, sql = ?, updated_at = ? WHERE id = ?").run(e.name,e.description??"",e.sql,t,e.id);let n=this.getBookmarkById(e.id);if(!n)throw Error(`Bookmark not found: ${e.id}`);return n}deleteBookmark(e){this.db.prepare("DELETE FROM query_bookmarks WHERE id = ?").run(e)}getBookmarkById(e){let t=this.db.prepare("SELECT * FROM query_bookmarks WHERE id = ?").get(e);return t?ft(t):null}saveWorkspace(e){this.db.prepare("INSERT INTO workspace (id, data, updated_at) VALUES ('default', ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET data = excluded.data, updated_at = datetime('now')").run(e)}loadWorkspace(){return this.db.prepare("SELECT data FROM workspace WHERE id = 'default'").get()?.data??null}}function On(e,t){try{return JSON.parse(e)}catch{throw Error(`Corrupted JSON in ${t}: ${e.slice(0,100)}`)}}function pt(e){return{id:e.id,connectionId:e.connection_id,schemaName:e.schema_name,tableName:e.table_name,name:e.name,config:On(e.config,`saved view "${e.name}"`),createdAt:e.created_at,updatedAt:e.updated_at}}function ft(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,name:e.name,description:e.description,sql:e.sql,createdAt:e.created_at,updatedAt:e.updated_at}}function Dn(e){return{id:e.id,connectionId:e.connection_id,database:e.database??void 0,sql:e.sql,status:e.status,durationMs:e.duration_ms??void 0,rowCount:e.row_count??void 0,errorMessage:e.error_message??void 0,executedAt:e.executed_at}}function Cs(){if(!_n)throw Error("Default DB path not configured. Call setDefaultDbPath() first.");return _n()}var Z,X=null,_n;var ht=T(()=>{le();mt();Nn();Z={defaultPageSize:"100",defaultTxMode:"auto-commit",theme:"dark",queryTimeout:"30000",maxHistoryEntries:"1000",clipboardIncludeHeaders:"true",exportDefaultFormat:"csv",defaultConnectionMode:"pool",autoPin:"on-begin",autoUnpin:"never",maxSessionsPerConnection:"5",idleTransactionTimeoutMs:"300000","console.queryResponseTimeout":"300000","cli.enabled":"false"}});class gt{cm;appDb;sessions=new Map;labelCounters=new Map;pendingRestore=new Map;txFirstSeen=new Map;idleCheckTimer=null;idleCheckRunning=!1;onTransactionRollback;constructor(e,t,n){this.cm=e,this.appDb=t,this.onTransactionRollback=n,this.startIdleTransactionCheck()}dispose(){this.stopIdleTransactionCheck()}async createSession(e,t,n){let r=this.appDb.getNumberSetting("maxSessionsPerConnection")??Number(Z.maxSessionsPerConnection),i=this.sessions.get(e)?.size??0;if(r!==null&&i>=r)throw Error(`Maximum sessions per connection (${r}) reached. Destroy an existing session first.`);let o=crypto.randomUUID(),a=this.cm.getDriver(e,t);await a.reserveSession(o,{readOnly:n?.readOnly,statementTimeoutMs:n?.readOnly?this.readOnlyStatementTimeoutMs():void 0});let c=await this.confirmReadOnly(a,o,n?.readOnly),u=(this.labelCounters.get(e)??0)+1;this.labelCounters.set(e,u);let l={sessionId:o,connectionId:e,database:t,label:n?.label??`Session ${u}`,inTransaction:!1,txAborted:!1,createdAt:Date.now(),readOnly:c};if(!this.sessions.has(e))this.sessions.set(e,new Map);return this.sessions.get(e).set(o,l),l}async confirmReadOnly(e,t,n){let r=e.isSessionReadOnly(t);if(n&&!r){try{await e.releaseSession(t)}catch{}throw Error("The driver did not open this session read-only")}return n?!0:void 0}async destroySession(e){let t=this.findSession(e);if(!t)throw Error(`Session not found: ${e}`);let n=this.cm.getDriver(t.connectionId,t.database);try{await n.cancel(e)}catch{}await n.releaseSession(e),this.txFirstSeen.delete(e);let r=this.sessions.get(t.connectionId);if(r){if(r.delete(e),r.size===0)this.sessions.delete(t.connectionId)}}async destroySessionsForDatabase(e,t){let n=this.sessions.get(e);if(!n)return;for(let[r,s]of n)if(s.database===t){try{let i=this.cm.getDriver(s.connectionId,s.database);try{await i.cancel(r)}catch{}await i.releaseSession(r)}catch{}this.txFirstSeen.delete(r),n.delete(r)}if(n.size===0)this.sessions.delete(e)}listSessions(e){let t=this.sessions.get(e);if(!t)return[];let n=[];for(let r of t.values()){try{let s=this.cm.getDriver(r.connectionId,r.database);r.inTransaction=s.inTransaction(r.sessionId),r.txAborted=s.isTxAborted(r.sessionId)}catch{}n.push({...r})}return n}getSession(e){let t=this.findSession(e);if(!t)return;try{let n=this.cm.getDriver(t.connectionId,t.database);t.inTransaction=n.inTransaction(t.sessionId),t.txAborted=n.isTxAborted(t.sessionId)}catch{}return{...t}}handleSessionDead(e){let t=this.findSession(e);if(!t)return;this.txFirstSeen.delete(e);let n=this.sessions.get(t.connectionId);if(n){if(n.delete(e),n.size===0)this.sessions.delete(t.connectionId)}}handleConnectionLost(e){let t=this.sessions.get(e);if(t){for(let r of t.keys())this.txFirstSeen.delete(r);if(t.size>0)this.pendingRestore.set(e,Array.from(t.values()).map((r)=>({database:r.database,label:r.label,readOnly:r.readOnly})))}let n=`${In}:${e}:`;for(let r of this.txFirstSeen.keys())if(r.startsWith(n))this.txFirstSeen.delete(r);this.sessions.delete(e)}async handleConnectionRestored(e){let t=this.pendingRestore.get(e);if(this.pendingRestore.delete(e),!t||t.length===0)return[];let n=[];for(let s of t){let i=!1,o,a;try{a=this.cm.getDriver(e,s.database),o=crypto.randomUUID(),await a.reserveSession(o,{readOnly:s.readOnly,statementTimeoutMs:s.readOnly?this.readOnlyStatementTimeoutMs():void 0}),i=!0;let c=await this.confirmReadOnly(a,o,s.readOnly),u={sessionId:o,connectionId:e,database:s.database,label:s.label,inTransaction:!1,txAborted:!1,createdAt:Date.now(),readOnly:c};if(!this.sessions.has(e))this.sessions.set(e,new Map);this.sessions.get(e).set(o,u),n.push(u)}catch{if(i&&a&&o)try{await a.releaseSession(o)}catch{}}}let r=this.labelCounters.get(e)??0;for(let s of n){let i=s.label.match(/^Session (\d+)$/);if(i)r=Math.max(r,Number(i[1]))}return this.labelCounters.set(e,r),n}readOnlyStatementTimeoutMs(){let e=this.appDb.getNumberSetting("queryTimeout")??Number(Z.queryTimeout);return e>0?e:void 0}startIdleTransactionCheck(){this.idleCheckTimer=setInterval(()=>{this.checkIdleTransactions()},Ts)}stopIdleTransactionCheck(){if(this.idleCheckTimer)clearInterval(this.idleCheckTimer),this.idleCheckTimer=null}async checkIdleTransactions(){if(this.idleCheckRunning)return;this.idleCheckRunning=!0;try{let e=this.appDb.getNumberSetting("idleTransactionTimeoutMs")??Number(Z.idleTransactionTimeoutMs);if(!e||e<=0)return;let t=Date.now();for(let[,n]of this.sessions)for(let[r,s]of n){let i=!1,o=!1;try{let a=this.cm.getDriver(s.connectionId,s.database);i=a.inTransaction(r),o=a.isIterating(r)}catch{this.txFirstSeen.delete(r);continue}if(o)continue;if(i){if(!this.txFirstSeen.has(r))this.txFirstSeen.set(r,t);else if(t-this.txFirstSeen.get(r)>=e){try{await this.cm.getDriver(s.connectionId,s.database).rollback(r)}catch{}try{this.onTransactionRollback?.(s.connectionId,s.database,r)}catch{}this.txFirstSeen.delete(r)}}else this.txFirstSeen.delete(r)}for(let n of this.cm.listConnections()){if(n.state!=="connected")continue;let r=this.cm.getActiveDatabases(n.id);for(let s of r){let i=`${In}:${n.id}:${s}`,o=!1,a=!1;try{let c=this.cm.getDriver(n.id,s);o=c.inTransaction(),a=c.isIterating()}catch{this.txFirstSeen.delete(i);continue}if(a)continue;if(o){if(!this.txFirstSeen.has(i))this.txFirstSeen.set(i,t);else if(t-this.txFirstSeen.get(i)>=e){try{await this.cm.getDriver(n.id,s).rollback()}catch{}try{this.onTransactionRollback?.(n.id,s)}catch{}this.txFirstSeen.delete(i)}}else this.txFirstSeen.delete(i)}}}finally{this.idleCheckRunning=!1}}findSession(e){for(let t of this.sessions.values()){let n=t.get(e);if(n)return n}return}}var Ts=30000,In="__default_tx__";var xn=T(()=>{ht()});function Rs(e){return vs.includes(e)}function Ln(e){let t=(r)=>e[`${As}${r}`],n=t("provider");return{provider:Rs(n)?n:ke.provider,apiKey:t("apiKey")??ke.apiKey,model:t("model")??ke.model,endpoint:t("endpoint")??ke.endpoint}}var ke,As="ai.",vs;var Pn=T(()=>{ke={provider:"anthropic",apiKey:"",model:"claude-sonnet-4-20250514",endpoint:""},vs=["anthropic","openai","custom"]});function kn(e,t=50){let n=[],r=0;for(let[s,i]of Object.entries(e.tables))for(let o of i){if(r>=t)break;r++;let a=e.columns[`${s}.${o.name}`]??[],c=e.foreignKeys[`${s}.${o.name}`]??[],u=a.map((m)=>{let f=[m.name,m.dataType];if(m.isPrimaryKey)f.push("PK");if(!m.nullable)f.push("NOT NULL");if(m.isAutoIncrement)f.push("AUTO_INCREMENT");return f.join(" ")}),l=s==="main"||s==="public"?o.name:`${s}.${o.name}`;n.push(`TABLE ${l} (${u.join(", ")})`);for(let m of c){let f=m.referencedSchema==="main"||m.referencedSchema==="public"?m.referencedTable:`${m.referencedSchema}.${m.referencedTable}`;n.push(` FK ${m.columns.join(",")} -> ${f}(${m.referencedColumns.join(",")})`)}}return n.join(`
118
+ `)}async function Ns(e,t){let r=`${e.endpoint||"https://api.anthropic.com"}/v1/messages`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:e.model,max_tokens:2048,system:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
116
119
 
117
120
  Rules:
118
121
  - Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
@@ -126,7 +129,7 @@ Rules:
126
129
  Database schema:
127
130
  ${t.schemaContext}
128
131
 
129
- Request: ${t.prompt}`}]})});if(!s.ok){let a=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`Anthropic API error (${s.status}): ${a.slice(0,200)}`)}let o=(await s.json()).content?.find((a)=>a.type==="text");return fn(o?.text??"")}async function pn(e,t){let r=`${e.endpoint||"https://api.openai.com"}/v1/chat/completions`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.model||"gpt-4o",max_tokens:2048,messages:[{role:"system",content:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
132
+ Request: ${t.prompt}`}]})});if(!s.ok){let a=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`Anthropic API error (${s.status}): ${a.slice(0,200)}`)}let o=(await s.json()).content?.find((a)=>a.type==="text");return Un(o?.text??"")}async function Mn(e,t){let r=`${e.endpoint||"https://api.openai.com"}/v1/chat/completions`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.model||"gpt-4o",max_tokens:2048,messages:[{role:"system",content:`You are an expert SQL query generator. Given a database schema and a natural language request, generate a valid SQL query.
130
133
 
131
134
  Rules:
132
135
  - Output ONLY the SQL query \u2014 no explanations, no markdown, no code fences.
@@ -140,8 +143,8 @@ Rules:
140
143
  Database schema:
141
144
  ${t.schemaContext}
142
145
 
143
- Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`OpenAI API error (${s.status}): ${o.slice(0,200)}`)}let i=await s.json();return fn(i.choices?.[0]?.message?.content??"")}async function Qr(e,t){if(!e.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return pn(e,t)}function fn(e){let t=e.trim(),n=t.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(n)t=n[1].trim();return t}async function gn(e,t){if(!e.apiKey)throw Error("AI API key not configured. Go to AI Settings (command palette) to set it up.");switch(e.provider){case"anthropic":return Br(e,t);case"openai":return pn(e,t);case"custom":return Qr(e,t);default:throw Error(`Unknown AI provider: ${e.provider}`)}}function Kr(e){return e.dataType!=="binary"}async function hn(e,t,n,r){let s=performance.now(),i=await e.loadSchema(),o=[];for(let[p,h]of Object.entries(i.tables)){if(t.scope==="schema"&&t.schemaName&&p!==t.schemaName)continue;for(let m of h){if(m.type!=="table")continue;if(t.scope==="tables"&&t.tableNames){if(!t.tableNames.includes(m.name))continue}o.push(m)}}let a=[],c=0,u=0,l=e.getDriverType()==="postgresql",d=l?"ILIKE":"LIKE";for(let p of o){if(r())return{matches:a,searchedTables:u,totalMatches:c,cancelled:!0,elapsedMs:Math.round(performance.now()-s)};n(p.name,u,o.length);let h=`${p.schema}.${p.name}`,g=(i.columns[h]??[]).filter(Kr);if(g.length===0){u++;continue}let y=[],E=[],f=0;for(let R of g){f++;let v=e.quoteIdentifier(R.name);y.push(`${fe(v,e)} ${d} ${e.placeholder(f)}`),E.push(`%${t.searchTerm}%`)}let S=e.qualifyTable(p.schema,p.name);f++;let w=e.placeholder(f),b=`SELECT * FROM ${S} WHERE ${y.join(" OR ")} LIMIT ${w}`;E.push(t.resultsPerTable);try{let R=await e.execute(b,E);for(let v of R.rows){let x=v;for(let U of g){let At=x[U.name];if(At==null)continue;let vt=String(At);if(l?vt.toLowerCase().includes(t.searchTerm.toLowerCase()):vt.toLowerCase().includes(t.searchTerm.toLowerCase())){a.push({schema:p.schema,table:p.name,column:U.name,row:x}),c++;break}}}}catch(R){console.debug(`Search: skipped ${p.schema}.${p.name}:`,R instanceof Error?R.message:R)}u++}return{matches:a,searchedTables:u,totalMatches:c,cancelled:!1,elapsedMs:Math.round(performance.now()-s)}}var yn=C(()=>{k()});function Wr(e){let t=[],n=0;while(n<e.length){let r=e[n];if(r==="'"||r==='"'){let s=r,i=r;n++;while(n<e.length)if(e[n]===s)if(i+=e[n],n++,n<e.length&&e[n]===s)i+=e[n],n++;else break;else i+=e[n],n++;t.push({type:"string",value:i,upper:i});continue}if(/\s/.test(r)){let s="";while(n<e.length&&/\s/.test(e[n]))s+=e[n],n++;t.push({type:"whitespace",value:s,upper:s});continue}if(/[a-zA-Z_]/.test(r)){let s="";while(n<e.length&&/[a-zA-Z0-9_]/.test(e[n]))s+=e[n],n++;t.push({type:"word",value:s,upper:s.toUpperCase()});continue}t.push({type:"symbol",value:r,upper:r}),n++}return t}function zr(e,t,n){let r=n.split(" "),s=t,i=0;while(i<r.length&&s<e.length){if(e[s].type==="whitespace"){s++;continue}if(e[s].upper!==r[i])return 0;i++,s++}return i===r.length?s-t:0}function bn(e){let t=e.trim();if(!t)return"";let n=Wr(t);for(let c of n)if(c.type==="word"){if(jr.includes(c.upper))c.value=c.upper}let r=[],s="",i=0,o=0;while(i<n.length){let c=n[i];if(c.type==="symbol"&&c.value==="("){o++,s+=c.value,i++;continue}if(c.type==="symbol"&&c.value===")"){if(o>0)o--;s+=c.value,i++;continue}if(o>0){s+=c.value,i++;continue}if(c.type==="word"){let u=!1,l=[...En,...Sn].sort((d,p)=>p.split(" ").length-d.split(" ").length);for(let d of l){let p=zr(n,i,d);if(p>0){let h=[];for(let E=i;E<i+p;E++)h.push(n[E].value);let m=h.filter((E)=>E.trim()).join(" "),g=Sn.includes(d);if(En.includes(d)||g){let E=s.trimEnd();if(E)r.push(E);s=m}else s+=m;i+=p,u=!0;break}}if(u)continue;if(Yr.includes(c.upper)){let d=s.trimEnd();if(d)r.push(d);s=" "+c.value,i++;continue}}if(c.type==="whitespace"){if(s.trimEnd())s+=" "}else s+=c.value;i++}let a=s.trimEnd();if(a)r.push(a);return r.join(`
144
- `)}var En,Sn,Yr,jr;var wn=C(()=>{En=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],Sn=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],Yr=["ON","AND","OR"],jr=["SELECT","DISTINCT","FROM","WHERE","AND","OR","NOT","IN","EXISTS","BETWEEN","LIKE","ILIKE","IS","NULL","TRUE","FALSE","AS","ON","USING","JOIN","INNER","LEFT","RIGHT","FULL","OUTER","CROSS","NATURAL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","INTERSECT","EXCEPT","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","PRIMARY","KEY","FOREIGN","REFERENCES","UNIQUE","CHECK","DEFAULT","CONSTRAINT","CASCADE","RESTRICT","BEGIN","COMMIT","ROLLBACK","TRANSACTION","CASE","WHEN","THEN","ELSE","END","ASC","DESC","NULLS","FIRST","LAST","COUNT","SUM","AVG","MIN","MAX","CAST","COALESCE","NULLIF","WITH","RECURSIVE","RETURNING"]});class rt{cm;constructor(e){this.cm=e}async begin(e,t,n){let r=this.cm.getDriver(e,t);if(r.inTransaction(n))throw Error("Transaction already active on this connection");await r.beginTransaction(n)}async commit(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to commit");await r.commit(n)}async rollback(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to rollback");await r.rollback(n)}isActive(e,t,n){try{return this.cm.getDriver(e,t).inTransaction(n)}catch{return!1}}async rollbackIfActive(e,t,n){if(this.isActive(e,t,n))await this.rollback(e,t,n)}}class st{cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;allowServerFileAccess;constructor(e,t,n,r){this.cm=e;this.queryExecutor=t;this.appDb=n;this.txManager=new rt(e),this.encryption=r?.encryption,this.Utils=r?.Utils,this.emitMessage=r?.emitMessage,this.sessionManager=r?.sessionManager,this.demoDbSourcePath=r?.demoDbSourcePath,this.demoDbTargetPath=r?.demoDbTargetPath,this.allowServerFileAccess=r?.allowServerFileAccess??!0}listConnections(){return this.cm.listConnections()}createConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.createConnection(e)}updateConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.updateConnection(e)}setConnectionReadOnly(e,t){return this.cm.setConnectionReadOnly(e,t)}setConnectionGroup(e,t){return this.appDb.setConnectionGroup(e,t)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup(e,t){this.appDb.renameConnectionGroup(e,t)}deleteConnectionGroup(e){this.appDb.deleteConnectionGroup(e)}async deleteConnection(e){await this.cm.deleteConnection(e)}async testConnection(e){return this.rejectServerSqliteConfig(e),this.cm.testConnection(e)}async connect(e,t,n){if(this.encryption){let r;if(n?.config){let s=n.encryptedSecrets?JSON.parse(await this.encryption.decrypt(n.encryptedSecrets)):{};r=en(n.config,s)}else if(n?.encryptedConfig)r=JSON.parse(await this.encryption.decrypt(n.encryptedConfig));if(r){this.rejectServerSqliteConfig(r);let s=this.appDb.getConnectionById(e),i=n?.name??s?.name??e;if(!s)this.appDb.createConnectionWithId(e,{name:i,config:r});else this.appDb.updateConnection({id:e,name:i,config:r})}}await this.cm.connect(e,t?{password:t}:void 0)}async disconnect(e){await this.cm.disconnect(e)}listConnectionHandles(){let e=this.cm.listConnectionHandles();if(!this.sessionManager)return e;let t=new Map;for(let n of this.cm.listConnections())for(let r of this.sessionManager.listSessions(n.id))t.set(r.sessionId,r);return e.map((n)=>{if(!n.sessionId)return n;let r=t.get(n.sessionId);if(!r)return n;return{...n,label:r.label}})}async terminateConnectionHandle(e,t,n){let r=this.listConnectionHandles().find((s)=>s.connectionId===e&&(t===void 0||s.database===t)&&s.handleId===n);if(r?.sessionId&&this.sessionManager){await this.sessionManager.destroySession(r.sessionId),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});return}await this.cm.terminateConnectionHandle(e,t,n)}async createSession(e,t){if(!this.sessionManager)throw Error("SessionManager not available");let n=await this.sessionManager.createSession(e,t);return this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)}),n}async destroySession(e){if(!this.sessionManager)throw Error("SessionManager not available");let t=this.sessionManager.getSession(e);if(await this.sessionManager.destroySession(e),t)this.emitMessage?.("session.changed",{connectionId:t.connectionId,sessions:this.sessionManager.listSessions(t.connectionId)})}listSessions(e){if(!this.sessionManager)return[];return this.sessionManager.listSessions(e)}getDriver(e,t){return this.cm.getDriver(e,t)}async listDatabases(e){return this.cm.listDatabases(e)}async listDatabasesForConfig(e){return this.rejectServerSqliteConfig(e),this.cm.listDatabasesForConfig(e)}async activateDatabase(e,t){await this.cm.activateDatabase(e,t)}async deactivateDatabase(e,t){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase(e,t),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});await this.cm.deactivateDatabase(e,t)}async executeQuery(e,t,n,r,s,i,o){return this.queryExecutor.executeQuery(e,t,n,void 0,r,s,i,o)}async executeStatements(e,t,n,r){let s=this.cm.getDriver(e,n),i=async(o)=>{let a=s.inTransaction(o);try{if(!a)await s.beginTransaction(o);let c=[];for(let u of t){let l=performance.now();try{let d=await s.execute(u.sql,u.params,o),p=Math.round(performance.now()-l);c.push({...d,durationMs:p}),this.queryExecutor.sessionLog.add(e,u.sql,d.error?"error":"success",p,d.affectedRows??d.rowCount,d.error,n,o)}catch(d){let p=Math.round(performance.now()-l);throw this.queryExecutor.sessionLog.add(e,u.sql,"error",p,0,d instanceof Error?d.message:String(d),n,o),d}}if(!a)await s.commit(o);return c}catch(c){if(!a)try{await s.rollback(o)}catch(u){console.debug("Rollback after error failed:",u instanceof Error?u.message:u)}throw c}};if(r)return i(r);return ne(s,i)}submitQuery(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.executeQuery(e,t,n,0,r,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,results:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{let u=c?.code;this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),errorCode:u,durationMs:Math.round(performance.now()-a)})})}submitExplain(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.explainQuery(e,t,n,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,explainResult:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),durationMs:Math.round(performance.now()-a)})})}async cancelQuery(e){await this.queryExecutor.cancelQuery(e)}async beginTransaction(e,t,n){await this.txManager.begin(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async commitTransaction(e,t,n){await this.txManager.commit(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async rollbackTransaction(e,t,n){await this.txManager.rollback(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}getTransactionLog(e){let t=this.queryExecutor.sessionLog.getEntries(e.connectionId,e.database);if(e.statusFilter)t=t.filter((s)=>s.status===e.statusFilter);if(e.search){let s=e.search.toLowerCase();t=t.filter((i)=>i.sql.toLowerCase().includes(s))}let n=this.txManager.isActive(e.connectionId,e.database,e.sessionId),r=n?this.queryExecutor.sessionLog.getPendingCount(e.connectionId,e.database,e.sessionId):0;return{entries:t,pendingStatementCount:r,inTransaction:n}}clearTransactionLog(e,t,n){this.queryExecutor.sessionLog.clear(e,t)}listHistory(e){return this.appDb.listHistory(e)}clearHistory(e){this.appDb.clearHistory(e)}listSavedViews(e,t,n){return this.appDb.listSavedViews(e,t,n)}createSavedView(e){return this.appDb.createSavedView(e)}updateSavedView(e){return this.appDb.updateSavedView(e)}deleteSavedView(e){this.appDb.deleteSavedView(e)}listSavedViewsByConnection(e){return this.appDb.listSavedViewsByConnection(e)}getSavedViewById(e){return this.appDb.getSavedViewById(e)}listBookmarks(e,t){return this.appDb.listBookmarks(e,t)}createBookmark(e){return this.appDb.createBookmark(e)}updateBookmark(e){return this.appDb.updateBookmark(e)}deleteBookmark(e){this.appDb.deleteBookmark(e)}async searchDatabase(e){let t=this.cm.getDriver(e.connectionId,e.database);return hn(t,{searchTerm:e.searchTerm,scope:e.scope,schemaName:e.schemaName,tableNames:e.tableNames,resultsPerTable:e.resultsPerTable??50},()=>{},()=>!1)}async exportData(e){let t=e.filePath;this.rejectServerFileAccess(t);let n=this.cm.getDriver(e.connectionId,e.database);if(!t)throw Error("Export requires a file path");let r=this.emitMessage?(i)=>this.emitMessage("export.progress",{rowCount:i}):void 0;return{...await Bt(n,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,includeHeaders:e.includeHeaders,delimiter:e.delimiter,encoding:e.encoding,utf8Bom:e.utf8Bom,batchSize:e.batchSize,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins},t,void 0,r),filePath:t}}async exportPreview(e){let t=this.cm.getDriver(e.connectionId,e.database);return Qt(t,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,delimiter:e.delimiter,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins})}async exportPreviewRows(e){let t=this.cm.getDriver(e.connectionId,e.database),{sql:n,params:r}=Ee({schema:e.schema,table:e.table,format:"csv",columns:e.columns,filters:e.filters,sort:e.sort,autoJoins:e.autoJoins},t),s=r.length+1,i=`${n} LIMIT ${t.placeholder(s)}`,a=(await t.execute(i,[...r,e.limit])).rows,c=a.length>0?Object.keys(a[0]):e.columns??[];return{rows:a,columns:c}}async importData(e){this.rejectServerFileAccess(e.filePath);let t=this.cm.getDriver(e.connectionId,e.database),n=this.resolveImportStream(e.filePath,e.fileContent),r=this.emitMessage?(s)=>this.emitMessage("import.progress",{rowCount:s}):void 0;return be(t,n,{schema:e.schema,table:e.table,format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,mappings:e.mappings,batchSize:e.batchSize},void 0,r)}async importPreview(e){this.rejectServerFileAccess(e.filePath);let t=this.resolveImportPreviewStream(e.filePath,e.fileContent),n=await Wt(t,{format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,limit:e.limit});if(e.filePath)try{let r=Bun.file(e.filePath);n.fileSizeBytes=r.size}catch{}return n}rejectServerFileAccess(e){if(!this.allowServerFileAccess&&e!==void 0)throw Error("Server file access is not available in this runtime")}rejectServerSqliteConfig(e){if(e?.type==="sqlite")this.rejectServerFileAccess(e.path)}resolveImportStream(e,t){if(e)return Bun.file(e).stream();if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream(e,t){if(e){let s=Bun.file(e).stream().getReader(),i=65536,o=0;return new ReadableStream({async pull(a){let{done:c,value:u}=await s.read();if(c){a.close();return}if(o+=u.byteLength,o>=65536){a.enqueue(u),a.close(),s.releaseLock();return}a.enqueue(u)},cancel(){s.releaseLock()}})}if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting(e,t){this.appDb.setSetting(e,t)}async encryptSecrets(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt(e)}async decryptConfig(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.decrypt(e)}async showOpenDialog({filters:e,multiple:t}){if(!this.Utils)throw Error("Utils not available");let n=e&&e.length>0?e.flatMap((i)=>i.extensions.map((o)=>`*.${o}`)).join(","):"*",s=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:n,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:t??!1})).filter((i)=>i!=="");return{paths:s,cancelled:s.length===0}}async showSaveDialog({defaultName:e}){if(!this.Utils)throw Error("Utils not available");let n=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!n||n==="")return{path:null,cancelled:!0};return{path:e?`${n}/${e}`:n,cancelled:!1}}formatSql(e){return bn(e)}async generateSql(e){let t=this.cm.getDriver(e.connectionId,e.database),n=await t.loadSchema(),r=mn(n),s=un(this.appDb.getAllSettings());return{sql:await gn(s,{prompt:e.prompt,schemaContext:r,dialect:t.getDriverType()})}}saveWorkspace(e){this.appDb.saveWorkspace(e)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let e=Bun.file(this.demoDbSourcePath);if(!await e.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,e);let t={type:"sqlite",path:this.demoDbTargetPath},n=this.appDb.createConnection({name:"Bookstore (Demo)",config:t});return await this.cm.connect(n.id),n}getSessionManager(){return this.sessionManager}}var Cn=C(()=>{se();dn();Ke();je();yn();wn()});function Tn(e){return{"connections.list":()=>e.listConnections(),"connections.create":({name:t,config:n,readOnly:r,color:s,groupName:i})=>e.createConnection({name:t,config:n,readOnly:r,color:s,groupName:i}),"connections.update":({id:t,name:n,config:r,readOnly:s,color:i,groupName:o})=>e.updateConnection({id:t,name:n,config:r,readOnly:s,color:i,groupName:o}),"connections.setReadOnly":({id:t,readOnly:n})=>e.setConnectionReadOnly(t,n),"connections.setGroup":({id:t,groupName:n})=>e.setConnectionGroup(t,n),"connections.listGroups":()=>e.listConnectionGroups(),"connections.renameGroup":({oldName:t,newName:n})=>{e.renameConnectionGroup(t,n)},"connections.deleteGroup":({groupName:t})=>{e.deleteConnectionGroup(t)},"connections.delete":async({id:t})=>{await e.deleteConnection(t)},"connections.test":async({config:t})=>e.testConnection(t),"connections.connect":async({connectionId:t,password:n,config:r,encryptedSecrets:s,name:i,encryptedConfig:o})=>{await e.connect(t,n,{config:r,encryptedSecrets:s,name:i,encryptedConfig:o})},"connections.disconnect":async({connectionId:t})=>{await e.disconnect(t)},"connections.listOpenHandles":()=>e.listConnectionHandles(),"connections.terminateHandle":async({connectionId:t,database:n,handleId:r})=>{await e.terminateConnectionHandle(t,n,r)},"session.create":async({connectionId:t,database:n})=>e.createSession(t,n),"session.destroy":async({sessionId:t})=>{await e.destroySession(t)},"session.list":({connectionId:t})=>e.listSessions(t),"databases.list":async({connectionId:t})=>e.listDatabases(t),"databases.listForConfig":async({config:t})=>e.listDatabasesForConfig(t),"databases.activate":async({connectionId:t,database:n})=>{await e.activateDatabase(t,n)},"databases.deactivate":async({connectionId:t,database:n})=>{await e.deactivateDatabase(t,n)},"schema.load":async({connectionId:t,database:n,sessionId:r})=>e.getDriver(t,n).loadSchema(r),"query.execute":async({connectionId:t,sql:n,queryId:r,params:s,database:i,statements:o,sessionId:a,searchPath:c})=>{if(o&&o.length>0)return e.executeStatements(t,o,i,a);return e.executeQuery(t,n,s,r,i,a,c)},"query.submit":({connectionId:t,sql:n,queryId:r,params:s,database:i,sessionId:o,searchPath:a})=>(e.submitQuery(t,n,s,r,i,o,a),{queryId:r}),"query.submitExplain":({connectionId:t,sql:n,analyze:r,queryId:s,database:i,sessionId:o,searchPath:a})=>(e.submitExplain(t,n,r??!1,s,i,o,a),{queryId:s}),"query.cancel":async({queryId:t})=>{await e.cancelQuery(t)},"query.format":({sql:t})=>({sql:e.formatSql(t)}),"tx.begin":async({connectionId:t,database:n,sessionId:r})=>{await e.beginTransaction(t,n,r)},"tx.commit":async({connectionId:t,database:n,sessionId:r})=>{await e.commitTransaction(t,n,r)},"tx.rollback":async({connectionId:t,database:n,sessionId:r})=>{await e.rollbackTransaction(t,n,r)},"transaction.getLog":(t)=>e.getTransactionLog(t),"transaction.clearLog":({connectionId:t,database:n,sessionId:r})=>{e.clearTransactionLog(t,n,r)},"search.searchDatabase":async(t)=>e.searchDatabase(t),"export.exportData":async(t)=>e.exportData(t),"export.preview":async(t)=>({content:await e.exportPreview(t)}),"export.previewRows":async(t)=>e.exportPreviewRows(t),"import.importData":async(t)=>e.importData(t),"import.preview":async(t)=>e.importPreview(t),"history.list":(t)=>e.listHistory(t),"history.clear":({connectionId:t})=>{e.clearHistory(t)},"views.save":({connectionId:t,schemaName:n,tableName:r,name:s,config:i})=>{if(!s?.trim())throw Error("View name is required");if(!t)throw Error("connectionId is required");if(!r)throw Error("tableName is required");if(e.listSavedViews(t,n,r).some((a)=>a.name===s.trim()))throw Error(`A view named "${s.trim()}" already exists for this table`);return e.createSavedView({connectionId:t,schemaName:n,tableName:r,name:s.trim(),config:i})},"views.update":({id:t,name:n,config:r})=>{if(!t)throw Error("View id is required");if(!n?.trim())throw Error("View name is required");let s=e.getSavedViewById(t);if(!s)throw Error(`Saved view not found: ${t}`);if(e.listSavedViews(s.connectionId,s.schemaName,s.tableName).some((o)=>o.id!==t&&o.name===n.trim()))throw Error(`A view named "${n.trim()}" already exists for this table`);return e.updateSavedView({id:t,name:n.trim(),config:r})},"views.delete":({id:t})=>{e.deleteSavedView(t)},"views.listByConnection":({connectionId:t})=>e.listSavedViewsByConnection(t),"bookmarks.list":({connectionId:t,search:n})=>e.listBookmarks(t,n),"bookmarks.create":({connectionId:t,database:n,name:r,description:s,sql:i})=>{if(!r?.trim())throw Error("Bookmark name is required");return e.createBookmark({connectionId:t,database:n,name:r.trim(),description:s,sql:i})},"bookmarks.update":({id:t,name:n,description:r,sql:s})=>{if(!t)throw Error("Bookmark id is required");if(!n?.trim())throw Error("Bookmark name is required");return e.updateBookmark({id:t,name:n.trim(),description:r,sql:s})},"bookmarks.delete":({id:t})=>{e.deleteBookmark(t)},"settings.getAll":()=>e.getAllSettings(),"settings.set":({key:t,value:n})=>{e.setSetting(t,n)},"storage.encryptSecrets":async({secrets:t})=>{if(!e.encryptSecrets)throw Error("Encryption not available");return{encryptedSecrets:await e.encryptSecrets(t)}},"storage.decryptConfig":async({encryptedConfig:t})=>{if(!e.decryptConfig)throw Error("Encryption not available");return{config:await e.decryptConfig(t)}},"ai.generateSql":async(t)=>e.generateSql(t),"workspace.save":({data:t})=>{e.saveWorkspace(t)},"workspace.load":()=>e.loadWorkspace(),"system.showOpenDialog":async(t)=>{if(!e.showOpenDialog)return{paths:[],cancelled:!0};return e.showOpenDialog(t)},"system.showSaveDialog":async(t)=>{if(!e.showSaveDialog)return{path:null,cancelled:!0};return e.showSaveDialog(t)},"demo.initialize":async()=>{if(!e.initializeDemo)throw Error("Demo initialization is not available");return e.initializeDemo()}}}function Jr(e){if(!e)throw Error("AppDatabase is required");return e}function An(e,t,n,r,s){let i=Jr(n),o=t??new re(e,void 0,i),a=new nt(e,i,(u,l,d)=>{o.sessionLog.resetPendingCount(u,l,d)}),c=new st(e,o,i,{encryption:s?.encryption,Utils:r,emitMessage:s?.emitMessage,sessionManager:a,demoDbSourcePath:s?.demoDbSourcePath,demoDbTargetPath:s?.demoDbTargetPath,allowServerFileAccess:s?.allowServerFileAccess});return{handlers:Tn(c),sessionManager:a,adapter:c}}var vn=C(()=>{ze();ln();Cn()});class it{inner;constructor(e){this.inner=e}log(e,t,n,r){let s=e.replace(/\s+/g," ").trim(),i=t&&t.length>0;if(r)console.debug(`[SQL ERROR] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`,r);else if(n!==void 0)console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`);else console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""}`)}async execute(e,t,n,r){let s=performance.now();try{let i=await this.inner.execute(e,t,n,r);return this.log(e,t,Math.round(performance.now()-s)),i}catch(i){throw this.log(e,t,Math.round(performance.now()-s),i),i}}async*iterate(e,t,n,r,s){this.log(e,t),yield*this.inner.iterate(e,t,n,r,s)}async importBatch(e,t,n,r){let s=`INSERT INTO ${e} (${t.join(", ")}) VALUES ... [${n.length} rows]`,i=performance.now();try{let o=await this.inner.importBatch(e,t,n,r);return this.log(s,void 0,Math.round(performance.now()-i)),o}catch(o){throw this.log(s,void 0,Math.round(performance.now()-i),o),o}}connect(e){return this.inner.connect(e)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession(e){return this.inner.reserveSession(e)}releaseSession(e){return this.inner.releaseSession(e)}getSessionIds(){return this.inner.getSessionIds()}cancel(e,t){return this.inner.cancel(e,t)}ping(){return this.inner.ping()}async loadSchema(e){console.debug("[SQL] loadSchema started"+(e?` (session: ${e})`:""));let t=performance.now();try{let n=await this.inner.loadSchema(e),r=Object.values(n.tables).reduce((s,i)=>s+i.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${n.schemas.length} schemas, ${r} tables (${Math.round(performance.now()-t)}ms)`),n}catch(n){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-t)}ms)`,n),n}}beginTransaction(e){return this.inner.beginTransaction(e)}commit(e){return this.inner.commit(e)}rollback(e){return this.inner.rollback(e)}inTransaction(e){return this.inner.inTransaction(e)}isTxAborted(e){return this.inner.isTxAborted(e)}isIterating(e){return this.inner.isIterating(e)}getDriverType(){return this.inner.getDriverType()}listConnectionHandles(){return this.inner.listConnectionHandles()}terminateConnectionHandle(e){return this.inner.terminateConnectionHandle(e)}quoteIdentifier(e){return this.inner.quoteIdentifier(e)}qualifyTable(e,t){return this.inner.qualifyTable(e,t)}emptyInsertSql(e){return this.inner.emptyInsertSql(e)}placeholder(e){return this.inner.placeholder(e)}}var{SQL:Vr}=globalThis.Bun;class le{url;resetFn;initFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;metadata=new Map;nextHandleNumber=1;constructor(e,t,n){this.url=e;this.resetFn=t;this.initFn=n}async connect(){if(this.systemConn=this.createSql("system"),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1"),this.initFn)await this.initFn(this.systemConn)}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.markUsed(this.systemConn),this.systemConn}async createConnection(){let e=this.createSql("leased");if(this.connections.add(e),this.initFn)try{await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}return e}async acquireConnection(){if(this.idleConn){let e=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),this.setRole(e,"leased"),this.markUsed(e),e}return this.createConnection()}async releaseConnection(e){if(!this.connections.has(e)){try{await e.close()}catch{}return}if(!this.idleConn){if(this.resetFn||this.initFn)try{if(this.resetFn)await this.resetFn(e);if(this.initFn)await this.initFn(e)}catch{await this.destroyConnection(e);return}this.setRole(e,"idle"),this.markUsed(e),this.idleConn=e,this.scheduleIdleTimeout()}else await this.destroyConnection(e)}async destroyConnection(e){if(this.idleConn===e)this.idleConn=null,this.clearIdleTimer();if(this.systemConn===e)this.systemConn=null;this.connections.delete(e),this.metadata.delete(e);try{await e.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn)await this.destroyConnection(this.systemConn);let e=this.createSql("system");this.connections.add(e);try{if(await e.unsafe("SELECT 1"),this.initFn)await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}this.systemConn=e}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let e=[...this.connections];this.connections.clear(),this.metadata.clear(),this.systemConn=null,await Promise.allSettled(e.map((t)=>t.close()))}getConnectionId(e){return this.metadata.get(e)?.handleId}snapshot(){return[...this.connections].map((e)=>this.metadata.get(e)).filter((e)=>e!==void 0).map((e)=>({...e}))}async terminateConnection(e){let t=this.findConnectionByHandleId(e);if(!t)return!1;if(t===this.systemConn)return await this.reconnectSystemConnection(),!0;return await this.destroyConnection(t),!0}createSql(e){let t=new Vr({url:this.url,max:1}),n=Date.now();return this.metadata.set(t,{handleId:`pool-${this.nextHandleNumber}`,role:e,createdAt:n,lastUsedAt:n}),this.nextHandleNumber+=1,t}findConnectionByHandleId(e){for(let t of this.connections)if(this.metadata.get(t)?.handleId===e)return t;return}markUsed(e){let t=this.metadata.get(e);if(!t)return;t.lastUsedAt=Date.now()}setRole(e,t){let n=this.metadata.get(e);if(!n)return;n.role=t}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},Gr)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var Gr=30000;var ot=()=>{};function at(e){let t=e instanceof Error?e.message:String(e),n=e?.errno??e?.code;if(/ECONNREFUSED|connection refused/i.test(t))return new D("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new D("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new D("HOST_NOT_FOUND",t,{cause:e});if(/too many connections|connection limit/i.test(t))return new D("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new D("SSL_ERROR",t,{cause:e});if(n?.startsWith("28")||/authentication failed|password authentication/i.test(t))return new we(t,{cause:e});if(n==="3D000"||/database .* does not exist/i.test(t))return new D("DATABASE_NOT_FOUND",t,{cause:e});if(n==="23505"||/violates unique constraint|duplicate key/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(n==="23503"||/violates foreign key constraint/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(n==="23514"||/violates check constraint/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(n==="23502"||/violates not-null constraint/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(n==="42601"||/syntax error/i.test(t))return new N("QUERY_SYNTAX",t,{cause:e});if(n==="42P01"||/relation .* does not exist/i.test(t))return new N("TABLE_NOT_FOUND",t,{cause:e});if(n==="42703"||/column .* does not exist/i.test(t))return new N("COLUMN_NOT_FOUND",t,{cause:e});if(n==="42501"||/permission denied/i.test(t))return new T("PERMISSION_DENIED",t,{cause:e});if(n==="40001")return new N("SERIALIZATION_FAILURE",t,{cause:e});if(n==="40P01")return new N("DEADLOCK_DETECTED",t,{cause:e});if(n==="25P02")return new N("TRANSACTION_ABORTED",t,{cause:e});if(n?.startsWith("42")||n?.startsWith("22"))return new N("QUERY_EXECUTION",t,{cause:e});return new T("UNKNOWN",t,{cause:e})}function ue(e){let t=e instanceof Error?e.message:String(e);if(/unable to open database|cannot open/i.test(t))return new D("CONNECTION_REFUSED",t,{cause:e});if(/UNIQUE constraint failed/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(/FOREIGN KEY constraint failed/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(/CHECK constraint failed/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(/NOT NULL constraint failed/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(/no such table/i.test(t))return new N("TABLE_NOT_FOUND",t,{cause:e});if(/no such column/i.test(t))return new N("COLUMN_NOT_FOUND",t,{cause:e});if(/syntax error|near /i.test(t))return new N("QUERY_SYNTAX",t,{cause:e});if(/authorization denied|not authorized/i.test(t))return new T("PERMISSION_DENIED",t,{cause:e});return new T("UNKNOWN",t,{cause:e})}function ct(e){let t=e instanceof Error?e.message:String(e),n=e?.errno;if(/ECONNREFUSED|connection refused/i.test(t)||n===2003)return new D("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new D("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new D("HOST_NOT_FOUND",t,{cause:e});if(/too many connections/i.test(t)||n===1040)return new D("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new D("SSL_ERROR",t,{cause:e});if(n===1045||/access denied/i.test(t))return new we(t,{cause:e});if(n===1049||/unknown database/i.test(t))return new D("DATABASE_NOT_FOUND",t,{cause:e});if(n===1062||/duplicate entry/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(n===1451||n===1452||/foreign key constraint/i.test(t)||/cannot delete or update a parent row/i.test(t)||/cannot add or update a child row/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(n===3819||/check constraint/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(n===1048||/cannot be null/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(n===1213||/deadlock found/i.test(t))return new N("DEADLOCK_DETECTED",t,{cause:e});if(n===1205||/lock wait timeout exceeded/i.test(t))return new N("SERIALIZATION_FAILURE",t,{cause:e});if(n===1064||/syntax error|you have an error in your sql syntax/i.test(t))return new N("QUERY_SYNTAX",t,{cause:e});if(n===1146||/table .* doesn't exist/i.test(t))return new N("TABLE_NOT_FOUND",t,{cause:e});if(n===1054||/unknown column/i.test(t))return new N("COLUMN_NOT_FOUND",t,{cause:e});if(n===1142||n===1143||/command denied|access denied/i.test(t))return new T("PERMISSION_DENIED",t,{cause:e});return new T("UNKNOWN",t,{cause:e})}var De=C(()=>{P()});function J(e){let t=e;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;return 0}var Yi,ji,Wi,zi,Ji,Vi;var Rn=C(()=>{k();Yi=new Set(["integer","serial","float","numeric"]),ji=new Set(["boolean"]),Wi=new Set(["timestamp","date"]),zi=new Set(["text","varchar","char"]),Ji=new Set(["json"]),Vi=new Set(["array"])});var Nn=C(()=>{Rn();k()});var Dn=C(()=>{ye();Nn()});function _e(e,t){let n=te(t).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(n)){if(e.txActive=!0,"txAborted"in e)e.txAborted=!1}else if(/^(COMMIT|END)\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}else if(/^ROLLBACK\b/.test(n)&&!/^ROLLBACK\s+TO\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}}function F(e){let t=e?.code;if(typeof t==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(t))return!0;let n=e instanceof Error?e.message:String(e);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(n)}async function V(e,t){if(t?.rollback)try{await e.unsafe("ROLLBACK")}catch{}try{await e.close()}catch{}}var lt=C(()=>{Dn()});function Xr(e){switch(e.toLowerCase()){case"int":case"integer":case"bigint":case"smallint":case"tinyint":case"mediumint":return"integer";case"float":case"double":return"float";case"decimal":case"numeric":return"numeric";case"bit":case"boolean":case"bool":return"boolean";case"text":case"tinytext":case"mediumtext":case"longtext":return"text";case"varchar":return"varchar";case"char":return"char";case"date":return"date";case"time":return"time";case"datetime":case"timestamp":return"timestamp";case"json":return"json";case"binary":case"varbinary":case"blob":case"tinyblob":case"mediumblob":case"longblob":return"binary";case"enum":case"set":return"enum";default:return"unknown"}}class ut{pool=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let t=`mysql://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}`,n=e.initSql?.trim(),r=n?async(s)=>{await s.unsafe(n)}:void 0;this.pool=new le(t,(s)=>s.unsafe("RESET CONNECTION"),r);try{await this.pool.connect()}catch(s){let i=this.pool;throw this.pool=null,await i.disconnectAll().catch(()=>{}),s instanceof T?s:ct(s)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await V(e.conn,{rollback:e.txActive});if(this.sessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let t=await this.pool.createConnection();this.sessions.set(e,{conn:t,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await V(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==O)}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s,a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,d=Math.round(performance.now()-a),p=[...l];if(s)_e(s,e);return{columns:p.length>0?Object.keys(p[0]).map((m)=>({name:m,dataType:"unknown"})):[],rows:p,rowCount:p.length,affectedRows:J(l),durationMs:d}}catch(l){throw l instanceof T?l:ct(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=await this.getSchemas(n),s=r.map((m)=>m.name),i={};for(let m of r)i[m.name]=await this.getTables(n,m.name);let[o,a,c,u]=await Promise.all([n.unsafe(`SELECT
146
+ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.status===401)throw Error("Invalid API key. Check your AI settings.");if(s.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`OpenAI API error (${s.status}): ${o.slice(0,200)}`)}let i=await s.json();return Un(i.choices?.[0]?.message?.content??"")}async function Ds(e,t){if(!e.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return Mn(e,t)}function Un(e){let t=e.trim(),n=t.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(n)t=n[1].trim();return t}async function $n(e,t){if(!e.apiKey)throw Error("AI API key not configured. Go to AI Settings (command palette) to set it up.");switch(e.provider){case"anthropic":return Ns(e,t);case"openai":return Mn(e,t);case"custom":return Ds(e,t);default:throw Error(`Unknown AI provider: ${e.provider}`)}}function yt(e){return e!=="pending"&&e!=="approved"}class St{proposals=new Map;waiters=new Map;observers=new Set;ttlMs;now;disposed=!1;constructor(e){this.ttlMs=e?.ttlMs??3600000,this.now=e?.now??(()=>Date.now())}create(e){this.assertUsable(),this.sweep();let t=[...this.proposals.values()].filter((r)=>r.status==="pending").length;if(t>=20)throw Error(`${t} proposals are already waiting for approval \u2014 wait for the user or cancel some first`);let n={id:crypto.randomUUID(),connectionId:e.connectionId,database:e.database,sql:e.sql,reason:e.reason,status:"pending",createdAt:this.now()};return this.proposals.set(n.id,n),this.notify(n),{...n}}get(e){this.sweep();let t=this.proposals.get(e);return t?{...t}:null}list(e){this.sweep();let t=[...this.proposals.values()];if(e?.status)t=t.filter((n)=>n.status===e.status);if(e?.connectionId)t=t.filter((n)=>n.connectionId===e.connectionId);return t.map((n)=>({...n}))}resolve(e){if(this.assertUsable(),this.sweep(),!_s.includes(e.status))throw Error(`Cannot resolve a proposal to status "${e.status}"`);return this.transition(this.require(e.proposalId),e.status,e.result,e.error)}cancel(e){return this.assertUsable(),this.sweep(),this.transition(this.require(e),"cancelled")}async wait(e,t){this.assertUsable(),this.sweep();let n=this.require(e);if(yt(n.status))return{...n};return new Promise((r)=>{let s,i=(o,a)=>{if(!a&&!yt(o.status))return;if(s!==void 0)clearTimeout(s);this.removeWaiter(e,i),r({...o})};this.addWaiter(e,i),s=setTimeout(()=>{this.removeWaiter(e,i),this.sweep();let o=this.proposals.get(e);r({...o??n})},t)})}waiterCount(){let e=0;for(let t of this.waiters.values())e+=t.size;return e}dispose(){this.disposed=!0;for(let[e,t]of[...this.waiters]){let n=this.proposals.get(e);if(!n)continue;for(let r of[...t])r(n,!0)}this.waiters.clear(),this.observers.clear(),this.proposals.clear()}require(e){let t=this.proposals.get(e);if(!t)throw Error(`Proposal not found: ${e}`);return t}transition(e,t,n,r){if(!(e.status==="pending"||e.status==="approved"&&Os.includes(t)))throw Error(`Proposal ${e.id} is already ${e.status}`);if(e.status=t,e.resolvedAt=this.now(),n!==void 0)e.result=n;if(r!==void 0)e.error=r;return this.notify(e),{...e}}sweep(){let e=this.now(),t=e-this.ttlMs;for(let[n,r]of this.proposals){if(r.status==="pending"){if(r.createdAt>t)continue;r.status="expired",r.resolvedAt=e,this.notify(r);continue}if(r.status==="approved"){if((r.resolvedAt??r.createdAt)>t)continue;r.status="failed",r.error="The app claimed this proposal but never reported the outcome. The statement may have run \u2014 check the data.",r.resolvedAt=e,this.notify(r);continue}if((r.resolvedAt??r.createdAt)<=t)this.proposals.delete(n)}this.evictOverflow()}evictOverflow(){if(this.proposals.size<=500)return;for(let[e,t]of this.proposals){if(this.proposals.size<=500)return;if(!yt(t.status))continue;this.proposals.delete(e)}}onChange(e){return this.observers.add(e),()=>this.observers.delete(e)}notify(e){for(let n of[...this.observers])n({...e});let t=this.waiters.get(e.id);if(!t)return;for(let n of[...t])n(e)}addWaiter(e,t){let n=this.waiters.get(e);if(n){n.add(t);return}this.waiters.set(e,new Set([t]))}removeWaiter(e,t){let n=this.waiters.get(e);if(!n)return;if(n.delete(t),n.size===0)this.waiters.delete(e)}assertUsable(){if(this.disposed)throw Error("ProposalStore has been disposed")}}var _s,Os;var qn=T(()=>{_s=["approved","rejected","executed","failed","cancelled","expired"],Os=["executed","failed"]});function Is(e){return e.dataType!=="binary"}async function Fn(e,t,n,r){let s=performance.now(),i=await e.loadSchema(t.sessionId),o=[];for(let[f,g]of Object.entries(i.tables)){if(t.scope==="schema"&&t.schemaName&&f!==t.schemaName)continue;for(let d of g){if(d.type!=="table")continue;if(t.scope==="tables"&&t.tableNames){if(!t.tableNames.includes(d.name))continue}o.push(d)}}let a=[],c=0,u=0,l=e.getDriverType()==="postgresql",m=l?"ILIKE":"LIKE";for(let f of o){if(r())return{matches:a,searchedTables:u,totalMatches:c,cancelled:!0,elapsedMs:Math.round(performance.now()-s)};n(f.name,u,o.length);let g=`${f.schema}.${f.name}`,h=(i.columns[g]??[]).filter(Is);if(h.length===0){u++;continue}let y=[],w=[],p=0;for(let N of h){p++;let v=e.quoteIdentifier(N.name);y.push(`${we(v,e)} ${m} ${e.placeholder(p)}`),w.push(`%${t.searchTerm}%`)}let S=e.qualifyTable(f.schema,f.name);p++;let E=e.placeholder(p),C=`SELECT * FROM ${S} WHERE ${y.join(" OR ")} LIMIT ${E}`;w.push(t.resultsPerTable);try{let N=await e.execute(C,w,t.sessionId);for(let v of N.rows){let L=v;for(let q of h){let Ut=L[q.name];if(Ut==null)continue;let $t=String(Ut);if(l?$t.toLowerCase().includes(t.searchTerm.toLowerCase()):$t.toLowerCase().includes(t.searchTerm.toLowerCase())){a.push({schema:f.schema,table:f.name,column:q.name,row:L}),c++;break}}}}catch(N){console.debug(`Search: skipped ${f.schema}.${f.name}:`,N instanceof Error?N.message:N)}u++}return{matches:a,searchedTables:u,totalMatches:c,cancelled:!1,elapsedMs:Math.round(performance.now()-s)}}var Hn=T(()=>{M()});function Ps(e){let t=[],n=0;while(n<e.length){let r=e[n];if(r==="'"||r==='"'){let s=r,i=r;n++;while(n<e.length)if(e[n]===s)if(i+=e[n],n++,n<e.length&&e[n]===s)i+=e[n],n++;else break;else i+=e[n],n++;t.push({type:"string",value:i,upper:i});continue}if(/\s/.test(r)){let s="";while(n<e.length&&/\s/.test(e[n]))s+=e[n],n++;t.push({type:"whitespace",value:s,upper:s});continue}if(/[a-zA-Z_]/.test(r)){let s="";while(n<e.length&&/[a-zA-Z0-9_]/.test(e[n]))s+=e[n],n++;t.push({type:"word",value:s,upper:s.toUpperCase()});continue}t.push({type:"symbol",value:r,upper:r}),n++}return t}function ks(e,t,n){let r=n.split(" "),s=t,i=0;while(i<r.length&&s<e.length){if(e[s].type==="whitespace"){s++;continue}if(e[s].upper!==r[i])return 0;i++,s++}return i===r.length?s-t:0}function Yn(e){let t=e.trim();if(!t)return"";let n=Ps(t);for(let c of n)if(c.type==="word"){if(Ls.includes(c.upper))c.value=c.upper}let r=[],s="",i=0,o=0;while(i<n.length){let c=n[i];if(c.type==="symbol"&&c.value==="("){o++,s+=c.value,i++;continue}if(c.type==="symbol"&&c.value===")"){if(o>0)o--;s+=c.value,i++;continue}if(o>0){s+=c.value,i++;continue}if(c.type==="word"){let u=!1,l=[...Bn,...Qn].sort((m,f)=>f.split(" ").length-m.split(" ").length);for(let m of l){let f=ks(n,i,m);if(f>0){let g=[];for(let w=i;w<i+f;w++)g.push(n[w].value);let d=g.filter((w)=>w.trim()).join(" "),h=Qn.includes(m);if(Bn.includes(m)||h){let w=s.trimEnd();if(w)r.push(w);s=d}else s+=d;i+=f,u=!0;break}}if(u)continue;if(xs.includes(c.upper)){let m=s.trimEnd();if(m)r.push(m);s=" "+c.value,i++;continue}}if(c.type==="whitespace"){if(s.trimEnd())s+=" "}else s+=c.value;i++}let a=s.trimEnd();if(a)r.push(a);return r.join(`
147
+ `)}var Bn,Qn,xs,Ls;var Kn=T(()=>{Bn=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],Qn=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],xs=["ON","AND","OR"],Ls=["SELECT","DISTINCT","FROM","WHERE","AND","OR","NOT","IN","EXISTS","BETWEEN","LIKE","ILIKE","IS","NULL","TRUE","FALSE","AS","ON","USING","JOIN","INNER","LEFT","RIGHT","FULL","OUTER","CROSS","NATURAL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","INTERSECT","EXCEPT","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","PRIMARY","KEY","FOREIGN","REFERENCES","UNIQUE","CHECK","DEFAULT","CONSTRAINT","CASCADE","RESTRICT","BEGIN","COMMIT","ROLLBACK","TRANSACTION","CASE","WHEN","THEN","ELSE","END","ASC","DESC","NULLS","FIRST","LAST","COUNT","SUM","AVG","MIN","MAX","CAST","COALESCE","NULLIF","WITH","RECURSIVE","RETURNING"]});class wt{cm;constructor(e){this.cm=e}async begin(e,t,n){let r=this.cm.getDriver(e,t);if(r.inTransaction(n))throw Error("Transaction already active on this connection");await r.beginTransaction(n)}async commit(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to commit");await r.commit(n)}async rollback(e,t,n){let r=this.cm.getDriver(e,t);if(!r.inTransaction(n))throw Error("No active transaction to rollback");await r.rollback(n)}isActive(e,t,n){try{return this.cm.getDriver(e,t).inTransaction(n)}catch{return!1}}async rollbackIfActive(e,t,n){if(this.isActive(e,t,n))await this.rollback(e,t,n)}}class Et{cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;allowServerFileAccess;appVersion;mode;proposals=new St;unsubscribeProposals;uiSnapshot=null;constructor(e,t,n,r){this.cm=e;this.queryExecutor=t;this.appDb=n;this.txManager=new wt(e),this.encryption=r?.encryption,this.Utils=r?.Utils,this.emitMessage=r?.emitMessage,this.sessionManager=r?.sessionManager,this.demoDbSourcePath=r?.demoDbSourcePath,this.demoDbTargetPath=r?.demoDbTargetPath,this.allowServerFileAccess=r?.allowServerFileAccess??!0,this.appVersion=r?.appVersion??"0.0.0",this.mode=r?.mode??"web",this.unsubscribeProposals=this.proposals.onChange((s)=>{this.emitMessage?.("cli.proposal",s)})}listConnections(){return this.cm.listConnections()}createConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.createConnection(e)}updateConnection(e){return this.rejectServerSqliteConfig(e.config),this.cm.updateConnection(e)}setConnectionReadOnly(e,t){return this.cm.setConnectionReadOnly(e,t)}setConnectionGroup(e,t){return this.appDb.setConnectionGroup(e,t)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup(e,t){this.appDb.renameConnectionGroup(e,t)}deleteConnectionGroup(e){this.appDb.deleteConnectionGroup(e)}async deleteConnection(e){await this.cm.deleteConnection(e)}async testConnection(e){return this.rejectServerSqliteConfig(e),this.cm.testConnection(e)}async connect(e,t,n){if(this.encryption){let r;if(n?.config){let s=n.encryptedSecrets?JSON.parse(await this.encryption.decrypt(n.encryptedSecrets)):{};r=An(n.config,s)}else if(n?.encryptedConfig)r=JSON.parse(await this.encryption.decrypt(n.encryptedConfig));if(r){this.rejectServerSqliteConfig(r);let s=this.appDb.getConnectionById(e),i=n?.name??s?.name??e;if(!s)this.appDb.createConnectionWithId(e,{name:i,config:r});else this.appDb.updateConnection({id:e,name:i,config:r})}}await this.cm.connect(e,t?{password:t}:void 0)}async disconnect(e){await this.cm.disconnect(e)}listConnectionHandles(){let e=this.cm.listConnectionHandles();if(!this.sessionManager)return e;let t=new Map;for(let n of this.cm.listConnections())for(let r of this.sessionManager.listSessions(n.id))t.set(r.sessionId,r);return e.map((n)=>{if(!n.sessionId)return n;let r=t.get(n.sessionId);if(!r)return n;return{...n,label:r.label}})}async terminateConnectionHandle(e,t,n){let r=this.listConnectionHandles().find((s)=>s.connectionId===e&&(t===void 0||s.database===t)&&s.handleId===n);if(r?.sessionId&&this.sessionManager){await this.sessionManager.destroySession(r.sessionId),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});return}await this.cm.terminateConnectionHandle(e,t,n)}async createSession(e,t,n){if(!this.sessionManager)throw Error("SessionManager not available");let r=await this.sessionManager.createSession(e,t,n);return this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)}),r}async destroySession(e){if(!this.sessionManager)throw Error("SessionManager not available");let t=this.sessionManager.getSession(e);if(await this.sessionManager.destroySession(e),t)this.emitMessage?.("session.changed",{connectionId:t.connectionId,sessions:this.sessionManager.listSessions(t.connectionId)})}listSessions(e){if(!this.sessionManager)return[];return this.sessionManager.listSessions(e)}getDriver(e,t){return this.cm.getDriver(e,t)}async listDatabases(e){return this.cm.listDatabases(e)}async listDatabasesForConfig(e){return this.rejectServerSqliteConfig(e),this.cm.listDatabasesForConfig(e)}async activateDatabase(e,t){await this.cm.activateDatabase(e,t)}async deactivateDatabase(e,t){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase(e,t),this.emitMessage?.("session.changed",{connectionId:e,sessions:this.sessionManager.listSessions(e)});await this.cm.deactivateDatabase(e,t)}async executeQuery(e,t,n,r,s,i,o){return this.queryExecutor.executeQuery(e,t,n,void 0,r,s,i,o)}async executeStatements(e,t,n,r){let s=this.cm.getDriver(e,n);for(let o of t)Ie(s,o.sql,r);let i=async(o)=>{let a=s.inTransaction(o);try{if(!a)await s.beginTransaction(o);let c=[];for(let u of t){let l=performance.now();try{let m=await s.execute(u.sql,u.params,o),f=Math.round(performance.now()-l);c.push({...m,durationMs:f}),this.queryExecutor.sessionLog.add(e,u.sql,m.error?"error":"success",f,Re(m),m.error,n,o)}catch(m){let f=Math.round(performance.now()-l);throw this.queryExecutor.sessionLog.add(e,u.sql,"error",f,0,m instanceof Error?m.message:String(m),n,o),m}}if(!a)await s.commit(o);return c}catch(c){if(!a)try{await s.rollback(o)}catch(u){console.debug("Rollback after error failed:",u instanceof Error?u.message:u)}throw c}};if(r)return i(r);return ae(s,i)}submitQuery(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.executeQuery(e,t,n,0,r,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,results:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{let u=c?.code;this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),errorCode:u,durationMs:Math.round(performance.now()-a)})})}submitExplain(e,t,n,r,s,i,o){let a=performance.now();this.queryExecutor.explainQuery(e,t,n,s,i,o).then((c)=>{this.emitMessage?.("query.completed",{queryId:r,explainResult:c,durationMs:Math.round(performance.now()-a)})}).catch((c)=>{this.emitMessage?.("query.completed",{queryId:r,error:c instanceof Error?c.message:String(c),durationMs:Math.round(performance.now()-a)})})}cancelQuery(e){return this.queryExecutor.cancelQuery(e)}async beginTransaction(e,t,n){await this.txManager.begin(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async commitTransaction(e,t,n){await this.txManager.commit(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}async rollbackTransaction(e,t,n){await this.txManager.rollback(e,t,n),this.queryExecutor.sessionLog.resetPendingCount(e,t,n)}getTransactionLog(e){let t=this.queryExecutor.sessionLog.getEntries(e.connectionId,e.database);if(e.statusFilter)t=t.filter((s)=>s.status===e.statusFilter);if(e.search){let s=e.search.toLowerCase();t=t.filter((i)=>i.sql.toLowerCase().includes(s))}let n=this.txManager.isActive(e.connectionId,e.database,e.sessionId),r=n?this.queryExecutor.sessionLog.getPendingCount(e.connectionId,e.database,e.sessionId):0;return{entries:t,pendingStatementCount:r,inTransaction:n}}clearTransactionLog(e,t,n){this.queryExecutor.sessionLog.clear(e,t)}listHistory(e){return this.appDb.listHistory(e)}clearHistory(e){this.appDb.clearHistory(e)}listSavedViews(e,t,n){return this.appDb.listSavedViews(e,t,n)}createSavedView(e){return this.appDb.createSavedView(e)}updateSavedView(e){return this.appDb.updateSavedView(e)}deleteSavedView(e){this.appDb.deleteSavedView(e)}listSavedViewsByConnection(e){return this.appDb.listSavedViewsByConnection(e)}getSavedViewById(e){return this.appDb.getSavedViewById(e)}listBookmarks(e,t){return this.appDb.listBookmarks(e,t)}createBookmark(e){return this.appDb.createBookmark(e)}updateBookmark(e){return this.appDb.updateBookmark(e)}deleteBookmark(e){this.appDb.deleteBookmark(e)}async searchDatabase(e){let t=this.cm.getDriver(e.connectionId,e.database);return Fn(t,{searchTerm:e.searchTerm,scope:e.scope,schemaName:e.schemaName,tableNames:e.tableNames,resultsPerTable:e.resultsPerTable??50,sessionId:e.sessionId},()=>{},()=>!1)}async exportData(e){let t=e.filePath;this.rejectServerFileAccess(t);let n=this.cm.getDriver(e.connectionId,e.database);if(!t)throw Error("Export requires a file path");let r=this.emitMessage?(i)=>this.emitMessage("export.progress",{rowCount:i}):void 0;return{...await on(n,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,includeHeaders:e.includeHeaders,delimiter:e.delimiter,encoding:e.encoding,utf8Bom:e.utf8Bom,batchSize:e.batchSize,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins},t,void 0,r),filePath:t}}async exportPreview(e){let t=this.cm.getDriver(e.connectionId,e.database);return an(t,{schema:e.schema,table:e.table,format:e.format,columns:e.columns,keyColumns:e.keyColumns,delimiter:e.delimiter,filters:e.filters,sort:e.sort,limit:e.limit,autoJoins:e.autoJoins})}async exportPreviewRows(e){let t=this.cm.getDriver(e.connectionId,e.database),{sql:n,params:r}=Te({schema:e.schema,table:e.table,format:"csv",columns:e.columns,filters:e.filters,sort:e.sort,autoJoins:e.autoJoins},t),s=r.length+1,i=`${n} LIMIT ${t.placeholder(s)}`,a=(await t.execute(i,[...r,e.limit])).rows,c=a.length>0?Object.keys(a[0]):e.columns??[];return{rows:a,columns:c}}async importData(e){this.rejectServerFileAccess(e.filePath);let t=this.cm.getDriver(e.connectionId,e.database),n=this.resolveImportStream(e.filePath,e.fileContent),r=this.emitMessage?(s)=>this.emitMessage("import.progress",{rowCount:s}):void 0;return ve(t,n,{schema:e.schema,table:e.table,format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,mappings:e.mappings,batchSize:e.batchSize},void 0,r)}async importPreview(e){this.rejectServerFileAccess(e.filePath);let t=this.resolveImportPreviewStream(e.filePath,e.fileContent),n=await dn(t,{format:e.format,delimiter:e.delimiter,hasHeader:e.hasHeader,limit:e.limit});if(e.filePath)try{let r=Bun.file(e.filePath);n.fileSizeBytes=r.size}catch{}return n}rejectServerFileAccess(e){if(!this.allowServerFileAccess&&e!==void 0)throw Error("Server file access is not available in this runtime")}rejectServerSqliteConfig(e){if(e?.type==="sqlite")this.rejectServerFileAccess(e.path)}resolveImportStream(e,t){if(e)return Bun.file(e).stream();if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream(e,t){if(e){let s=Bun.file(e).stream().getReader(),i=65536,o=0;return new ReadableStream({async pull(a){let{done:c,value:u}=await s.read();if(c){a.close();return}if(o+=u.byteLength,o>=65536){a.enqueue(u),a.close(),s.releaseLock();return}a.enqueue(u)},cancel(){s.releaseLock()}})}if(t!==void 0)return new ReadableStream({start(n){n.enqueue(new TextEncoder().encode(t)),n.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting(e,t){this.appDb.setSetting(e,t)}async encryptSecrets(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt(e)}async decryptConfig(e){if(!this.encryption)throw Error("Encryption not available");return this.encryption.decrypt(e)}async showOpenDialog({filters:e,multiple:t}){if(!this.Utils)throw Error("Utils not available");let n=e&&e.length>0?e.flatMap((i)=>i.extensions.map((o)=>`*.${o}`)).join(","):"*",s=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:n,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:t??!1})).filter((i)=>i!=="");return{paths:s,cancelled:s.length===0}}async showSaveDialog({defaultName:e}){if(!this.Utils)throw Error("Utils not available");let n=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!n||n==="")return{path:null,cancelled:!0};return{path:e?`${n}/${e}`:n,cancelled:!1}}formatSql(e){return Yn(e)}async generateSql(e){let t=this.cm.getDriver(e.connectionId,e.database),n=await t.loadSchema(),r=kn(n),s=Ln(this.appDb.getAllSettings());return{sql:await $n(s,{prompt:e.prompt,schemaContext:r,dialect:t.getDriverType()})}}saveWorkspace(e){this.appDb.saveWorkspace(e)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let e=Bun.file(this.demoDbSourcePath);if(!await e.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,e);let t={type:"sqlite",path:this.demoDbTargetPath},n=this.appDb.createConnection({name:"Bookstore (Demo)",config:t});return await this.cm.connect(n.id),n}agentHello(){return{version:this.appVersion,mode:this.mode,pid:process.pid,protocol:Ms}}proposeWrite(e){return this.proposals.create(e)}listProposals(e){return this.proposals.list(e)}getProposal(e){return this.proposals.get(e)}async waitForProposal(e,t){return this.proposals.wait(e,t)}cancelProposal(e){return this.proposals.cancel(e)}resolveProposal(e){return this.proposals.resolve(e)}getUiSnapshot(){return this.uiSnapshot??{tabs:[],activeTabId:null,activeConnectionId:null,updatedAt:0}}setUiSnapshot(e){this.uiSnapshot=e}sendUiCommand(e){this.emitMessage?.("cli.command",e)}getSessionManager(){return this.sessionManager}dispose(){this.unsubscribeProposals(),this.proposals.dispose()}}var Ms=1;var Wn=T(()=>{le();Pn();tt();rt();qn();xe();Hn();Kn()});function Fs(e,t){if(e===void 0)return;let n=e.trim();if(n==="")return;if(!ot(n,t))throw Error("where must be a single boolean expression: no statement separators, comments, unbalanced parentheses or backslashes in quoted text")}function Hs(e,t){return e.listConnections().find((n)=>n.id===t)?.config.type}function Me(e,t){if(!t)throw Error("connectionId is required");if(!e.listConnections().some((n)=>n.id===t))throw Error(`Unknown connection: ${t}`)}async function jn(e,t){try{await e.destroySession(t)}catch(n){console.warn(`Failed to destroy agent session ${t}`,n)}}async function bt(e,t,n,r){Me(e,t);let s=await e.createSession(t,n,{readOnly:!0,label:qs});if(s.readOnly!==!0)throw await jn(e,s.sessionId),new b("READ_ONLY_SESSION","The database did not confirm a read-only agent session");try{return await r(s.sessionId)}finally{await jn(e,s.sessionId)}}function Bs(e){if(e===void 0)return $s;if(!Number.isFinite(e)||e<0)throw Error("timeoutMs must be a non-negative number");return Math.min(e,Us)}function zn(e){return{"connections.list":()=>e.listConnections(),"connections.create":({name:t,config:n,readOnly:r,color:s,groupName:i})=>e.createConnection({name:t,config:n,readOnly:r,color:s,groupName:i}),"connections.update":({id:t,name:n,config:r,readOnly:s,color:i,groupName:o})=>e.updateConnection({id:t,name:n,config:r,readOnly:s,color:i,groupName:o}),"connections.setReadOnly":({id:t,readOnly:n})=>e.setConnectionReadOnly(t,n),"connections.setGroup":({id:t,groupName:n})=>e.setConnectionGroup(t,n),"connections.listGroups":()=>e.listConnectionGroups(),"connections.renameGroup":({oldName:t,newName:n})=>{e.renameConnectionGroup(t,n)},"connections.deleteGroup":({groupName:t})=>{e.deleteConnectionGroup(t)},"connections.delete":async({id:t})=>{await e.deleteConnection(t)},"connections.test":async({config:t})=>e.testConnection(t),"connections.connect":async({connectionId:t,password:n,config:r,encryptedSecrets:s,name:i,encryptedConfig:o})=>{await e.connect(t,n,{config:r,encryptedSecrets:s,name:i,encryptedConfig:o})},"connections.disconnect":async({connectionId:t})=>{await e.disconnect(t)},"connections.listOpenHandles":()=>e.listConnectionHandles(),"connections.terminateHandle":async({connectionId:t,database:n,handleId:r})=>{await e.terminateConnectionHandle(t,n,r)},"session.create":async({connectionId:t,database:n,readOnly:r,label:s})=>e.createSession(t,n,{readOnly:r,label:s}),"session.destroy":async({sessionId:t})=>{await e.destroySession(t)},"session.list":({connectionId:t})=>e.listSessions(t),"databases.list":async({connectionId:t})=>e.listDatabases(t),"databases.listForConfig":async({config:t})=>e.listDatabasesForConfig(t),"databases.activate":async({connectionId:t,database:n})=>{await e.activateDatabase(t,n)},"databases.deactivate":async({connectionId:t,database:n})=>{await e.deactivateDatabase(t,n)},"schema.load":async({connectionId:t,database:n,sessionId:r})=>e.getDriver(t,n).loadSchema(r),"query.execute":async({connectionId:t,sql:n,queryId:r,params:s,database:i,statements:o,sessionId:a,searchPath:c})=>{if(o&&o.length>0)return e.executeStatements(t,o,i,a);return e.executeQuery(t,n,s,r,i,a,c)},"query.submit":({connectionId:t,sql:n,queryId:r,params:s,database:i,sessionId:o,searchPath:a})=>(e.submitQuery(t,n,s,r,i,o,a),{queryId:r}),"query.submitExplain":({connectionId:t,sql:n,analyze:r,queryId:s,database:i,sessionId:o,searchPath:a})=>(e.submitExplain(t,n,r??!1,s,i,o,a),{queryId:s}),"query.cancel":async({queryId:t})=>({cancelled:await e.cancelQuery(t)}),"query.format":({sql:t})=>({sql:e.formatSql(t)}),"tx.begin":async({connectionId:t,database:n,sessionId:r})=>{await e.beginTransaction(t,n,r)},"tx.commit":async({connectionId:t,database:n,sessionId:r})=>{await e.commitTransaction(t,n,r)},"tx.rollback":async({connectionId:t,database:n,sessionId:r})=>{await e.rollbackTransaction(t,n,r)},"transaction.getLog":(t)=>e.getTransactionLog(t),"transaction.clearLog":({connectionId:t,database:n,sessionId:r})=>{e.clearTransactionLog(t,n,r)},"search.searchDatabase":async(t)=>e.searchDatabase(t),"export.exportData":async(t)=>e.exportData(t),"export.preview":async(t)=>({content:await e.exportPreview(t)}),"export.previewRows":async(t)=>e.exportPreviewRows(t),"import.importData":async(t)=>e.importData(t),"import.preview":async(t)=>e.importPreview(t),"history.list":(t)=>e.listHistory(t),"history.clear":({connectionId:t})=>{e.clearHistory(t)},"views.save":({connectionId:t,schemaName:n,tableName:r,name:s,config:i})=>{if(!s?.trim())throw Error("View name is required");if(!t)throw Error("connectionId is required");if(!r)throw Error("tableName is required");if(e.listSavedViews(t,n,r).some((a)=>a.name===s.trim()))throw Error(`A view named "${s.trim()}" already exists for this table`);return e.createSavedView({connectionId:t,schemaName:n,tableName:r,name:s.trim(),config:i})},"views.update":({id:t,name:n,config:r})=>{if(!t)throw Error("View id is required");if(!n?.trim())throw Error("View name is required");let s=e.getSavedViewById(t);if(!s)throw Error(`Saved view not found: ${t}`);if(e.listSavedViews(s.connectionId,s.schemaName,s.tableName).some((o)=>o.id!==t&&o.name===n.trim()))throw Error(`A view named "${n.trim()}" already exists for this table`);return e.updateSavedView({id:t,name:n.trim(),config:r})},"views.delete":({id:t})=>{e.deleteSavedView(t)},"views.listByConnection":({connectionId:t})=>e.listSavedViewsByConnection(t),"bookmarks.list":({connectionId:t,search:n})=>e.listBookmarks(t,n),"bookmarks.create":({connectionId:t,database:n,name:r,description:s,sql:i})=>{if(!r?.trim())throw Error("Bookmark name is required");return e.createBookmark({connectionId:t,database:n,name:r.trim(),description:s,sql:i})},"bookmarks.update":({id:t,name:n,description:r,sql:s})=>{if(!t)throw Error("Bookmark id is required");if(!n?.trim())throw Error("Bookmark name is required");return e.updateBookmark({id:t,name:n.trim(),description:r,sql:s})},"bookmarks.delete":({id:t})=>{e.deleteBookmark(t)},"settings.getAll":()=>e.getAllSettings(),"settings.set":({key:t,value:n})=>{e.setSetting(t,n)},"storage.encryptSecrets":async({secrets:t})=>{if(!e.encryptSecrets)throw Error("Encryption not available");return{encryptedSecrets:await e.encryptSecrets(t)}},"storage.decryptConfig":async({encryptedConfig:t})=>{if(!e.decryptConfig)throw Error("Encryption not available");return{config:await e.decryptConfig(t)}},"ai.generateSql":async(t)=>e.generateSql(t),"workspace.save":({data:t})=>{e.saveWorkspace(t)},"workspace.load":()=>e.loadWorkspace(),"system.showOpenDialog":async(t)=>{if(!e.showOpenDialog)return{paths:[],cancelled:!0};return e.showOpenDialog(t)},"system.showSaveDialog":async(t)=>{if(!e.showSaveDialog)return{path:null,cancelled:!0};return e.showSaveDialog(t)},"agent.hello":()=>e.agentHello(),"agent.schema":async({connectionId:t,database:n})=>bt(e,t,n,(r)=>e.getDriver(t,n).loadSchema(r)),"agent.query":async({connectionId:t,database:n,sql:r,queryId:s,params:i,searchPath:o})=>{if(!r?.trim())throw Error("sql is required");if(!s)throw Error("queryId is required");return bt(e,t,n,(a)=>e.executeQuery(t,r,i,s,n,a,o))},"agent.search":async(t)=>bt(e,t.connectionId,t.database,(n)=>e.searchDatabase({...t,sessionId:n})),"agent.proposeWrite":({connectionId:t,database:n,sql:r,reason:s})=>{if(Me(e,t),!r?.trim())throw Error("sql is required");return{proposalId:e.proposeWrite({connectionId:t,database:n,sql:r.trim(),reason:s?.trim()||void 0}).id}},"agent.proposals.list":(t)=>e.listProposals(t),"agent.proposals.get":({proposalId:t})=>{if(!t)throw Error("proposalId is required");let n=e.getProposal(t);if(!n)throw Error(`Proposal not found: ${t}`);return n},"agent.proposals.wait":async({proposalId:t,timeoutMs:n})=>{if(!t)throw Error("proposalId is required");return e.waitForProposal(t,Bs(n))},"agent.proposals.cancel":({proposalId:t})=>{if(!t)throw Error("proposalId is required");e.cancelProposal(t)},"agent.proposals.resolve":({proposalId:t,status:n,result:r,error:s})=>{if(!t)throw Error("proposalId is required");if(!n)throw Error("status is required");return e.resolveProposal({proposalId:t,status:n,result:r,error:s})},"ui.state":()=>e.getUiSnapshot(),"ui.openTable":({connectionId:t,database:n,schema:r,table:s,where:i,limit:o})=>{if(Me(e,t),!s?.trim())throw Error("table is required");if(o!==void 0&&(!Number.isInteger(o)||o<=0))throw Error("limit must be a positive integer");return Fs(i,Hs(e,t)),e.sendUiCommand({kind:"open-table",connectionId:t,database:n,schema:r??"",table:s.trim(),where:i,limit:o}),{ok:!0}},"ui.openConsole":({connectionId:t,database:n,sql:r})=>(Me(e,t),e.sendUiCommand({kind:"open-console",connectionId:t,database:n,sql:r}),{ok:!0}),"ui.snapshot.set":({snapshot:t})=>{if(!t||!Array.isArray(t.tabs))throw Error("snapshot is required");e.setUiSnapshot(t)},"demo.initialize":async()=>{if(!e.initializeDemo)throw Error("Demo initialization is not available");return e.initializeDemo()}}}var Us=600000,$s=30000,qs="cli";var Gn=T(()=>{at();P()});function Qs(e){if(!e)throw Error("AppDatabase is required");return e}function Vn(e,t,n,r,s){let i=Qs(n),o=t??new ce(e,void 0,i),a=new gt(e,i,(u,l,m)=>{o.sessionLog.resetPendingCount(u,l,m)}),c=new Et(e,o,i,{encryption:s?.encryption,Utils:r,emitMessage:s?.emitMessage,sessionManager:a,demoDbSourcePath:s?.demoDbSourcePath,demoDbTargetPath:s?.demoDbTargetPath,allowServerFileAccess:s?.allowServerFileAccess,appVersion:s?.appVersion,mode:s?.mode});return{handlers:zn(c),sessionManager:a,adapter:c}}var Jn=T(()=>{xe();xn();Wn();Gn()});class Ct{inner;constructor(e){this.inner=e}log(e,t,n,r){let s=e.replace(/\s+/g," ").trim(),i=t&&t.length>0;if(r)console.debug(`[SQL ERROR] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`,r);else if(n!==void 0)console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""} (${n}ms)`);else console.debug(`[SQL] ${s}${i?` -- params: ${JSON.stringify(t)}`:""}`)}async execute(e,t,n,r){let s=performance.now();try{let i=await this.inner.execute(e,t,n,r);return this.log(e,t,Math.round(performance.now()-s)),i}catch(i){throw this.log(e,t,Math.round(performance.now()-s),i),i}}async*iterate(e,t,n,r,s){this.log(e,t),yield*this.inner.iterate(e,t,n,r,s)}async importBatch(e,t,n,r){let s=`INSERT INTO ${e} (${t.join(", ")}) VALUES ... [${n.length} rows]`,i=performance.now();try{let o=await this.inner.importBatch(e,t,n,r);return this.log(s,void 0,Math.round(performance.now()-i)),o}catch(o){throw this.log(s,void 0,Math.round(performance.now()-i),o),o}}connect(e){return this.inner.connect(e)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession(e,t){return this.inner.reserveSession(e,t)}releaseSession(e){return this.inner.releaseSession(e)}getSessionIds(){return this.inner.getSessionIds()}isSessionReadOnly(e){return this.inner.isSessionReadOnly(e)}cancel(e,t){return this.inner.cancel(e,t)}ping(){return this.inner.ping()}async loadSchema(e){console.debug("[SQL] loadSchema started"+(e?` (session: ${e})`:""));let t=performance.now();try{let n=await this.inner.loadSchema(e),r=Object.values(n.tables).reduce((s,i)=>s+i.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${n.schemas.length} schemas, ${r} tables (${Math.round(performance.now()-t)}ms)`),n}catch(n){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-t)}ms)`,n),n}}beginTransaction(e){return this.inner.beginTransaction(e)}commit(e){return this.inner.commit(e)}rollback(e){return this.inner.rollback(e)}inTransaction(e){return this.inner.inTransaction(e)}isTxAborted(e){return this.inner.isTxAborted(e)}isIterating(e){return this.inner.isIterating(e)}getDriverType(){return this.inner.getDriverType()}listConnectionHandles(){return this.inner.listConnectionHandles()}terminateConnectionHandle(e){return this.inner.terminateConnectionHandle(e)}quoteIdentifier(e){return this.inner.quoteIdentifier(e)}qualifyTable(e,t){return this.inner.qualifyTable(e,t)}emptyInsertSql(e){return this.inner.emptyInsertSql(e)}placeholder(e){return this.inner.placeholder(e)}}var{SQL:Ys}=globalThis.Bun;class pe{url;resetFn;initFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;metadata=new Map;nextHandleNumber=1;constructor(e,t,n){this.url=e;this.resetFn=t;this.initFn=n}async connect(){if(this.systemConn=this.createSql("system"),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1"),this.initFn)await this.initFn(this.systemConn)}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.markUsed(this.systemConn),this.systemConn}async createConnection(){let e=this.createSql("leased");if(this.connections.add(e),this.initFn)try{await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}return e}async acquireConnection(){if(this.idleConn){let e=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),this.setRole(e,"leased"),this.markUsed(e),e}return this.createConnection()}async releaseConnection(e){if(!this.connections.has(e)){try{await e.close()}catch{}return}if(!this.idleConn){if(this.resetFn||this.initFn)try{if(this.resetFn)await this.resetFn(e);if(this.initFn)await this.initFn(e)}catch{await this.destroyConnection(e);return}this.setRole(e,"idle"),this.markUsed(e),this.idleConn=e,this.scheduleIdleTimeout()}else await this.destroyConnection(e)}async destroyConnection(e){if(this.idleConn===e)this.idleConn=null,this.clearIdleTimer();if(this.systemConn===e)this.systemConn=null;this.connections.delete(e),this.metadata.delete(e);try{await e.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn)await this.destroyConnection(this.systemConn);let e=this.createSql("system");this.connections.add(e);try{if(await e.unsafe("SELECT 1"),this.initFn)await this.initFn(e)}catch(t){throw await this.destroyConnection(e),t}this.systemConn=e}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let e=[...this.connections];this.connections.clear(),this.metadata.clear(),this.systemConn=null,await Promise.allSettled(e.map((t)=>t.close()))}getConnectionId(e){return this.metadata.get(e)?.handleId}snapshot(){return[...this.connections].map((e)=>this.metadata.get(e)).filter((e)=>e!==void 0).map((e)=>({...e}))}async terminateConnection(e){let t=this.findConnectionByHandleId(e);if(!t)return!1;if(t===this.systemConn)return await this.reconnectSystemConnection(),!0;return await this.destroyConnection(t),!0}createSql(e){let t=new Ys({url:this.url,max:1}),n=Date.now();return this.metadata.set(t,{handleId:`pool-${this.nextHandleNumber}`,role:e,createdAt:n,lastUsedAt:n}),this.nextHandleNumber+=1,t}findConnectionByHandleId(e){for(let t of this.connections)if(this.metadata.get(t)?.handleId===e)return t;return}markUsed(e){let t=this.metadata.get(e);if(!t)return;t.lastUsedAt=Date.now()}setRole(e,t){let n=this.metadata.get(e);if(!n)return;n.role=t}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},Ks)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var Ks=30000;var Tt=()=>{};function fe(e){let t=e instanceof Error?e.message:String(e),n=e?.errno??e?.code;if(n==="57014")return new R("QUERY_CANCELED",t,{cause:e});if(/ECONNREFUSED|connection refused/i.test(t))return new D("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new D("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new D("HOST_NOT_FOUND",t,{cause:e});if(/too many connections|connection limit/i.test(t))return new D("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new D("SSL_ERROR",t,{cause:e});if(n?.startsWith("28")||/authentication failed|password authentication/i.test(t))return new Se(t,{cause:e});if(n==="3D000"||/database .* does not exist/i.test(t))return new D("DATABASE_NOT_FOUND",t,{cause:e});if(n==="23505"||/violates unique constraint|duplicate key/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(n==="23503"||/violates foreign key constraint/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(n==="23514"||/violates check constraint/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(n==="23502"||/violates not-null constraint/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(n==="42601"||/syntax error/i.test(t))return new R("QUERY_SYNTAX",t,{cause:e});if(n==="42P01"||/relation .* does not exist/i.test(t))return new R("TABLE_NOT_FOUND",t,{cause:e});if(n==="42703"||/column .* does not exist/i.test(t))return new R("COLUMN_NOT_FOUND",t,{cause:e});if(n==="42501"||/permission denied/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});if(n==="40001")return new R("SERIALIZATION_FAILURE",t,{cause:e});if(n==="40P01")return new R("DEADLOCK_DETECTED",t,{cause:e});if(n==="25P02")return new R("TRANSACTION_ABORTED",t,{cause:e});if(n?.startsWith("42")||n?.startsWith("22"))return new R("QUERY_EXECUTION",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}function ee(e){let t=e instanceof Error?e.message:String(e);if(/unable to open database|cannot open/i.test(t))return new D("CONNECTION_REFUSED",t,{cause:e});if(/UNIQUE constraint failed/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(/FOREIGN KEY constraint failed/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(/CHECK constraint failed/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(/NOT NULL constraint failed/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(/no such table/i.test(t))return new R("TABLE_NOT_FOUND",t,{cause:e});if(/no such column/i.test(t))return new R("COLUMN_NOT_FOUND",t,{cause:e});if(/syntax error|near /i.test(t))return new R("QUERY_SYNTAX",t,{cause:e});if(/authorization denied|not authorized/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}function Ue(e){let t=e instanceof Error?e.message:String(e),n=e?.errno;if(n===3024||n===1969)return new R("QUERY_CANCELED",t,{cause:e});if(/ECONNREFUSED|connection refused/i.test(t)||n===2003)return new D("CONNECTION_REFUSED",t,{cause:e});if(/timeout|timed out/i.test(t))return new D("CONNECTION_TIMEOUT",t,{cause:e});if(/ENOTFOUND|getaddrinfo/i.test(t))return new D("HOST_NOT_FOUND",t,{cause:e});if(/too many connections/i.test(t)||n===1040)return new D("CONNECTION_LIMIT",t,{cause:e});if(/SSL|TLS|certificate/i.test(t))return new D("SSL_ERROR",t,{cause:e});if(n===1045||/access denied/i.test(t))return new Se(t,{cause:e});if(n===1049||/unknown database/i.test(t))return new D("DATABASE_NOT_FOUND",t,{cause:e});if(n===1062||/duplicate entry/i.test(t))return new _("CONSTRAINT_UNIQUE",t,{cause:e});if(n===1451||n===1452||/foreign key constraint/i.test(t)||/cannot delete or update a parent row/i.test(t)||/cannot add or update a child row/i.test(t))return new _("CONSTRAINT_FK",t,{cause:e});if(n===3819||/check constraint/i.test(t))return new _("CONSTRAINT_CHECK",t,{cause:e});if(n===1048||/cannot be null/i.test(t))return new _("CONSTRAINT_NOT_NULL",t,{cause:e});if(n===1213||/deadlock found/i.test(t))return new R("DEADLOCK_DETECTED",t,{cause:e});if(n===1205||/lock wait timeout exceeded/i.test(t))return new R("SERIALIZATION_FAILURE",t,{cause:e});if(n===1064||/syntax error|you have an error in your sql syntax/i.test(t))return new R("QUERY_SYNTAX",t,{cause:e});if(n===1146||/table .* doesn't exist/i.test(t))return new R("TABLE_NOT_FOUND",t,{cause:e});if(n===1054||/unknown column/i.test(t))return new R("COLUMN_NOT_FOUND",t,{cause:e});if(n===1142||n===1143||/command denied|access denied/i.test(t))return new b("PERMISSION_DENIED",t,{cause:e});return new b("UNKNOWN",t,{cause:e})}var $e=T(()=>{P()});function te(e){let t=e;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;return 0}var Zo,ea,ta,na,ra,sa;var Xn=T(()=>{M();Zo=new Set(["integer","serial","float","numeric"]),ea=new Set(["boolean"]),ta=new Set(["timestamp","date"]),na=new Set(["text","varchar","char"]),ra=new Set(["json"]),sa=new Set(["array"])});var Zn=T(()=>{Xn();M()});var er=T(()=>{Ce();G();Zn()});function ne(e,t){let n=z(t).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(n)){if(e.txActive=!0,"txAborted"in e)e.txAborted=!1}else if(/^(COMMIT|END)\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}else if(/^ROLLBACK\b/.test(n)&&!/^ROLLBACK\s+TO\b/.test(n)){if(e.txActive=!1,"txAborted"in e)e.txAborted=!1}}function B(e){let t=e?.code;if(typeof t==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(t))return!0;let n=e instanceof Error?e.message:String(e);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(n)}async function x(e,t){if(t?.rollback)try{await e.unsafe("ROLLBACK")}catch{}try{await e.close()}catch{}}var qe=T(()=>{er()});function Ws(e){switch(e.toLowerCase()){case"int":case"integer":case"bigint":case"smallint":case"tinyint":case"mediumint":return"integer";case"float":case"double":return"float";case"decimal":case"numeric":return"numeric";case"bit":case"boolean":case"bool":return"boolean";case"text":case"tinytext":case"mediumtext":case"longtext":return"text";case"varchar":return"varchar";case"char":return"char";case"date":return"date";case"time":return"time";case"datetime":case"timestamp":return"timestamp";case"json":return"json";case"binary":case"varbinary":case"blob":case"tinyblob":case"mediumblob":case"longblob":return"binary";case"enum":case"set":return"enum";default:return"unknown"}}class At{pool=null;connected=!1;sessions=new Map;readOnlySessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let t=`mysql://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}`,n=e.initSql?.trim(),r=n?async(s)=>{await s.unsafe(n)}:void 0;this.pool=new pe(t,(s)=>s.unsafe("RESET CONNECTION"),r);try{await this.pool.connect()}catch(s){let i=this.pool;throw this.pool=null,await i.disconnectAll().catch(()=>{}),s instanceof b?s:Ue(s)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await x(e.conn,{rollback:e.txActive});if(this.sessions.clear(),this.readOnlySessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e,t){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let n=await this.pool.createConnection();if(t?.readOnly){let r=["SET SESSION TRANSACTION READ ONLY"];r.push("SET NAMES utf8mb4");try{for(let i of r)await n.unsafe(i);let s=Math.floor(t.statementTimeoutMs??0);if(Number.isFinite(s)&&s>0)r.push(await this.setStatementTimeout(n,s))}catch(s){throw await x(n),await this.pool.destroyConnection(n),s instanceof b?s:Ue(s)}this.readOnlySessions.set(e,r)}this.sessions.set(e,{conn:n,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){this.readOnlySessions.delete(e);let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await x(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==I)}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async reassertReadOnly(e,t){let n=e===void 0?void 0:this.readOnlySessions.get(e);if(!n)return;for(let r of n)await t.unsafe(r)}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s;if(s)await this.reassertReadOnly(n,i);let a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,m=Math.round(performance.now()-a),f=[...l];if(s)ne(s,e);return{columns:f.length>0?Object.keys(f[0]).map((d)=>({name:d,dataType:"unknown"})):[],rows:f,rowCount:f.length,affectedRows:te(l),durationMs:m}}catch(l){throw l instanceof b?l:Ue(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=await this.getSchemas(n),s=r.map((d)=>d.name),i={};for(let d of r)i[d.name]=await this.getTables(n,d.name);let[o,a,c,u]=await Promise.all([n.unsafe(`SELECT
145
148
  c.TABLE_SCHEMA AS table_schema,
146
149
  c.TABLE_NAME AS table_name,
147
150
  c.COLUMN_NAME AS column_name,
@@ -195,10 +198,10 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
195
198
  AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
196
199
  GROUP BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME,
197
200
  kcu.CONSTRAINT_NAME, kcu.TABLE_SCHEMA, kcu.TABLE_NAME
198
- ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,s)]),l={};for(let m of o){let g=`${m.table_schema}.${m.table_name}`;if(!l[g])l[g]=[];l[g].push({name:m.column_name,dataType:Xr(m.data_type),nullable:m.is_nullable==="YES",defaultValue:m.column_default,isPrimaryKey:m.column_key==="PRI",isAutoIncrement:(m.extra??"").includes("auto_increment"),maxLength:m.character_maximum_length??void 0})}let d={};for(let m of a){let g=`${m.table_schema}.${m.table_name}`;if(!d[g])d[g]=[];d[g].push({name:m.index_name,columns:typeof m.columns==="string"?m.columns.split(","):[m.columns],isUnique:m.non_unique===0||m.non_unique==="0",isPrimary:m.index_name==="PRIMARY"})}let p={};for(let m of c){let g=`${m.table_schema}.${m.table_name}`;if(!p[g])p[g]=[];p[g].push({name:m.constraint_name,columns:typeof m.columns==="string"?m.columns.split(","):[m.columns],referencedSchema:m.referenced_schema,referencedTable:m.referenced_table,referencedColumns:typeof m.referenced_columns==="string"?m.referenced_columns.split(","):[m.referenced_columns],onUpdate:m.on_update,onDelete:m.on_delete})}let h={};for(let m of u){let g=`${m.referenced_schema}.${m.referenced_table}`;if(!h[g])h[g]=[];h[g].push({constraintName:m.constraint_name,referencingSchema:m.referencing_schema,referencingTable:m.referencing_table,referencingColumns:typeof m.referencing_columns==="string"?m.referencing_columns.split(","):[m.referencing_columns],referencedColumns:typeof m.referenced_columns==="string"?m.referenced_columns.split(","):[m.referenced_columns]})}for(let m of r)for(let g of i[m.name]){let y=`${m.name}.${g.name}`;if(!l[y])l[y]=[];if(!d[y])d[y]=[];if(!p[y])p[y]=[];if(!h[y])h[y]=[]}return{schemas:r,tables:i,columns:l,indexes:d,foreignKeys:p,referencingForeignKeys:h}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe("SELECT DATABASE() AS name")]}async getTables(e,t){return this.ensureConnected(),[...await e.unsafe(`SELECT table_name AS name, table_type
201
+ ORDER BY kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.CONSTRAINT_NAME`,s)]),l={};for(let d of o){let h=`${d.table_schema}.${d.table_name}`;if(!l[h])l[h]=[];l[h].push({name:d.column_name,dataType:Ws(d.data_type),nullable:d.is_nullable==="YES",defaultValue:d.column_default,isPrimaryKey:d.column_key==="PRI",isAutoIncrement:(d.extra??"").includes("auto_increment"),maxLength:d.character_maximum_length??void 0})}let m={};for(let d of a){let h=`${d.table_schema}.${d.table_name}`;if(!m[h])m[h]=[];m[h].push({name:d.index_name,columns:typeof d.columns==="string"?d.columns.split(","):[d.columns],isUnique:d.non_unique===0||d.non_unique==="0",isPrimary:d.index_name==="PRIMARY"})}let f={};for(let d of c){let h=`${d.table_schema}.${d.table_name}`;if(!f[h])f[h]=[];f[h].push({name:d.constraint_name,columns:typeof d.columns==="string"?d.columns.split(","):[d.columns],referencedSchema:d.referenced_schema,referencedTable:d.referenced_table,referencedColumns:typeof d.referenced_columns==="string"?d.referenced_columns.split(","):[d.referenced_columns],onUpdate:d.on_update,onDelete:d.on_delete})}let g={};for(let d of u){let h=`${d.referenced_schema}.${d.referenced_table}`;if(!g[h])g[h]=[];g[h].push({constraintName:d.constraint_name,referencingSchema:d.referencing_schema,referencingTable:d.referencing_table,referencingColumns:typeof d.referencing_columns==="string"?d.referencing_columns.split(","):[d.referencing_columns],referencedColumns:typeof d.referenced_columns==="string"?d.referenced_columns.split(","):[d.referenced_columns]})}for(let d of r)for(let h of i[d.name]){let y=`${d.name}.${h.name}`;if(!l[y])l[y]=[];if(!m[y])m[y]=[];if(!f[y])f[y]=[];if(!g[y])g[y]=[]}return{schemas:r,tables:i,columns:l,indexes:m,foreignKeys:f,referencingForeignKeys:g}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe("SELECT DATABASE() AS name")]}async getTables(e,t){return this.ensureConnected(),[...await e.unsafe(`SELECT table_name AS name, table_type
199
202
  FROM information_schema.tables
200
203
  WHERE table_schema = ?
201
- ORDER BY table_name`,[t])].map((r)=>({schema:t,name:r.name,type:r.table_type==="VIEW"?"view":"table"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=this.resolveSession(s);if(i?.txActive)throw Error("Cannot iterate on a session with an active transaction");let o=i?i.conn:await this.pool.acquireConnection(),a=!i;if(i)i.txActive=!0,i.iterating=!0;try{await o.unsafe("START TRANSACTION WITH CONSISTENT SNAPSHOT");let c=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let u=`${e} LIMIT ? OFFSET ?`,d=[...await o.unsafe(u,[...t??[],n,c])];if(d.length===0)break;if(yield d,d.length<n)break;c+=n}await o.unsafe("COMMIT")}catch(c){try{await o.unsafe("ROLLBACK")}catch{}throw c}finally{if(i)i.txActive=!1,i.iterating=!1;if(a)await this.pool.releaseConnection(o)}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let d=0;d<t.length;d++)i.push(n[u][t[d]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("START TRANSACTION"),t.txActive=!0}else{if(this.sessions.has(O)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("START TRANSACTION")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(O,{conn:t,txActive:!0,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??O,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1}catch(r){if(F(r))throw n.txActive=!1,new T("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch{}throw r}finally{if(t===O)this.sessions.delete(O),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??O,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch(r){if(F(r))n.txActive=!1;throw r}finally{if(t===O)this.sessions.delete(O),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??O;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){return!1}isIterating(e){let t=e??O;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"mysql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`\`${e.replace(/`/g,"``")}\``}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} () VALUES ()`}placeholder(e){return"?"}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===O,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:!1,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}}var O="__default__";var _n=C(()=>{k();P();ot();De();lt()});async function Zr(e){await e.unsafe("RESET ALL"),await e.unsafe("RESET ROLE"),await e.unsafe("RESET SESSION AUTHORIZATION"),await e.unsafe("UNLISTEN *"),await e.unsafe("SELECT pg_advisory_unlock_all()"),await e.unsafe("DISCARD SEQUENCES"),await e.unsafe("DISCARD TEMP")}function es(e){switch(e.toLowerCase()){case"integer":case"bigint":case"smallint":return"integer";case"serial":case"bigserial":case"smallserial":return"serial";case"real":case"double precision":return"float";case"numeric":case"decimal":case"money":return"numeric";case"boolean":return"boolean";case"text":return"text";case"character varying":return"varchar";case"character":return"char";case"date":return"date";case"time without time zone":case"time with time zone":return"time";case"timestamp without time zone":case"timestamp with time zone":return"timestamp";case"json":case"jsonb":return"json";case"uuid":return"uuid";case"bytea":case"bit":case"bit varying":return"binary";default:return"unknown"}}class dt{pool=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="postgresql")throw Error("PostgresDriver requires a postgresql connection config");let t=new URLSearchParams;if(e.ssl)t.set("sslmode",e.ssl);t.set("application_name","dotaz");let n=`postgres://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}?${t}`,r=e.initSql?.trim(),s=r?async(i)=>{await i.unsafe(r)}:void 0;this.pool=new le(n,Zr,s);try{await this.pool.connect()}catch(i){let o=this.pool;throw this.pool=null,await o.disconnectAll().catch(()=>{}),i instanceof T?i:at(i)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await V(e.conn,{rollback:!0});if(this.sessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let t=await this.pool.createConnection();this.sessions.set(e,{conn:t,txActive:!1,txAborted:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await V(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==I)}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s,a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,d=Math.round(performance.now()-a),p=[...l];if(s)_e(s,e);return{columns:p.length>0?Object.keys(p[0]).map((m)=>({name:m,dataType:"unknown"})):[],rows:p,rowCount:p.length,affectedRows:J(l),durationMs:d}}catch(l){if(s?.txActive&&!F(l))s.txAborted=!0;throw l instanceof T?l:at(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=!!process.env.DEBUG_SQL,s=async(f,S)=>{if(!r)return S();let w=performance.now();console.debug(`[SQL] loadSchema: ${f} \u2014 started`);try{let b=await S();return console.debug(`[SQL] loadSchema: ${f} \u2014 completed (${Math.round(performance.now()-w)}ms)`),b}catch(b){throw console.debug(`[SQL ERROR] loadSchema: ${f} \u2014 failed (${Math.round(performance.now()-w)}ms)`,b),b}},i=await s("getSchemas",()=>this.getSchemas(n)),a=`{${i.map((f)=>f.name).join(",")}}`,c={};for(let f of i){let S=await s(`getTables(${f.name})`,()=>this.getTables(n,f.name)),w=await s(`getMaterializedViews(${f.name})`,()=>this.getMaterializedViews(n,f.name));c[f.name]=[...S,...w]}let u=new Map;for(let f of i){let S=c[f.name].filter((w)=>w.type==="materialized-view");if(S.length>0)u.set(f.name,S.map((w)=>w.name))}let[l,d,p,h]=await Promise.all([s("columns",()=>n.unsafe(`SELECT
204
+ ORDER BY table_name`,[t])].map((r)=>({schema:t,name:r.name,type:r.table_type==="VIEW"?"view":"table"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=this.resolveSession(s);if(i?.txActive)throw Error("Cannot iterate on a session with an active transaction");let o=i?i.conn:await this.pool.acquireConnection(),a=!i;if(i)i.txActive=!0,i.iterating=!0;try{if(i)await this.reassertReadOnly(s,o);await o.unsafe("START TRANSACTION WITH CONSISTENT SNAPSHOT");let c=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(i&&c>0)await this.reassertReadOnly(s,o);let u=`${e} LIMIT ? OFFSET ?`,m=[...await o.unsafe(u,[...t??[],n,c])];if(m.length===0)break;if(yield m,m.length<n)break;c+=n}await o.unsafe("COMMIT")}catch(c){try{await o.unsafe("ROLLBACK")}catch{}throw c}finally{if(i)i.txActive=!1,i.iterating=!1;if(a)await this.pool.releaseConnection(o)}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let m=0;m<t.length;m++)i.push(n[u][t[m]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("START TRANSACTION"),t.txActive=!0}else{if(this.sessions.has(I)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("START TRANSACTION")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(I,{conn:t,txActive:!0,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??I,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1}catch(r){if(B(r))throw n.txActive=!1,new b("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch{}throw r}finally{if(t===I)this.sessions.delete(I),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??I,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1}catch(r){if(B(r))n.txActive=!1;throw r}finally{if(t===I)this.sessions.delete(I),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??I;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){return!1}isIterating(e){let t=e??I;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"mysql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`\`${e.replace(/`/g,"``")}\``}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} () VALUES ()`}placeholder(e){return"?"}async setStatementTimeout(e,t){let n=`SET SESSION MAX_EXECUTION_TIME = ${t}`;try{return await e.unsafe(n),n}catch{let r=`SET SESSION max_statement_time = ${t/1000}`;return await e.unsafe(r),r}}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===I,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:!1,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}}var I="__default__";var tr=T(()=>{M();P();Tt();$e();qe()});async function js(e){await e.unsafe("RESET ALL"),await e.unsafe("RESET ROLE"),await e.unsafe("RESET SESSION AUTHORIZATION"),await e.unsafe("UNLISTEN *"),await e.unsafe("SELECT pg_advisory_unlock_all()"),await e.unsafe("DISCARD SEQUENCES"),await e.unsafe("DISCARD TEMP")}function zs(e){switch(e.toLowerCase()){case"integer":case"bigint":case"smallint":return"integer";case"serial":case"bigserial":case"smallserial":return"serial";case"real":case"double precision":return"float";case"numeric":case"decimal":case"money":return"numeric";case"boolean":return"boolean";case"text":return"text";case"character varying":return"varchar";case"character":return"char";case"date":return"date";case"time without time zone":case"time with time zone":return"time";case"timestamp without time zone":case"timestamp with time zone":return"timestamp";case"json":case"jsonb":return"json";case"uuid":return"uuid";case"bytea":case"bit":case"bit varying":return"binary";default:return"unknown"}}class vt{pool=null;connected=!1;sessions=new Map;readOnlySessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect(e){if(e.type!=="postgresql")throw Error("PostgresDriver requires a postgresql connection config");let t=new URLSearchParams;if(e.ssl)t.set("sslmode",e.ssl);t.set("application_name","dotaz");let n=`postgres://${encodeURIComponent(e.user)}:${encodeURIComponent(e.password)}@${e.host}:${e.port}/${encodeURIComponent(e.database)}?${t}`,r=e.initSql?.trim(),s=r?async(i)=>{await i.unsafe(r)}:void 0;this.pool=new pe(n,js,s);try{await this.pool.connect()}catch(i){let o=this.pool;throw this.pool=null,await o.disconnectAll().catch(()=>{}),i instanceof b?i:fe(i)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,e]of this.sessions)await x(e.conn,{rollback:!0});if(this.sessions.clear(),this.readOnlySessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession(e,t){if(this.ensureConnected(),this.sessions.has(e))throw Error(`Session "${e}" already exists`);let n=await this.pool.createConnection();if(t?.readOnly){let r=["SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY"],s=Math.floor(t.statementTimeoutMs??0);if(Number.isFinite(s)&&s>0)r.push(`SET SESSION statement_timeout = ${s}`);let i=r.join("; ");try{await n.unsafe(i)}catch(o){throw await x(n),await this.pool.destroyConnection(n),o instanceof b?o:fe(o)}this.readOnlySessions.set(e,i)}this.sessions.set(e,{conn:n,txActive:!1,txAborted:!1,iterating:!1,activeQueries:new Set})}async releaseSession(e){this.readOnlySessions.delete(e);let t=this.sessions.get(e);if(!t)return;if(this.sessions.delete(e),await x(t.conn,{rollback:!0}),this.pool)await this.pool.destroyConnection(t.conn)}getSessionIds(){return[...this.sessions.keys()].filter((e)=>e!==O)}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async reassertReadOnly(e,t,n){let r=this.readOnlySessions.get(e);if(!r)return;try{await n.unsafe(r)}catch(s){let i=s instanceof b?s:fe(s);if(t.txAborted&&i.code==="TRANSACTION_ABORTED")return;throw i}}async execute(e,t,n,r){this.ensureConnected();let s=this.resolveSession(n),i=s?s.conn:await this.pool.acquireConnection(),o=!s;if(s&&n!==void 0)await this.reassertReadOnly(n,s,i);let a=performance.now(),c=i.unsafe(e,t??[]),u=s?void 0:r??Symbol();if(s)s.activeQueries.add(c);else this.poolActiveQueries.set(u,c);try{let l=await c,m=Math.round(performance.now()-a),f=[...l];if(s)ne(s,e);return{columns:f.length>0?Object.keys(f[0]).map((d)=>({name:d,dataType:"unknown"})):[],rows:f,rowCount:f.length,affectedRows:te(l),durationMs:m}}catch(l){if(s?.txActive&&!B(l))s.txAborted=!0;throw l instanceof b?l:fe(l)}finally{if(s)s.activeQueries.delete(c);else if(this.poolActiveQueries.delete(u),o)await this.pool.releaseConnection(i)}}async cancel(e,t){if(e){let n=this.sessions.get(e);if(n){for(let r of n.activeQueries)r.cancel();n.activeQueries.clear()}}else if(t){let n=this.poolActiveQueries.get(t);if(n)n.cancel(),this.poolActiveQueries.delete(t)}else{for(let n of this.poolActiveQueries.values())n.cancel();this.poolActiveQueries.clear()}}async loadSchema(e){this.ensureConnected();let t=this.resolveSession(e),n=t?t.conn:this.pool.getSystemConnection(),r=!!process.env.DEBUG_SQL,s=async(p,S)=>{if(!r)return S();let E=performance.now();console.debug(`[SQL] loadSchema: ${p} \u2014 started`);try{let C=await S();return console.debug(`[SQL] loadSchema: ${p} \u2014 completed (${Math.round(performance.now()-E)}ms)`),C}catch(C){throw console.debug(`[SQL ERROR] loadSchema: ${p} \u2014 failed (${Math.round(performance.now()-E)}ms)`,C),C}},i=await s("getSchemas",()=>this.getSchemas(n)),a=`{${i.map((p)=>p.name).join(",")}}`,c={};for(let p of i){let S=await s(`getTables(${p.name})`,()=>this.getTables(n,p.name)),E=await s(`getMaterializedViews(${p.name})`,()=>this.getMaterializedViews(n,p.name));c[p.name]=[...S,...E]}let u=new Map;for(let p of i){let S=c[p.name].filter((E)=>E.type==="materialized-view");if(S.length>0)u.set(p.name,S.map((E)=>E.name))}let[l,m,f,g]=await Promise.all([s("columns",()=>n.unsafe(`SELECT
202
205
  c.table_schema,
203
206
  c.table_name,
204
207
  c.column_name,
@@ -298,7 +301,7 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
298
301
  AND nsp_ref.nspname = ANY($1)
299
302
  GROUP BY nsp_ref.nspname, cl_ref.relname, con.conname,
300
303
  nsp_src.nspname, cl_src.relname
301
- ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[a]))]);for(let[f,S]of u){let w=await s(`matviewColumns(${f})`,()=>n.unsafe(`SELECT
304
+ ORDER BY nsp_ref.nspname, cl_ref.relname, con.conname`,[a]))]);for(let[p,S]of u){let E=await s(`matviewColumns(${p})`,()=>n.unsafe(`SELECT
302
305
  n.nspname AS schema_name,
303
306
  c.relname AS table_name,
304
307
  a.attname AS column_name,
@@ -316,7 +319,7 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
316
319
  AND c.relname = ANY($2)
317
320
  AND a.attnum > 0
318
321
  AND NOT a.attisdropped
319
- ORDER BY n.nspname, c.relname, a.attnum`,[f,`{${S.join(",")}}`]));for(let b of w)l.push({table_schema:b.schema_name,table_name:b.table_name,column_name:b.column_name,data_type:b.data_type,udt_name:b.udt_name,is_nullable:b.is_nullable,column_default:b.column_default,character_maximum_length:null,is_primary_key:!1})}let m={};for(let f of l){let S=`${f.table_schema}.${f.table_name}`;if(!m[S])m[S]=[];m[S].push({name:f.column_name,dataType:this.mapDataType(f.data_type,f.udt_name),nullable:f.is_nullable==="YES",defaultValue:f.column_default,isPrimaryKey:f.is_primary_key,isAutoIncrement:f.is_primary_key&&typeof f.column_default==="string"&&f.column_default.startsWith("nextval("),maxLength:f.character_maximum_length??void 0})}let g={};for(let f of d){let S=`${f.table_schema}.${f.table_name}`;if(!g[S])g[S]=[];g[S].push({name:f.index_name,columns:typeof f.columns==="string"?f.columns.replace(/^\{|\}$/g,"").split(","):f.columns,isUnique:f.is_unique,isPrimary:f.is_primary})}let y={};for(let f of p){let S=`${f.table_schema}.${f.table_name}`;if(!y[S])y[S]=[];y[S].push({name:f.constraint_name,columns:typeof f.columns==="string"?f.columns.replace(/^\{|\}$/g,"").split(","):f.columns,referencedSchema:f.referenced_schema,referencedTable:f.referenced_table,referencedColumns:typeof f.referenced_columns==="string"?f.referenced_columns.replace(/^\{|\}$/g,"").split(","):f.referenced_columns,onUpdate:f.on_update,onDelete:f.on_delete})}let E={};for(let f of h){let S=`${f.referenced_schema}.${f.referenced_table}`;if(!E[S])E[S]=[];E[S].push({constraintName:f.constraint_name,referencingSchema:f.referencing_schema,referencingTable:f.referencing_table,referencingColumns:typeof f.referencing_columns==="string"?f.referencing_columns.replace(/^\{|\}$/g,"").split(","):f.referencing_columns,referencedColumns:typeof f.referenced_columns==="string"?f.referenced_columns.replace(/^\{|\}$/g,"").split(","):f.referenced_columns})}for(let f of i)for(let S of c[f.name]){let w=`${f.name}.${S.name}`;if(!m[w])m[w]=[];if(!g[w])g[w]=[];if(!y[w])y[w]=[];if(!E[w])E[w]=[]}return{schemas:i,tables:c,columns:m,indexes:g,foreignKeys:y,referencingForeignKeys:E}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe(`SELECT schema_name AS name
322
+ ORDER BY n.nspname, c.relname, a.attnum`,[p,`{${S.join(",")}}`]));for(let C of E)l.push({table_schema:C.schema_name,table_name:C.table_name,column_name:C.column_name,data_type:C.data_type,udt_name:C.udt_name,is_nullable:C.is_nullable,column_default:C.column_default,character_maximum_length:null,is_primary_key:!1})}let d={};for(let p of l){let S=`${p.table_schema}.${p.table_name}`;if(!d[S])d[S]=[];d[S].push({name:p.column_name,dataType:this.mapDataType(p.data_type,p.udt_name),nullable:p.is_nullable==="YES",defaultValue:p.column_default,isPrimaryKey:p.is_primary_key,isAutoIncrement:p.is_primary_key&&typeof p.column_default==="string"&&p.column_default.startsWith("nextval("),maxLength:p.character_maximum_length??void 0})}let h={};for(let p of m){let S=`${p.table_schema}.${p.table_name}`;if(!h[S])h[S]=[];h[S].push({name:p.index_name,columns:typeof p.columns==="string"?p.columns.replace(/^\{|\}$/g,"").split(","):p.columns,isUnique:p.is_unique,isPrimary:p.is_primary})}let y={};for(let p of f){let S=`${p.table_schema}.${p.table_name}`;if(!y[S])y[S]=[];y[S].push({name:p.constraint_name,columns:typeof p.columns==="string"?p.columns.replace(/^\{|\}$/g,"").split(","):p.columns,referencedSchema:p.referenced_schema,referencedTable:p.referenced_table,referencedColumns:typeof p.referenced_columns==="string"?p.referenced_columns.replace(/^\{|\}$/g,"").split(","):p.referenced_columns,onUpdate:p.on_update,onDelete:p.on_delete})}let w={};for(let p of g){let S=`${p.referenced_schema}.${p.referenced_table}`;if(!w[S])w[S]=[];w[S].push({constraintName:p.constraint_name,referencingSchema:p.referencing_schema,referencingTable:p.referencing_table,referencingColumns:typeof p.referencing_columns==="string"?p.referencing_columns.replace(/^\{|\}$/g,"").split(","):p.referencing_columns,referencedColumns:typeof p.referenced_columns==="string"?p.referenced_columns.replace(/^\{|\}$/g,"").split(","):p.referenced_columns})}for(let p of i)for(let S of c[p.name]){let E=`${p.name}.${S.name}`;if(!d[E])d[E]=[];if(!h[E])h[E]=[];if(!y[E])y[E]=[];if(!w[E])w[E]=[]}return{schemas:i,tables:c,columns:d,indexes:h,foreignKeys:y,referencingForeignKeys:w}}async getSchemas(e){return this.ensureConnected(),[...await e.unsafe(`SELECT schema_name AS name
320
323
  FROM information_schema.schemata
321
324
  WHERE schema_name NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
322
325
  AND schema_name NOT LIKE 'pg_temp_%'
@@ -327,13 +330,13 @@ Request: ${t.prompt}`}]})});if(!s.ok){let o=await s.text().catch(()=>"");if(s.st
327
330
  ORDER BY table_name`,[t])].map((r)=>({schema:t,name:r.name,type:r.table_type==="VIEW"?"view":"table"}))}async getMaterializedViews(e,t){return this.ensureConnected(),[...await e.unsafe(`SELECT matviewname
328
331
  FROM pg_matviews
329
332
  WHERE schemaname = $1
330
- ORDER BY matviewname`,[t])].map((r)=>({schema:t,name:r.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("BEGIN"),t.txActive=!0,t.txAborted=!1}else{if(this.sessions.has(I)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("BEGIN")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(I,{conn:t,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??I,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1,n.txAborted=!1}catch(r){if(F(r))throw n.txActive=!1,n.txAborted=!1,new T("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch{}throw r}finally{if(t===I)this.sessions.delete(I),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??I,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch(r){if(F(r))n.txActive=!1,n.txAborted=!1;throw r}finally{if(t===I)this.sessions.delete(I),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??I;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){let t=e??I;return this.sessions.get(t)?.txAborted??!1}isIterating(e){let t=e??I;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"postgresql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=`dotaz_iter_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=s?this.sessions.get(s):void 0;if(s&&!o)throw Error(`Session "${s}" not found`);if(o?.txActive)throw Error("Cannot iterate on a session with an active transaction");let a=o?o.conn:await this.pool.acquireConnection(),c=!o;if(o)o.txActive=!0,o.iterating=!0;let u=!1;try{await a.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await a.unsafe(`DECLARE ${i} NO SCROLL CURSOR FOR ${e}`,t??[]);try{while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let d=[...await a.unsafe(`FETCH FORWARD ${n} FROM ${i}`)];if(d.length===0)break;if(yield d,d.length<n)break}}finally{try{await a.unsafe(`CLOSE ${i}`)}catch{}}await a.unsafe("COMMIT")}catch(l){u=!0;try{await a.unsafe("ROLLBACK")}catch{}throw l}finally{if(o)o.txActive=!1,o.iterating=!1;if(c)await this.pool.releaseConnection(a);else if(o&&!u)try{await a.unsafe("ROLLBACK")}catch{}}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let d=0;d<t.length;d++)i.push(n[u][t[d]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===I,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:i.txAborted,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}mapDataType(e,t){if(e==="ARRAY")return"array";if(e==="USER-DEFINED"){let n=t.toLowerCase();if(n==="json"||n==="jsonb")return"json";return"enum"}return es(e)}}var I="__default__";var In=C(()=>{k();P();ot();De();lt()});var{SQL:mt}=globalThis.Bun;function ts(e){let t=e.toUpperCase();if(t==="INTEGER"||t==="INT"||t==="BIGINT"||t==="SMALLINT"||t==="TINYINT"||t==="MEDIUMINT")return"integer";if(t==="REAL"||t==="FLOAT"||t==="DOUBLE")return"float";if(t==="NUMERIC"||t==="DECIMAL")return"numeric";if(t==="BOOLEAN"||t==="BOOL")return"boolean";if(t==="TEXT")return"text";if(t.includes("VARCHAR")||t.includes("VARYING"))return"varchar";if(t.includes("CHAR")&&!t.includes("VARCHAR"))return"char";if(t==="DATE")return"date";if(t==="TIME")return"time";if(t==="DATETIME"||t.includes("TIMESTAMP"))return"timestamp";if(t==="JSON"||t==="JSONB")return"json";if(t==="BLOB"||t==="BINARY"||t.includes("VARBINARY"))return"binary";return"unknown"}class pt{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;iterating=!1;iterateDb=null;iterateActive=!1;initSql=null;mainHandleId=null;mainCreatedAt=0;mainLastUsedAt=0;iterateHandleId=null;iterateCreatedAt=0;iterateLastUsedAt=0;nextHandleNumber=1;async connect(e){if(e.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");let t=e.initSql?.trim()||null;try{this.db=new mt(`sqlite:${e.path}`),this.dbPath=e.path,this.resetMainHandle(),await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON"),this.initSql=t,await this.applyInitSql(this.db)}catch(n){if(this.db)try{await this.db.close()}catch{}throw this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,n instanceof T?n:ue(n)}this.connected=!0}async disconnect(){if(this.connected=!1,this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession(e){this.sessionIds.add(e)}async releaseSession(e){if(this.txActive&&this.txOwnerSession===e){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete(e)}getSessionIds(){return[...this.sessionIds]}async execute(e,t,n){this.ensureConnected(),this.ensureSessionCanExecute(n),this.markMainUsed();let r=performance.now();try{let s=await this.db.unsafe(e,t??[]),i=Math.round(performance.now()-r),o=[...s],a=e.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(a))this.txActive=!0,this.txOwnerSession=n??null;else if(/^(COMMIT|END)\b/.test(a))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(a)&&!/^ROLLBACK\s+TO\b/.test(a))this.txActive=!1,this.txOwnerSession=null;return{columns:o.length>0?Object.keys(o[0]).map((u)=>({name:u,dataType:"unknown"})):[],rows:o,rowCount:o.length,affectedRows:J(s),durationMs:i}}catch(s){throw s instanceof T?s:ue(s)}}async cancel(e,t){}async loadSchema(e){this.ensureConnected(),this.markMainUsed();let t=await this.getSchemas(),n=t[0].name,r=await this.getTables(n),s={[n]:r},i={},o={},a={},c={},u=new Map;for(let l of r){let d=`${n}.${l.name}`;i[d]=await this.getColumns(n,l.name),o[d]=await this.getIndexes(n,l.name);let p=await this.getForeignKeys(n,l.name);a[d]=p;for(let h of p){let m=`${h.referencedSchema}.${h.referencedTable}`;if(!u.has(m))u.set(m,[]);u.get(m).push({constraintName:h.name,referencingSchema:n,referencingTable:l.name,referencingColumns:h.columns,referencedColumns:h.referencedColumns})}}for(let l of r){let d=`${n}.${l.name}`;c[d]=u.get(d)??[]}return{schemas:t,tables:s,columns:i,indexes:o,foreignKeys:a,referencingForeignKeys:c}}async getSchemas(){return[{name:"main"}]}async getTables(e){return this.ensureConnected(),[...await this.db.unsafe("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name")].map((n)=>({schema:e,name:n.name,type:n.type}))}async getColumns(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(t)})`)],r=n.filter((s)=>s.pk>0).length;return n.map((s)=>({name:s.name,dataType:ts(s.type||"BLOB"),nullable:s.notnull===0&&s.pk===0,defaultValue:s.dflt_value,isPrimaryKey:s.pk>0,isAutoIncrement:s.pk>0&&r===1&&s.type?.toUpperCase()==="INTEGER"}))}async getIndexes(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(t)})`)],r=[];for(let s of n){let i=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(s.name)})`)];r.push({name:s.name,columns:i.map((o)=>o.name),isUnique:s.unique===1,isPrimary:s.origin==="pk"})}return r}async getForeignKeys(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(t)})`)],r=new Map;for(let s of n){let i=r.get(s.id);if(i)i.columns.push(s.from),i.referencedColumns.push(s.to);else r.set(s.id,{name:`fk_${t}_${s.id}`,columns:[s.from],referencedSchema:"main",referencedTable:s.table,referencedColumns:[s.to],onUpdate:s.on_update,onDelete:s.on_delete})}return Array.from(r.values())}async ping(){this.ensureConnected(),this.markMainUsed(),await this.db.unsafe("SELECT 1")}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=this.dbPath===":memory:",o=i?this.db:await this.getIterateDb();if(i){if(this.markMainUsed(),this.ensureSessionCanExecute(s),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=s??null,this.iterating=!0}else this.iterateActive=!0,this.markIterateUsed();await o.unsafe("BEGIN");let a=!1;try{let c=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let u=`${e} LIMIT ? OFFSET ?`,d=[...await o.unsafe(u,[...t??[],n,c])];if(d.length===0)break;if(yield d,d.length<n)break;c+=n}await o.unsafe("COMMIT"),a=!0}catch(c){try{await o.unsafe("ROLLBACK")}catch{}throw c}finally{if(!a)try{await o.unsafe("ROLLBACK")}catch{}if(i)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null;else this.iterateActive=!1,this.markIterateUsed()}}async getIterateDb(){if(!this.iterateDb){let e=new mt(`sqlite:${this.dbPath}`);try{await this.applyInitSql(e)}catch(t){try{await e.close()}catch{}throw t instanceof T?t:ue(t)}this.iterateDb=e,this.resetIterateHandle()}return this.iterateDb}async applyInitSql(e){if(!this.initSql)return;for(let t of Y(this.initSql))await e.unsafe(t)}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let d=0;d<t.length;d++)i.push(n[u][t[d]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){if(this.ensureConnected(),this.markMainUsed(),this.txActive)throw Error(e&&this.txOwnerSession!==e?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=e??null}async commit(e){if(this.ensureConnected(),this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot commit during active iteration");this.markMainUsed(),await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback(e){if(this.ensureConnected(),this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot rollback during active iteration");this.markMainUsed();try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction(e){if(e!==void 0)return this.txActive&&this.txOwnerSession===e;return this.txActive&&this.txOwnerSession===null}isTxAborted(e){return!1}isIterating(e){return this.iterating}getDriverType(){return"sqlite"}listConnectionHandles(){if(!this.connected||!this.db||!this.mainHandleId)return[];let e=this.txActive?"transaction":this.iterating?"active":"idle",t=[{handleId:this.mainHandleId,role:"sqlite-main",state:e,createdAt:this.mainCreatedAt,lastUsedAt:this.mainLastUsedAt,activeQueryCount:0,inTransaction:this.txActive,txAborted:!1,iterating:this.iterating,canTerminate:!0}];if(this.iterateDb&&this.iterateHandleId)t.push({handleId:this.iterateHandleId,role:"sqlite-iterate",state:this.iterateActive?"active":"idle",createdAt:this.iterateCreatedAt,lastUsedAt:this.iterateLastUsedAt,activeQueryCount:this.iterateActive?1:0,inTransaction:this.iterateActive,txAborted:!1,iterating:this.iterateActive,canTerminate:!0});return t}async terminateConnectionHandle(e){if(this.ensureConnected(),this.mainHandleId===e){await this.reopenMainConnection();return}if(this.iterateHandleId===e&&this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1;return}throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){if(e==="main")return this.quoteIdentifier(t);return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}ensureSessionCanExecute(e){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if(e!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if(e===void 0||e!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx(e){if(!this.txActive)throw Error("No active transaction");if(!(e===void 0?this.txOwnerSession===null:this.txOwnerSession===e))throw Error(`Cannot modify transaction owned by ${this.txOwnerSession===null?"sessionless caller":`session "${this.txOwnerSession}"`}`)}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}async reopenMainConnection(){let e=this.dbPath;if(!e)throw Error("SQLite path is not available");if(this.db)try{await this.db.close()}catch{}let t=new mt(`sqlite:${e}`);try{await t.unsafe("PRAGMA journal_mode = WAL"),await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t)}catch(n){try{await t.close()}catch{}throw n instanceof T?n:ue(n)}this.db=t,this.txActive=!1,this.txOwnerSession=null,this.iterating=!1,this.resetMainHandle()}resetMainHandle(){let e=Date.now();this.mainHandleId=this.createHandleId(),this.mainCreatedAt=e,this.mainLastUsedAt=e}resetIterateHandle(){let e=Date.now();this.iterateHandleId=this.createHandleId(),this.iterateCreatedAt=e,this.iterateLastUsedAt=e}createHandleId(){let e=`sqlite-${this.nextHandleNumber}`;return this.nextHandleNumber+=1,e}markMainUsed(){this.mainLastUsedAt=Date.now()}markIterateUsed(){this.iterateLastUsedAt=Date.now()}}var On=C(()=>{k();P();De()});import{chmodSync as ns,unlinkSync as rs,writeFileSync as ss}from"fs";import{tmpdir as is}from"os";import{join as os}from"path";async function ls(){return new Promise((e,t)=>{let n=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),r=n.port;if(n.stop(!0),r>0)e(r);else t(Error("Could not find a free port"))})}async function us(e,t,n){let r=Date.now()+t;while(Date.now()<r){if(n&&n.exitCode!==null)return;try{(await Bun.connect({hostname:"127.0.0.1",port:e,socket:{data(){},open(i){i.end()},close(){},error(){}}})).end();return}catch{await Bun.sleep(cs)}}throw Error(`SSH tunnel port ${e} did not become available within ${t/1000}s`)}async function Ie(e,t,n){let r=e.localPort||await ls(),s=null,i=null;try{let o=["ssh","-N","-L",`${r}:${t}:${n}`,"-p",String(e.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],a={...process.env};if(e.authMethod==="key"&&e.keyPath)o.push("-i",e.keyPath),o.push("-o","BatchMode=yes");else if(e.password)s=os(is(),`dotaz-askpass-${process.pid}-${Date.now()}`),ss(s,`#!/bin/sh
331
- echo '${e.password.replace(/'/g,"'\\''")}'`),ns(s,448),a.SSH_ASKPASS=s,a.SSH_ASKPASS_REQUIRE="force",a.DISPLAY=a.DISPLAY||":0";if(o.push(`${e.username}@${e.host}`),i=Bun.spawn(o,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:a}),i.stdin&&typeof i.stdin!=="number")i.stdin.end();let c=i.stderr&&typeof i.stderr!=="number"?i.stderr:null,u=us(r,as,i),l=i.exited.then(async(p)=>{if(p!==0){let h=await ds(c),m=ms(h)||`SSH process exited with code ${p}`;throw Error(m)}});return await Promise.race([u,l]),{localPort:r,close:async()=>{if(i)i.kill(),i=null;xn(s)}}}catch(o){if(i)i.kill();if(xn(s),o instanceof Error)throw ps(o);throw Error(`SSH tunnel error: ${String(o)}`)}}function xn(e){if(e)try{rs(e)}catch{}}async function ds(e){if(!e)return"";try{let t=e.getReader(),n=[];while(!0){let{done:r,value:s}=await t.read();if(r)break;n.push(s)}return Buffer.concat(n).toString("utf-8")}catch{return""}}function ms(e){if(!e.trim())return null;let t=e.trim().split(`
332
- `);for(let n of t){let r=n.toLowerCase();if(r.includes("permission denied")||r.includes("authentication"))return`SSH authentication failed: ${n.trim()}`;if(r.includes("connection refused"))return`SSH host unreachable: ${n.trim()}`;if(r.includes("timed out")||r.includes("timeout"))return`SSH connection timed out: ${n.trim()}`;if(r.includes("no such file")||r.includes("no such identity"))return`SSH key file not found: ${n.trim()}`;if(r.includes("could not resolve"))return`SSH host unreachable: ${n.trim()}`}return t[t.length-1]?.trim()||null}function ps(e){let t=e.message.toLowerCase();if(t.includes("authentication")||t.includes("permission denied"))return Error(`SSH authentication failed: ${e.message}`);if(t.includes("econnrefused")||t.includes("connection refused")||t.includes("unreachable"))return Error(`SSH host unreachable: ${e.message}`);if(t.includes("timeout")||t.includes("timed out"))return Error(`SSH connection timed out: ${e.message}`);return Error(`SSH tunnel error: ${e.message}`)}var as=15000,cs=100;var Ln=()=>{};class ft{drivers=new Map;passwords=new Map;states=new Map;listeners=[];sessionDeadListeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;healthCheckRunning=new Set;connectAttempt=new Map;constructor(e,t){this.appDb=e,this.opts={...gs,...t}}async connect(e,t){let n=this.appDb.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);this.cancelAutoReconnect(e);let r=(this.connectAttempt.get(e)??0)+1;if(this.connectAttempt.set(e,r),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),await this.setConnectionState(e,"connecting");try{let s=t?{...n.config,...t}:n.config;if(me(s),L(s))this.passwords.set(e,s.password);s=await this.setupSshTunnel(e,s);let i=j(s),o=de(s);if(await o.connect(s),this.connectAttempt.get(e)!==r){await o.disconnect().catch(()=>{});return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),M[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let c=s,u=(c.activeDatabases??[]).filter((l)=>l!==c.database).map((l)=>this.connectDatabase(e,c,l));await Promise.allSettled(u)}await this.setConnectionState(e,"connected"),this.startHealthCheck(e)}catch(s){if(this.connectAttempt.get(e)!==r)return;await this.closeTunnel(e);let i=s instanceof Error?s.message:"Unknown connection error",o=s instanceof T?s.code:void 0;throw await this.setConnectionState(e,"error",i,o),s}}async disconnect(e){this.connectAttempt.set(e,(this.connectAttempt.get(e)??0)+1),this.cancelAutoReconnect(e),this.stopHealthCheck(e),await this.gracefulDisconnect(e),await this.closeTunnel(e),this.passwords.delete(e),await this.setConnectionState(e,"disconnected")}async reconnect(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.gracefulDisconnect(e);await this.connect(e)}getDriver(e,t){let n=this.drivers.get(e);if(!n)throw Error(`No active connection for id: ${e}`);let r=t??this.getDefaultDatabaseName(e),s=n.get(r);if(!s)throw Error(`No active driver for database "${r}" on connection ${e}`);return s}getConnectionState(e){return this.states.get(e)?.state??"disconnected"}listConnectionHandles(){let e=[];for(let[t,n]of this.drivers){let s=this.appDb.getConnectionById(t)?.name??t;for(let[i,o]of n)for(let a of o.listConnectionHandles())e.push({...a,connectionId:t,connectionName:s,database:i,driverType:o.getDriverType()})}return e}async terminateConnectionHandle(e,t,n){await this.getDriver(e,t).terminateConnectionHandle(n)}async listDatabases(e){let t=this.appDb.getConnectionById(e);if(!t||!M[t.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let n=j(t.config),r=this.getDriver(e,n),s=t.config.type==="postgresql"?Pn:kn,i=await r.execute(s),o=this.drivers.get(e),a=o?[...o.keys()]:[n];return i.rows.map((c)=>({name:c.name,isDefault:c.name===n,isActive:a.includes(c.name)}))}async activateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!M[n.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let r=n.config,s=this.drivers.get(e);if(!s)throw Error(`No active connection for id: ${e}`);if(s.has(t))return;let i=this.passwords.get(e)??r.password,o={...r,database:t,password:i};await this.connectDatabase(e,o,t);let a=[...new Set([...r.activeDatabases??[],t])];this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:a}})}async deactivateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!M[n.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let r=n.config;if(t===j(r))throw Error("Cannot deactivate the default database");let s=this.drivers.get(e);if(s){let o=s.get(t);if(o)try{await o.disconnect()}finally{s.delete(t)}}let i=(r.activeDatabases??[]).filter((o)=>o!==t);this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:i.length>0?i:void 0}})}listConnections(){return this.appDb.listConnections().map((t)=>({...t,state:this.getConnectionState(t.id),error:this.states.get(t.id)?.error}))}createConnection(e,t=!1){return me(e.config,t),this.appDb.createConnection(e)}updateConnection(e){return me(e.config),{...this.appDb.updateConnection(e),state:this.getConnectionState(e.id),error:this.states.get(e.id)?.error}}setConnectionReadOnly(e,t){return{...this.appDb.setConnectionReadOnly(e,t),state:this.getConnectionState(e),error:this.states.get(e)?.error}}async deleteConnection(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),this.passwords.delete(e),this.states.delete(e),this.appDb.deleteConnection(e)}async testConnection(e){me(e);let t=null,n=e;try{if(e.type==="postgresql"&&e.sshTunnel?.enabled)t=await Ie(e.sshTunnel,e.host,e.port),n={...e,host:"127.0.0.1",port:t.localPort};let r=de(n);return await r.connect(n),await r.disconnect(),{success:!0}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown connection error"}}finally{if(t)await t.close()}}async listDatabasesForConfig(e){if(e.type!=="postgresql"&&e.type!=="mysql")throw Error(`Listing databases is not supported for connection type: ${e.type}`);let t=e.type==="postgresql"?"postgres":"information_schema",n=e.database?e:{...e,database:t};me(n);let r=null;try{if(n.type==="postgresql"&&n.sshTunnel?.enabled)r=await Ie(n.sshTunnel,n.host,n.port),n={...n,host:"127.0.0.1",port:r.localPort};let s=de(n);try{await s.connect(n);let i=n.type==="postgresql"?Pn:kn;return(await s.execute(i)).rows.map((a)=>a.name)}finally{await s.disconnect().catch(()=>{})}}finally{if(r)await r.close().catch(()=>{})}}onStatusChanged(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);if(t>=0)this.listeners.splice(t,1)}}onSessionDead(e){return this.sessionDeadListeners.push(e),()=>{let t=this.sessionDeadListeners.indexOf(e);if(t>=0)this.sessionDeadListeners.splice(t,1)}}async disconnectAll(){for(let t of[...this.reconnectStates.keys()])this.cancelAutoReconnect(t);for(let t of[...this.healthTimers.keys()])this.stopHealthCheck(t);let e=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let t of e)await this.disconnect(t)}startHealthCheck(e){this.stopHealthCheck(e);let t=setInterval(()=>{this.performHealthCheck(e)},this.opts.healthCheckIntervalMs);this.healthTimers.set(e,t)}stopHealthCheck(e){let t=this.healthTimers.get(e);if(t)clearInterval(t),this.healthTimers.delete(e)}async performHealthCheck(e){if(this.healthCheckRunning.has(e))return;this.healthCheckRunning.add(e);try{let t=this.drivers.get(e);if(!t)return;for(let n of t.values()){try{await Promise.race([n.ping(),new Promise((r,s)=>setTimeout(()=>s(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let r=!1;for(let s of t.values()){if(s.inTransaction()){r=!0;break}for(let i of s.getSessionIds())if(s.inTransaction(i)){r=!0;break}if(r)break}this.stopHealthCheck(e);try{await this.disconnectAllDrivers(e)}catch{}await this.setConnectionState(e,"disconnected","Connection lost"),this.startAutoReconnect(e,r);return}for(let r of n.getSessionIds())try{await n.execute("SELECT 1",void 0,r)}catch{try{await n.releaseSession(r)}catch{}for(let s of this.sessionDeadListeners)try{await s({connectionId:e,sessionId:r})}catch{}}}}finally{this.healthCheckRunning.delete(e)}}startAutoReconnect(e,t=!1){this.cancelAutoReconnect(e);let n={attempt:0,timer:null,cancelled:!1,hadTransaction:t};this.reconnectStates.set(e,n),this.scheduleReconnectAttempt(e,n)}cancelAutoReconnect(e){let t=this.reconnectStates.get(e);if(t){if(t.cancelled=!0,t.timer)clearTimeout(t.timer);this.reconnectStates.delete(e)}}async scheduleReconnectAttempt(e,t){if(t.cancelled)return;if(t.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete(e),await this.setConnectionState(e,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let n=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,t.attempt),this.opts.reconnectMaxDelayMs);t.timer=setTimeout(()=>{if(t.cancelled)return;this.attemptReconnect(e,t).catch(()=>{})},n)}async attemptReconnect(e,t){if(t.cancelled)return;let n=this.appDb.getConnectionById(e);if(!n){this.cancelAutoReconnect(e);return}t.attempt++,await this.setConnectionState(e,"reconnecting");try{await this.closeTunnel(e);let r=this.passwords.get(e),s=r?{...n.config,password:r}:n.config;s=await this.setupSshTunnel(e,s);let i=j(s),o=de(s);if(await o.connect(s),t.cancelled){await o.disconnect(),await this.closeTunnel(e);return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),M[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let u=s,l=(u.activeDatabases??[]).filter((d)=>d!==u.database).map((d)=>this.connectDatabase(e,u,d));await Promise.allSettled(l)}let c=t.hadTransaction;this.reconnectStates.delete(e),await this.setConnectionState(e,"connected",void 0,void 0,c),this.startHealthCheck(e)}catch{if(t.cancelled)return;await this.closeTunnel(e),this.scheduleReconnectAttempt(e,t)}}async gracefulDisconnect(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{for(let s of r.getSessionIds()){try{await r.cancel(s)}catch{}if(r.inTransaction(s))try{await r.rollback(s)}catch{}}if(r.inTransaction())try{await r.rollback()}catch{}try{await r.cancel()}catch{}}finally{try{await r.disconnect()}finally{t.delete(n)}}this.drivers.delete(e)}async disconnectAllDrivers(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{await r.disconnect()}finally{t.delete(n)}this.drivers.delete(e)}async connectDatabase(e,t,n){let r=this.drivers.get(e);if(!r)throw Error(`No active connection for id: ${e}`);let s=this.tunnels.get(e),i=s?{host:"127.0.0.1",port:s.localPort}:{},o={...t,...i,database:n},a=de(o);await a.connect(o),r.set(n,a)}async setupSshTunnel(e,t){if(t.type!=="postgresql"||!t.sshTunnel?.enabled)return t;let n=await Ie(t.sshTunnel,t.host,t.port);return this.tunnels.set(e,n),{...t,host:"127.0.0.1",port:n.localPort}}async closeTunnel(e){let t=this.tunnels.get(e);if(t)await t.close(),this.tunnels.delete(e)}getActiveDatabases(e){let t=this.drivers.get(e);if(!t)return[];return[...t.keys()]}getDefaultDatabaseName(e){let t=this.appDb.getConnectionById(e);if(!t)throw Error(`Connection not found: ${e}`);return j(t.config)}async setConnectionState(e,t,n,r,s){this.states.set(e,{state:t,error:n});let i=this.listeners.map((o)=>o({connectionId:e,state:t,error:n,errorCode:r,transactionLost:s||void 0}));await Promise.allSettled(i)}}function de(e){let t;switch(e.type){case"postgresql":t=new dt;break;case"sqlite":t=new pt;break;case"mysql":t=new ut;break;default:throw Error(`Unsupported connection type: ${e.type}`)}if(process.env.DEBUG_SQL)t=new it(t);return t}function me(e,t=!1){if(!e?.type)throw Error("Connection config must have a type");let n=M[e.type];if(!n)throw Error(`Unsupported connection type: ${e.type}`);if(n.hasHost&&L(e)){let r=n.label;if(!e.host)throw Error(`${r} host is required`);if(!e.port)throw Error(`${r} port is required`);if(!e.database)throw Error(`${r} database is required`);if(!e.user)throw Error(`${r} user is required`);if(!t&&(e.password===void 0||e.password===null))throw Error(`${r} password is required`)}else if(e.type==="sqlite"){if(!e.path)throw Error("SQLite path is required")}}var fs,kn,Pn="SELECT datname AS name FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname",gs;var Mn=C(()=>{se();P();_n();In();On();Ln();fs=["mysql","information_schema","performance_schema","sys"],kn=`SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN (${fs.map((e)=>`'${e}'`).join(", ")}) ORDER BY schema_name`,gs={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5}});function hs(e){let t=[],n=/-c\s+([^\s=]+)=([^\s]+)/g,r;while((r=n.exec(e))!==null){let s=r[1],i=r[2].replace(/'/g,"''");t.push(`SET ${s} = '${i}';`)}return t.join(`
333
- `)}function Un(){let e=process.env.DATABASE_URL;if(!e)return null;let t;try{t=new URL(e)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let n=t.protocol.replace(/:$/,"");if(n==="postgresql"||n==="postgres"){let r=t.hostname||"localhost",s=t.port?Number(t.port):5432,i=t.pathname.replace(/^\//,"")||"postgres",o=decodeURIComponent(t.username||"postgres"),a=decodeURIComponent(t.password||""),c=t.searchParams.get("options"),u=process.env.DOTAZ_INIT_SQL?.trim()||(c?hs(c):"")||void 0;return{name:`${r}/${i}`,config:{type:"postgresql",host:r,port:s,database:i,user:o,password:a,initSql:u}}}if(n==="mysql"){let r=t.hostname||"localhost",s=t.port?Number(t.port):3306,i=t.pathname.replace(/^\//,"")||"mysql",o=decodeURIComponent(t.username||"root"),a=decodeURIComponent(t.password||""),c=process.env.DOTAZ_INIT_SQL?.trim()||void 0;return{name:`${r}/${i}`,config:{type:"mysql",host:r,port:s,database:i,user:o,password:a,initSql:c}}}return console.warn(`DATABASE_URL: unsupported scheme "${n}", ignoring`),null}var G="env-default";function gt(e,t){if(!t.has(e.id))return e;return{...e,config:Zt(e.config),serverManaged:!0}}function xe(e,t){return(...n)=>{let r=e(...n);return r instanceof Promise?r.then((s)=>gt(s,t)):gt(r,t)}}function yt(){return Le}function qn(e,t){let n=crypto.randomUUID(),r=ce.create(":memory:"),s=new ft(r),i=new re(s,void 0,r),o=new Ge(t),a=(g,y)=>{if(m.ws)m.ws.send(JSON.stringify({type:"message",channel:g,payload:y}))},{handlers:c,sessionManager:u}=An(s,i,r,void 0,{encryption:o,emitMessage:a,allowServerFileAccess:!1}),l=new Set,d=Un();if(d){let g=Oe.size>0?{...d.config,activeDatabases:[...Oe]}:d.config;r.createConnectionWithId(G,{name:d.name,config:g}),l.add(G);let y=c["connections.list"];c["connections.list"]=()=>y().map((x)=>gt(x,l));let E=c["connections.create"];c["connections.create"]=xe(E,l);let f=c["connections.setReadOnly"];c["connections.setReadOnly"]=xe(f,l);let S=c["connections.setGroup"];c["connections.setGroup"]=xe(S,l);let w=c["connections.update"];c["connections.update"]=xe((v)=>{if(l.has(v.id))throw Error("Server-managed connections cannot be reconfigured");return w(v)},l);let b=c["databases.activate"];c["databases.activate"]=async(v)=>{let x=await b(v);if(v.connectionId===G)Oe.add(v.database);return x};let R=c["databases.deactivate"];c["databases.deactivate"]=async(v)=>{let x=await R(v);if(v.connectionId===G)Oe.delete(v.database);return x}}let p=s.onSessionDead((g)=>{if(u.handleSessionDead(g.sessionId),m.ws)m.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:g.connectionId,sessions:u.listSessions(g.connectionId)}}))}),h=s.onStatusChanged(async(g)=>{if(m.ws)m.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:g.connectionId,state:g.state,error:g.error,errorCode:g.errorCode,transactionLost:g.transactionLost}}));if(g.state==="disconnected"||g.state==="error"){if(u.handleConnectionLost(g.connectionId),m.ws)m.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:g.connectionId,sessions:[]}}))}if(g.state==="connected")try{let y=await u.handleConnectionRestored(g.connectionId);if(y.length>0&&m.ws)m.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:g.connectionId,sessions:y}}))}catch(y){console.warn("Session restoration failed:",y instanceof Error?y.message:y)}}),m={id:n,appDb:r,connectionManager:s,queryExecutor:i,handlers:c,sessionManager:u,serverManagedIds:l,unsubscribe:()=>{p(),h()},ws:e,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(Le.set(n,m),d)s.connect(G).catch((g)=>{console.warn("DATABASE_URL auto-connect failed:",g?.message??g)});return m}async function pe(e){if(Le.delete(e.id),e.ttlTimer)clearTimeout(e.ttlTimer),e.ttlTimer=null;e.unsubscribe(),e.sessionManager.dispose();for(let t of e.queryExecutor.getRunningQueryIds())await e.queryExecutor.cancelQuery(t);await e.connectionManager.disconnectAll(),e.appDb.close()}async function Fn(e){if(e.ws=null,e.disconnectedAt=Date.now(),e.activeStreams===0)await pe(e);else e.ttlTimer=setTimeout(async()=>{if(Le.has(e.id))await pe(e)},ht)}async function Et(e){if(e.activeStreams--,e.ws===null&&e.activeStreams===0)await pe(e)}function St(e,t,n,r,s){let i=crypto.randomUUID();return X.set(i,{session:e,connectionId:n,database:r,params:s,type:t,createdAt:Date.now()}),i}function bt(e,t){let n=X.get(e);if(!n)return null;if(n.type!==t)return null;if(Date.now()-n.createdAt>$n)return X.delete(e),null;return X.delete(e),n}function Hn(){let e=Date.now();for(let[t,n]of X)if(e-n.createdAt>$n)X.delete(t)}var ht=300000,$n=300000,Le,Oe,X;var Bn=C(()=>{vn();Mn();Xe();ze();tt();se();Le=new Map,Oe=new Set;X=new Map});import{resolve as wt}from"path";async function ws(e,t){let n=bt(t,"export");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(m){return new Response(JSON.stringify({error:m?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}r.activeStreams++;let u=Ss[a.format]??"application/octet-stream",l=bs[a.format]??"dat",d=`${a.table}.${l}`,p=new AbortController;e.signal.addEventListener("abort",()=>p.abort());let h=new ReadableStream({async start(m){let g={write(y){if(typeof y==="string")m.enqueue(new TextEncoder().encode(y));else m.enqueue(y)},async end(){}};try{let y=await Qe(c,a,g,p.signal,(E)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:E}}))});if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:y.rowCount}}));m.close()}catch(y){if(p.signal.aborted)try{m.close()}catch{}else m.error(y)}finally{await Et(r)}}});return new Response(h,{headers:{"Content-Type":u,"Content-Disposition":`attachment; filename="${d}"`}})}async function Cs(e,t){let n=bt(t,"import");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(l){return new Response(JSON.stringify({error:l?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!e.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});r.activeStreams++;let u=new AbortController;e.signal.addEventListener("abort",()=>u.abort());try{let l=await be(c,e.body,a,u.signal,(d)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:d}}))});return new Response(JSON.stringify({rowCount:l.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(l){return new Response(JSON.stringify({error:l?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await Et(r)}}var ys,Ct,Qn,H,Kn,Es=60000,Ss,bs,Ts;var Yn=C(()=>{Ke();je();P();Bn();ys=Number(process.env.DOTAZ_PORT)||6401,Ct=process.env.DOTAZ_HOST||"localhost",Qn=process.env.DOTAZ_DIST_DIR||wt(import.meta.dir,"../../dist");try{H=Rt(Ct)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}Kn=process.env.DOTAZ_ENCRYPTION_KEY;if(!Kn)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{Hn()},60000);setInterval(async()=>{let e=Date.now();for(let[,t]of yt())if(t.disconnectedAt!==null&&e-t.disconnectedAt>ht)await pe(t)},Es);Ss={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},bs={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};Ts=Bun.serve({port:ys,hostname:Ct,async fetch(e,t){let n=new URL(e.url);if(!ke(e,H))return new Response("Host not allowed",{status:403});if(n.pathname==="/api/bootstrap"&&e.method==="GET"){let a=Q(e,H);if(!a.ok)return K(a,"json");return Response.json({ok:!0})}if(n.pathname==="/rpc"){let a=Q(e,H);if(!a.ok)return K(a,"text");if(t.upgrade(e,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let r=n.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(r&&e.method==="GET"){let a=Q(e,H);if(!a.ok)return K(a,"json");return ws(e,r[1])}let s=n.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(s&&e.method==="POST"){let a=Q(e,H);if(!a.ok)return K(a,"json");return Cs(e,s[1])}if(n.pathname==="/api/menu-action"&&e.method==="POST"){let a=Q(e,H);if(!a.ok)return K(a,"json");try{let u=(await e.json())?.action;if(!u)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,l]of yt())if(l.ws)l.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:u}}));return new Response(JSON.stringify({ok:!0}),{headers:{"Content-Type":"application/json"}})}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}}let i=wt(Qn,n.pathname.slice(1)),o=Bun.file(i);if(await o.exists())return new Response(o);if(i=wt(Qn,"index.html"),o=Bun.file(i),await o.exists())return new Response(o,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open(e){let t=qn(e,Kn);Object.assign(e.data,t)},async close(e){await Fn(e.data)},async message(e,t){let n;try{n=JSON.parse(typeof t==="string"?t:new TextDecoder().decode(t))}catch{e.send(JSON.stringify({type:"response",id:0,success:!1,error:"Invalid JSON"}));return}if(n.type==="request"){if(n.method==="stream.createExportToken"){let{connectionId:s,database:i,...o}=n.params,a=St(e.data,"export",s,i,o);e.send(JSON.stringify({type:"response",id:n.id,success:!0,payload:{token:a}}));return}if(n.method==="stream.createImportToken"){let{connectionId:s,database:i,...o}=n.params,a=St(e.data,"import",s,i,o);e.send(JSON.stringify({type:"response",id:n.id,success:!0,payload:{token:a}}));return}let r=e.data.handlers[n.method];if(!r){e.send(JSON.stringify({type:"response",id:n.id,success:!1,error:`Unknown method: ${n.method}`}));return}try{let s=await r(n.params);e.send(JSON.stringify({type:"response",id:n.id,success:!0,payload:s}))}catch(s){e.send(JSON.stringify({type:"response",id:n.id,success:!1,error:s?.message??String(s),errorCode:s instanceof T?s.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${Ct}:${Ts.port}`)});var{secrets:jn}=globalThis.Bun;import{randomBytes as As}from"crypto";import{resolve as vs}from"path";function Me(e){return typeof e==="string"&&e.trim().length>0}function Dt(e,t){if(Me(t))return null;if(B(e))return null;return"DOTAZ_ENCRYPTION_KEY is required when binding Dotaz to a non-loopback host. Set it to a stable random value so saved credentials remain decryptable across restarts."}var Wn="dev.dotaz.server",zn="encryption-key",Z=process.argv.slice(2),Vn=Number(process.env.DOTAZ_PORT)||6401,Tt=process.env.DOTAZ_HOST||"localhost";for(let e=0;e<Z.length;e++){let t=Z[e];if((t==="--port"||t==="-p")&&Z[e+1])Vn=Number(Z[e+1]),e++;else if((t==="--host"||t==="-H")&&Z[e+1])Tt=Z[e+1],e++;else if(t==="--help")console.log(`Usage: dotaz [options]
333
+ ORDER BY matviewname`,[t])].map((r)=>({schema:t,name:r.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async beginTransaction(e){if(this.ensureConnected(),e){let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);await t.conn.unsafe("BEGIN"),t.txActive=!0,t.txAborted=!1}else{if(this.sessions.has(O)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let t=await this.pool.acquireConnection();try{await t.unsafe("BEGIN")}catch(n){throw await this.pool.releaseConnection(t),n}this.sessions.set(O,{conn:t,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit(e){this.ensureConnected();let t=e??O,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot commit during active iteration");try{await n.conn.unsafe("COMMIT"),n.txActive=!1,n.txAborted=!1}catch(r){if(B(r))throw n.txActive=!1,n.txAborted=!1,new b("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:r});try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch{}throw r}finally{if(t===O)this.sessions.delete(O),await this.pool.releaseConnection(n.conn)}}async rollback(e){this.ensureConnected();let t=e??O,n=this.sessions.get(t);if(!n)throw Error("No active transaction");if(n.iterating)throw Error("Cannot rollback during active iteration");try{await n.conn.unsafe("ROLLBACK"),n.txActive=!1,n.txAborted=!1}catch(r){if(B(r))n.txActive=!1,n.txAborted=!1;throw r}finally{if(t===O)this.sessions.delete(O),await this.pool.releaseConnection(n.conn)}}inTransaction(e){let t=e??O;return this.sessions.get(t)?.txActive??!1}isTxAborted(e){let t=e??O;return this.sessions.get(t)?.txAborted??!1}isIterating(e){let t=e??O;return this.sessions.get(t)?.iterating??!1}getDriverType(){return"postgresql"}listConnectionHandles(){if(!this.pool)return[];return this.pool.snapshot().map((e)=>this.describePoolConnection(e))}async terminateConnectionHandle(e){this.ensureConnected();let t=this.findSessionByHandleId(e);if(t){await this.cancel(t.sessionId),await this.releaseSession(t.sessionId);return}if(!await this.pool.terminateConnection(e))throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}async*iterate(e,t,n=1000,r,s){this.ensureConnected();let i=`dotaz_iter_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=s?this.sessions.get(s):void 0;if(s&&!o)throw Error(`Session "${s}" not found`);if(o?.txActive)throw Error("Cannot iterate on a session with an active transaction");let a=o?o.conn:await this.pool.acquireConnection(),c=!o;if(o)o.txActive=!0,o.iterating=!0;let u=!1;try{await a.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await a.unsafe(`DECLARE ${i} NO SCROLL CURSOR FOR ${e}`,t??[]);try{while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let m=[...await a.unsafe(`FETCH FORWARD ${n} FROM ${i}`)];if(m.length===0)break;if(yield m,m.length<n)break}}finally{try{await a.unsafe(`CLOSE ${i}`)}catch{}}await a.unsafe("COMMIT")}catch(l){u=!0;try{await a.unsafe("ROLLBACK")}catch{}throw l}finally{if(o)o.txActive=!1,o.iterating=!1;if(c)await this.pool.releaseConnection(a);else if(o&&!u)try{await a.unsafe("ROLLBACK")}catch{}}}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let m=0;m<t.length;m++)i.push(n[u][t[m]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}describePoolConnection(e){let t=this.findSessionByHandleId(e.handleId);if(t){let i=t.session,o=t.sessionId===O,a=i.txActive?"transaction":i.iterating||i.activeQueries.size>0?"active":"idle";return{handleId:e.handleId,role:o?"default-transaction":"session",state:a,label:o?"Default transaction":void 0,sessionId:o?void 0:t.sessionId,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:i.activeQueries.size,inTransaction:i.txActive,txAborted:i.txAborted,iterating:i.iterating,canTerminate:!0}}let n=e.role==="system"?"system":e.role==="idle"?"idle":"temporary",r=e.role==="system"?this.poolActiveQueries.size:0,s=r>0||e.role==="leased"?"active":"idle";return{handleId:e.handleId,role:n,state:s,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,activeQueryCount:r,inTransaction:!1,txAborted:!1,iterating:e.role==="leased",canTerminate:!0}}findSessionByHandleId(e){if(!this.pool)return;for(let[t,n]of this.sessions)if(this.pool.getConnectionId(n.conn)===e)return{sessionId:t,session:n};return}resolveSession(e){if(!e)return;let t=this.sessions.get(e);if(!t)throw Error(`Session "${e}" not found`);return t}mapDataType(e,t){if(e==="ARRAY")return"array";if(e==="USER-DEFINED"){let n=t.toLowerCase();if(n==="json"||n==="jsonb")return"json";return"enum"}return zs(e)}}var O="__default__";var nr=T(()=>{M();P();Tt();$e();qe()});var{SQL:Fe}=globalThis.Bun;function Gs(e){let t=e.toUpperCase();if(t==="INTEGER"||t==="INT"||t==="BIGINT"||t==="SMALLINT"||t==="TINYINT"||t==="MEDIUMINT")return"integer";if(t==="REAL"||t==="FLOAT"||t==="DOUBLE")return"float";if(t==="NUMERIC"||t==="DECIMAL")return"numeric";if(t==="BOOLEAN"||t==="BOOL")return"boolean";if(t==="TEXT")return"text";if(t.includes("VARCHAR")||t.includes("VARYING"))return"varchar";if(t.includes("CHAR")&&!t.includes("VARCHAR"))return"char";if(t==="DATE")return"date";if(t==="TIME")return"time";if(t==="DATETIME"||t.includes("TIMESTAMP"))return"timestamp";if(t==="JSON"||t==="JSONB")return"json";if(t==="BLOB"||t==="BINARY"||t.includes("VARBINARY"))return"binary";return"unknown"}class Rt{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;readOnlySessions=new Map;iterating=!1;iterateDb=null;iterateActive=!1;initSql=null;mainHandleId=null;mainCreatedAt=0;mainLastUsedAt=0;iterateHandleId=null;iterateCreatedAt=0;iterateLastUsedAt=0;nextHandleNumber=1;async connect(e){if(e.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");let t=e.initSql?.trim()||null;try{this.db=new Fe(`sqlite:${e.path}`),this.dbPath=e.path,this.resetMainHandle(),await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON"),this.initSql=t,await this.applyInitSql(this.db)}catch(n){if(this.db)try{await this.db.close()}catch{}throw this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,n instanceof b?n:ee(n)}this.connected=!0}async disconnect(){this.connected=!1;for(let e of this.readOnlySessions.values())await x(e.conn,{rollback:e.txActive});if(this.readOnlySessions.clear(),this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.initSql=null,this.mainHandleId=null,this.mainCreatedAt=0,this.mainLastUsedAt=0,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession(e,t){if(t?.readOnly)await this.openReadOnlyHandle(e);this.sessionIds.add(e)}async releaseSession(e){let t=this.readOnlySessions.get(e);if(t){this.readOnlySessions.delete(e),await x(t.conn,{rollback:t.txActive}),this.sessionIds.delete(e);return}if(this.txActive&&this.txOwnerSession===e){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete(e)}getSessionIds(){return[...this.sessionIds]}isSessionReadOnly(e){return this.readOnlySessions.has(e)}async execute(e,t,n){this.ensureConnected(),this.ensureKnownSession(n);let r=n===void 0?void 0:this.readOnlySessions.get(n);if(r){r.lastUsedAt=Date.now();let o=await this.runStatement(r.conn,e,t);return ne(r,e),o}this.ensureSessionCanExecute(n),this.markMainUsed();let s=await this.runStatement(this.db,e,t),i=e.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(i))this.txActive=!0,this.txOwnerSession=n??null;else if(/^(COMMIT|END)\b/.test(i))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(i)&&!/^ROLLBACK\s+TO\b/.test(i))this.txActive=!1,this.txOwnerSession=null;return s}async runStatement(e,t,n){let r=performance.now();try{let s=await e.unsafe(t,n??[]),i=Math.round(performance.now()-r),o=[...s];return{columns:o.length>0?Object.keys(o[0]).map((c)=>({name:c,dataType:"unknown"})):[],rows:o,rowCount:o.length,affectedRows:te(s),durationMs:i}}catch(s){throw s instanceof b?s:ee(s)}}async openReadOnlyHandle(e){if(this.ensureConnected(),this.readOnlySessions.has(e))return;if(!this.dbPath||this.dbPath===":memory:")throw Error("Read-only sessions require a file-backed SQLite database");let t=new Fe({adapter:"sqlite",filename:this.dbPath,readonly:!0});try{await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t),await t.unsafe("PRAGMA query_only = ON")}catch(r){try{await t.close()}catch{}throw r instanceof b?r:ee(r)}let n=Date.now();this.readOnlySessions.set(e,{conn:t,txActive:!1,iterating:!1,handleId:this.createHandleId(),createdAt:n,lastUsedAt:n})}async cancel(e,t){}async loadSchema(e){this.ensureConnected(),this.markMainUsed();let t=await this.getSchemas(),n=t[0].name,r=await this.getTables(n),s={[n]:r},i={},o={},a={},c={},u=new Map;for(let l of r){let m=`${n}.${l.name}`;i[m]=await this.getColumns(n,l.name),o[m]=await this.getIndexes(n,l.name);let f=await this.getForeignKeys(n,l.name);a[m]=f;for(let g of f){let d=`${g.referencedSchema}.${g.referencedTable}`;if(!u.has(d))u.set(d,[]);u.get(d).push({constraintName:g.name,referencingSchema:n,referencingTable:l.name,referencingColumns:g.columns,referencedColumns:g.referencedColumns})}}for(let l of r){let m=`${n}.${l.name}`;c[m]=u.get(m)??[]}return{schemas:t,tables:s,columns:i,indexes:o,foreignKeys:a,referencingForeignKeys:c}}async getSchemas(){return[{name:"main"}]}async getTables(e){return this.ensureConnected(),[...await this.db.unsafe("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name")].map((n)=>({schema:e,name:n.name,type:n.type}))}async getColumns(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(t)})`)],r=n.filter((s)=>s.pk>0).length;return n.map((s)=>({name:s.name,dataType:Gs(s.type||"BLOB"),nullable:s.notnull===0&&s.pk===0,defaultValue:s.dflt_value,isPrimaryKey:s.pk>0,isAutoIncrement:s.pk>0&&r===1&&s.type?.toUpperCase()==="INTEGER"}))}async getIndexes(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(t)})`)],r=[];for(let s of n){let i=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(s.name)})`)];r.push({name:s.name,columns:i.map((o)=>o.name),isUnique:s.unique===1,isPrimary:s.origin==="pk"})}return r}async getForeignKeys(e,t){this.ensureConnected();let n=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(t)})`)],r=new Map;for(let s of n){let i=r.get(s.id);if(i)i.columns.push(s.from),i.referencedColumns.push(s.to);else r.set(s.id,{name:`fk_${t}_${s.id}`,columns:[s.from],referencedSchema:"main",referencedTable:s.table,referencedColumns:[s.to],onUpdate:s.on_update,onDelete:s.on_delete})}return Array.from(r.values())}async ping(){this.ensureConnected(),this.markMainUsed(),await this.db.unsafe("SELECT 1")}async*iterate(e,t,n=1000,r,s){this.ensureConnected(),this.ensureKnownSession(s);let i=s===void 0?void 0:this.readOnlySessions.get(s),o=!i&&this.dbPath===":memory:",a;if(i){if(i.txActive)throw Error("Cannot iterate with an active transaction");a=i.conn,i.iterating=!0,i.lastUsedAt=Date.now()}else if(o){if(a=this.db,this.markMainUsed(),this.ensureSessionCanExecute(s),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=s??null,this.iterating=!0}else a=await this.getIterateDb(),this.iterateActive=!0,this.markIterateUsed();await a.unsafe("BEGIN");let c=!1;try{let u=0;while(!0){if(r?.aborted)throw new DOMException("Aborted","AbortError");let l=`${e} LIMIT ? OFFSET ?`,f=[...await a.unsafe(l,[...t??[],n,u])];if(f.length===0)break;if(yield f,f.length<n)break;u+=n}await a.unsafe("COMMIT"),c=!0}catch(u){try{await a.unsafe("ROLLBACK")}catch{}throw u}finally{if(!c)try{await a.unsafe("ROLLBACK")}catch{}if(i)i.iterating=!1,i.lastUsedAt=Date.now();else if(o)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null;else this.iterateActive=!1,this.markIterateUsed()}}async getIterateDb(){if(!this.iterateDb){let e=new Fe(`sqlite:${this.dbPath}`);try{await this.applyInitSql(e)}catch(t){try{await e.close()}catch{}throw t instanceof b?t:ee(t)}this.iterateDb=e,this.resetIterateHandle()}return this.iterateDb}async applyInitSql(e){if(!this.initSql)return;for(let t of H(this.initSql))await e.unsafe(t)}async importBatch(e,t,n,r){if(this.ensureConnected(),n.length===0)return 0;let s=t.map((u)=>this.quoteIdentifier(u)).join(", "),i=[],o=[];for(let u=0;u<n.length;u++){let l=[];for(let m=0;m<t.length;m++)i.push(n[u][t[m]]),l.push(this.placeholder(i.length));o.push(`(${l.join(", ")})`)}let a=`INSERT INTO ${e} (${s}) VALUES ${o.join(", ")}`;return(await this.execute(a,i,r)).affectedRows??n.length}async beginTransaction(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(t.txActive)throw Error("A transaction is already active");await t.conn.unsafe("BEGIN"),t.txActive=!0,t.lastUsedAt=Date.now();return}if(this.markMainUsed(),this.txActive)throw Error(e&&this.txOwnerSession!==e?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=e??null}async commit(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(!t.txActive)throw Error("No active transaction");if(t.iterating)throw Error("Cannot commit during active iteration");await t.conn.unsafe("COMMIT"),t.txActive=!1,t.lastUsedAt=Date.now();return}if(this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot commit during active iteration");this.markMainUsed(),await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback(e){this.ensureConnected(),this.ensureKnownSession(e);let t=e===void 0?void 0:this.readOnlySessions.get(e);if(t){if(!t.txActive)throw Error("No active transaction");if(t.iterating)throw Error("Cannot rollback during active iteration");try{await t.conn.unsafe("ROLLBACK")}finally{t.txActive=!1,t.lastUsedAt=Date.now()}return}if(this.ensureSessionOwnsTx(e),this.iterating)throw Error("Cannot rollback during active iteration");this.markMainUsed();try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction(e){if(e!==void 0){let t=this.readOnlySessions.get(e);if(t)return t.txActive;return this.txActive&&this.txOwnerSession===e}return this.txActive&&this.txOwnerSession===null}isTxAborted(e){return!1}isIterating(e){if(e!==void 0){let t=this.readOnlySessions.get(e);if(t)return t.iterating}return this.iterating}getDriverType(){return"sqlite"}listConnectionHandles(){if(!this.connected||!this.db||!this.mainHandleId)return[];let e=this.txActive?"transaction":this.iterating?"active":"idle",t=[{handleId:this.mainHandleId,role:"sqlite-main",state:e,createdAt:this.mainCreatedAt,lastUsedAt:this.mainLastUsedAt,activeQueryCount:0,inTransaction:this.txActive,txAborted:!1,iterating:this.iterating,canTerminate:!0}];if(this.iterateDb&&this.iterateHandleId)t.push({handleId:this.iterateHandleId,role:"sqlite-iterate",state:this.iterateActive?"active":"idle",createdAt:this.iterateCreatedAt,lastUsedAt:this.iterateLastUsedAt,activeQueryCount:this.iterateActive?1:0,inTransaction:this.iterateActive,txAborted:!1,iterating:this.iterateActive,canTerminate:!0});for(let[n,r]of this.readOnlySessions)t.push({handleId:r.handleId,role:"session",state:r.txActive?"transaction":r.iterating?"active":"idle",label:"Read-only session",sessionId:n,createdAt:r.createdAt,lastUsedAt:r.lastUsedAt,activeQueryCount:r.iterating?1:0,inTransaction:r.txActive,txAborted:!1,iterating:r.iterating,canTerminate:!0});return t}async terminateConnectionHandle(e){if(this.ensureConnected(),this.mainHandleId===e){await this.reopenMainConnection();return}for(let[t,n]of this.readOnlySessions)if(n.handleId===e){await this.releaseSession(t);return}if(this.iterateHandleId===e&&this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null,this.iterateHandleId=null,this.iterateCreatedAt=0,this.iterateLastUsedAt=0,this.iterateActive=!1;return}throw Error(`Connection handle not found: ${e}`)}quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}qualifyTable(e,t){if(e==="main")return this.quoteIdentifier(t);return`${this.quoteIdentifier(e)}.${this.quoteIdentifier(t)}`}emptyInsertSql(e){return`INSERT INTO ${e} DEFAULT VALUES`}placeholder(e){return`$${e}`}ensureKnownSession(e){if(e===void 0)return;if(!this.sessionIds.has(e))throw Error(`Session "${e}" not found`)}ensureSessionCanExecute(e){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if(e!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if(e===void 0||e!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx(e){if(!this.txActive)throw Error("No active transaction");if(!(e===void 0?this.txOwnerSession===null:this.txOwnerSession===e))throw Error(`Cannot modify transaction owned by ${this.txOwnerSession===null?"sessionless caller":`session "${this.txOwnerSession}"`}`)}ensureConnected(){if(!this.db||!this.connected)throw Error("Not connected. Call connect() first.")}async reopenMainConnection(){let e=this.dbPath;if(!e)throw Error("SQLite path is not available");if(this.db)try{await this.db.close()}catch{}let t=new Fe(`sqlite:${e}`);try{await t.unsafe("PRAGMA journal_mode = WAL"),await t.unsafe("PRAGMA foreign_keys = ON"),await this.applyInitSql(t)}catch(n){try{await t.close()}catch{}throw n instanceof b?n:ee(n)}this.db=t,this.txActive=!1,this.txOwnerSession=null,this.iterating=!1,this.resetMainHandle()}resetMainHandle(){let e=Date.now();this.mainHandleId=this.createHandleId(),this.mainCreatedAt=e,this.mainLastUsedAt=e}resetIterateHandle(){let e=Date.now();this.iterateHandleId=this.createHandleId(),this.iterateCreatedAt=e,this.iterateLastUsedAt=e}createHandleId(){let e=`sqlite-${this.nextHandleNumber}`;return this.nextHandleNumber+=1,e}markMainUsed(){this.mainLastUsedAt=Date.now()}markIterateUsed(){this.iterateLastUsedAt=Date.now()}}var rr=T(()=>{G();M();P();$e();qe()});import{chmodSync as Vs,unlinkSync as Js,writeFileSync as Xs}from"fs";import{tmpdir as Zs}from"os";import{join as ei}from"path";async function ri(){return new Promise((e,t)=>{let n=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),r=n.port;if(n.stop(!0),r>0)e(r);else t(Error("Could not find a free port"))})}async function si(e,t,n){let r=Date.now()+t;while(Date.now()<r){if(n&&n.exitCode!==null)return;try{(await Bun.connect({hostname:"127.0.0.1",port:e,socket:{data(){},open(i){i.end()},close(){},error(){}}})).end();return}catch{await Bun.sleep(ni)}}throw Error(`SSH tunnel port ${e} did not become available within ${t/1000}s`)}async function He(e,t,n){let r=e.localPort||await ri(),s=null,i=null;try{let o=["ssh","-N","-L",`${r}:${t}:${n}`,"-p",String(e.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],a={...process.env};if(e.authMethod==="key"&&e.keyPath)o.push("-i",e.keyPath),o.push("-o","BatchMode=yes");else if(e.password)s=ei(Zs(),`dotaz-askpass-${process.pid}-${Date.now()}`),Xs(s,`#!/bin/sh
334
+ echo '${e.password.replace(/'/g,"'\\''")}'`),Vs(s,448),a.SSH_ASKPASS=s,a.SSH_ASKPASS_REQUIRE="force",a.DISPLAY=a.DISPLAY||":0";if(o.push(`${e.username}@${e.host}`),i=Bun.spawn(o,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:a}),i.stdin&&typeof i.stdin!=="number")i.stdin.end();let c=i.stderr&&typeof i.stderr!=="number"?i.stderr:null,u=si(r,ti,i),l=i.exited.then(async(f)=>{if(f!==0){let g=await ii(c),d=oi(g)||`SSH process exited with code ${f}`;throw Error(d)}});return await Promise.race([u,l]),{localPort:r,close:async()=>{if(i)i.kill(),i=null;sr(s)}}}catch(o){if(i)i.kill();if(sr(s),o instanceof Error)throw ai(o);throw Error(`SSH tunnel error: ${String(o)}`)}}function sr(e){if(e)try{Js(e)}catch{}}async function ii(e){if(!e)return"";try{let t=e.getReader(),n=[];while(!0){let{done:r,value:s}=await t.read();if(r)break;n.push(s)}return Buffer.concat(n).toString("utf-8")}catch{return""}}function oi(e){if(!e.trim())return null;let t=e.trim().split(`
335
+ `);for(let n of t){let r=n.toLowerCase();if(r.includes("permission denied")||r.includes("authentication"))return`SSH authentication failed: ${n.trim()}`;if(r.includes("connection refused"))return`SSH host unreachable: ${n.trim()}`;if(r.includes("timed out")||r.includes("timeout"))return`SSH connection timed out: ${n.trim()}`;if(r.includes("no such file")||r.includes("no such identity"))return`SSH key file not found: ${n.trim()}`;if(r.includes("could not resolve"))return`SSH host unreachable: ${n.trim()}`}return t[t.length-1]?.trim()||null}function ai(e){let t=e.message.toLowerCase();if(t.includes("authentication")||t.includes("permission denied"))return Error(`SSH authentication failed: ${e.message}`);if(t.includes("econnrefused")||t.includes("connection refused")||t.includes("unreachable"))return Error(`SSH host unreachable: ${e.message}`);if(t.includes("timeout")||t.includes("timed out"))return Error(`SSH connection timed out: ${e.message}`);return Error(`SSH tunnel error: ${e.message}`)}var ti=15000,ni=100;var ir=()=>{};class Nt{drivers=new Map;passwords=new Map;states=new Map;listeners=[];sessionDeadListeners=[];appDb;opts;tunnels=new Map;healthTimers=new Map;reconnectStates=new Map;healthCheckRunning=new Set;connectAttempt=new Map;constructor(e,t){this.appDb=e,this.opts={...li,...t}}async connect(e,t){let n=this.appDb.getConnectionById(e);if(!n)throw Error(`Connection not found: ${e}`);this.cancelAutoReconnect(e);let r=(this.connectAttempt.get(e)??0)+1;if(this.connectAttempt.set(e,r),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),await this.setConnectionState(e,"connecting");try{let s=t?{...n.config,...t}:n.config;if(ge(s),k(s))this.passwords.set(e,s.password);s=await this.setupSshTunnel(e,s);let i=V(s),o=he(s);if(await o.connect(s),this.connectAttempt.get(e)!==r){await o.disconnect().catch(()=>{});return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),U[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let c=s,u=(c.activeDatabases??[]).filter((l)=>l!==c.database).map((l)=>this.connectDatabase(e,c,l));await Promise.allSettled(u)}await this.setConnectionState(e,"connected"),this.startHealthCheck(e)}catch(s){if(this.connectAttempt.get(e)!==r)return;await this.closeTunnel(e);let i=s instanceof Error?s.message:"Unknown connection error",o=s instanceof b?s.code:void 0;throw await this.setConnectionState(e,"error",i,o),s}}async disconnect(e){this.connectAttempt.set(e,(this.connectAttempt.get(e)??0)+1),this.cancelAutoReconnect(e),this.stopHealthCheck(e),await this.gracefulDisconnect(e),await this.closeTunnel(e),this.passwords.delete(e),await this.setConnectionState(e,"disconnected")}async reconnect(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.gracefulDisconnect(e);await this.connect(e)}getDriver(e,t){let n=this.drivers.get(e);if(!n)throw Error(`No active connection for id: ${e}`);let r=t??this.getDefaultDatabaseName(e),s=n.get(r);if(!s)throw Error(`No active driver for database "${r}" on connection ${e}`);return s}getConnectionState(e){return this.states.get(e)?.state??"disconnected"}listConnectionHandles(){let e=[];for(let[t,n]of this.drivers){let s=this.appDb.getConnectionById(t)?.name??t;for(let[i,o]of n)for(let a of o.listConnectionHandles())e.push({...a,connectionId:t,connectionName:s,database:i,driverType:o.getDriverType()})}return e}async terminateConnectionHandle(e,t,n){await this.getDriver(e,t).terminateConnectionHandle(n)}async listDatabases(e){let t=this.appDb.getConnectionById(e);if(!t||!U[t.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let n=V(t.config),r=this.getDriver(e,n),s=t.config.type==="postgresql"?ar:or,i=await r.execute(s),o=this.drivers.get(e),a=o?[...o.keys()]:[n];return i.rows.map((c)=>({name:c.name,isDefault:c.name===n,isActive:a.includes(c.name)}))}async activateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!U[n.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let r=n.config,s=this.drivers.get(e);if(!s)throw Error(`No active connection for id: ${e}`);if(s.has(t))return;let i=this.passwords.get(e)??r.password,o={...r,database:t,password:i};await this.connectDatabase(e,o,t);let a=[...new Set([...r.activeDatabases??[],t])];this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:a}})}async deactivateDatabase(e,t){let n=this.appDb.getConnectionById(e);if(!n||!U[n.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let r=n.config;if(t===V(r))throw Error("Cannot deactivate the default database");let s=this.drivers.get(e);if(s){let o=s.get(t);if(o)try{await o.disconnect()}finally{s.delete(t)}}let i=(r.activeDatabases??[]).filter((o)=>o!==t);this.appDb.updateConnection({id:e,name:n.name,config:{...r,activeDatabases:i.length>0?i:void 0}})}listConnections(){return this.appDb.listConnections().map((t)=>({...t,state:this.getConnectionState(t.id),error:this.states.get(t.id)?.error}))}createConnection(e,t=!1){return ge(e.config,t),this.appDb.createConnection(e)}updateConnection(e){return ge(e.config),{...this.appDb.updateConnection(e),state:this.getConnectionState(e.id),error:this.states.get(e.id)?.error}}setConnectionReadOnly(e,t){return{...this.appDb.setConnectionReadOnly(e,t),state:this.getConnectionState(e),error:this.states.get(e)?.error}}async deleteConnection(e){if(this.cancelAutoReconnect(e),this.stopHealthCheck(e),this.drivers.has(e))await this.disconnectAllDrivers(e);await this.closeTunnel(e),this.passwords.delete(e),this.states.delete(e),this.appDb.deleteConnection(e)}async testConnection(e){ge(e);let t=null,n=e;try{if(e.type==="postgresql"&&e.sshTunnel?.enabled)t=await He(e.sshTunnel,e.host,e.port),n={...e,host:"127.0.0.1",port:t.localPort};let r=he(n);return await r.connect(n),await r.disconnect(),{success:!0}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown connection error"}}finally{if(t)await t.close()}}async listDatabasesForConfig(e){if(e.type!=="postgresql"&&e.type!=="mysql")throw Error(`Listing databases is not supported for connection type: ${e.type}`);let t=e.type==="postgresql"?"postgres":"information_schema",n=e.database?e:{...e,database:t};ge(n);let r=null;try{if(n.type==="postgresql"&&n.sshTunnel?.enabled)r=await He(n.sshTunnel,n.host,n.port),n={...n,host:"127.0.0.1",port:r.localPort};let s=he(n);try{await s.connect(n);let i=n.type==="postgresql"?ar:or;return(await s.execute(i)).rows.map((a)=>a.name)}finally{await s.disconnect().catch(()=>{})}}finally{if(r)await r.close().catch(()=>{})}}onStatusChanged(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);if(t>=0)this.listeners.splice(t,1)}}onSessionDead(e){return this.sessionDeadListeners.push(e),()=>{let t=this.sessionDeadListeners.indexOf(e);if(t>=0)this.sessionDeadListeners.splice(t,1)}}async disconnectAll(){for(let t of[...this.reconnectStates.keys()])this.cancelAutoReconnect(t);for(let t of[...this.healthTimers.keys()])this.stopHealthCheck(t);let e=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let t of e)await this.disconnect(t)}startHealthCheck(e){this.stopHealthCheck(e);let t=setInterval(()=>{this.performHealthCheck(e)},this.opts.healthCheckIntervalMs);this.healthTimers.set(e,t)}stopHealthCheck(e){let t=this.healthTimers.get(e);if(t)clearInterval(t),this.healthTimers.delete(e)}async performHealthCheck(e){if(this.healthCheckRunning.has(e))return;this.healthCheckRunning.add(e);try{let t=this.drivers.get(e);if(!t)return;for(let n of t.values()){try{await Promise.race([n.ping(),new Promise((r,s)=>setTimeout(()=>s(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let r=!1;for(let s of t.values()){if(s.inTransaction()){r=!0;break}for(let i of s.getSessionIds())if(s.inTransaction(i)){r=!0;break}if(r)break}this.stopHealthCheck(e);try{await this.disconnectAllDrivers(e)}catch{}await this.setConnectionState(e,"disconnected","Connection lost"),this.startAutoReconnect(e,r);return}for(let r of n.getSessionIds())try{await n.execute("SELECT 1",void 0,r)}catch{try{await n.releaseSession(r)}catch{}for(let s of this.sessionDeadListeners)try{await s({connectionId:e,sessionId:r})}catch{}}}}finally{this.healthCheckRunning.delete(e)}}startAutoReconnect(e,t=!1){this.cancelAutoReconnect(e);let n={attempt:0,timer:null,cancelled:!1,hadTransaction:t};this.reconnectStates.set(e,n),this.scheduleReconnectAttempt(e,n)}cancelAutoReconnect(e){let t=this.reconnectStates.get(e);if(t){if(t.cancelled=!0,t.timer)clearTimeout(t.timer);this.reconnectStates.delete(e)}}async scheduleReconnectAttempt(e,t){if(t.cancelled)return;if(t.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete(e),await this.setConnectionState(e,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let n=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,t.attempt),this.opts.reconnectMaxDelayMs);t.timer=setTimeout(()=>{if(t.cancelled)return;this.attemptReconnect(e,t).catch(()=>{})},n)}async attemptReconnect(e,t){if(t.cancelled)return;let n=this.appDb.getConnectionById(e);if(!n){this.cancelAutoReconnect(e);return}t.attempt++,await this.setConnectionState(e,"reconnecting");try{await this.closeTunnel(e);let r=this.passwords.get(e),s=r?{...n.config,password:r}:n.config;s=await this.setupSshTunnel(e,s);let i=V(s),o=he(s);if(await o.connect(s),t.cancelled){await o.disconnect(),await this.closeTunnel(e);return}let a=new Map;if(a.set(i,o),this.drivers.set(e,a),U[s.type].supportsMultiDatabase&&"activeDatabases"in s&&s.activeDatabases){let u=s,l=(u.activeDatabases??[]).filter((m)=>m!==u.database).map((m)=>this.connectDatabase(e,u,m));await Promise.allSettled(l)}let c=t.hadTransaction;this.reconnectStates.delete(e),await this.setConnectionState(e,"connected",void 0,void 0,c),this.startHealthCheck(e)}catch{if(t.cancelled)return;await this.closeTunnel(e),this.scheduleReconnectAttempt(e,t)}}async gracefulDisconnect(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{for(let s of r.getSessionIds()){try{await r.cancel(s)}catch{}if(r.inTransaction(s))try{await r.rollback(s)}catch{}}if(r.inTransaction())try{await r.rollback()}catch{}try{await r.cancel()}catch{}}finally{try{await r.disconnect()}finally{t.delete(n)}}this.drivers.delete(e)}async disconnectAllDrivers(e){let t=this.drivers.get(e);if(!t)return;for(let[n,r]of t)try{await r.disconnect()}finally{t.delete(n)}this.drivers.delete(e)}async connectDatabase(e,t,n){let r=this.drivers.get(e);if(!r)throw Error(`No active connection for id: ${e}`);let s=this.tunnels.get(e),i=s?{host:"127.0.0.1",port:s.localPort}:{},o={...t,...i,database:n},a=he(o);await a.connect(o),r.set(n,a)}async setupSshTunnel(e,t){if(t.type!=="postgresql"||!t.sshTunnel?.enabled)return t;let n=await He(t.sshTunnel,t.host,t.port);return this.tunnels.set(e,n),{...t,host:"127.0.0.1",port:n.localPort}}async closeTunnel(e){let t=this.tunnels.get(e);if(t)await t.close(),this.tunnels.delete(e)}getActiveDatabases(e){let t=this.drivers.get(e);if(!t)return[];return[...t.keys()]}getDefaultDatabaseName(e){let t=this.appDb.getConnectionById(e);if(!t)throw Error(`Connection not found: ${e}`);return V(t.config)}async setConnectionState(e,t,n,r,s){this.states.set(e,{state:t,error:n});let i=this.listeners.map((o)=>o({connectionId:e,state:t,error:n,errorCode:r,transactionLost:s||void 0}));await Promise.allSettled(i)}}function he(e){let t;switch(e.type){case"postgresql":t=new vt;break;case"sqlite":t=new Rt;break;case"mysql":t=new At;break;default:throw Error(`Unsupported connection type: ${e.type}`)}if(process.env.DEBUG_SQL)t=new Ct(t);return t}function ge(e,t=!1){if(!e?.type)throw Error("Connection config must have a type");let n=U[e.type];if(!n)throw Error(`Unsupported connection type: ${e.type}`);if(n.hasHost&&k(e)){let r=n.label;if(!e.host)throw Error(`${r} host is required`);if(!e.port)throw Error(`${r} port is required`);if(!e.database)throw Error(`${r} database is required`);if(!e.user)throw Error(`${r} user is required`);if(!t&&(e.password===void 0||e.password===null))throw Error(`${r} password is required`)}else if(e.type==="sqlite"){if(!e.path)throw Error("SQLite path is required")}}var ci,or,ar="SELECT datname AS name FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname",li;var cr=T(()=>{le();P();tr();nr();rr();ir();ci=["mysql","information_schema","performance_schema","sys"],or=`SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN (${ci.map((e)=>`'${e}'`).join(", ")}) ORDER BY schema_name`,li={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5}});function ui(e){let t=[],n=/-c\s+([^\s=]+)=([^\s]+)/g,r;while((r=n.exec(e))!==null){let s=r[1],i=r[2].replace(/'/g,"''");t.push(`SET ${s} = '${i}';`)}return t.join(`
336
+ `)}function lr(){let e=process.env.DATABASE_URL;if(!e)return null;let t;try{t=new URL(e)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let n=t.protocol.replace(/:$/,"");if(n==="postgresql"||n==="postgres"){let r=t.hostname||"localhost",s=t.port?Number(t.port):5432,i=t.pathname.replace(/^\//,"")||"postgres",o=decodeURIComponent(t.username||"postgres"),a=decodeURIComponent(t.password||""),c=t.searchParams.get("options"),u=process.env.DOTAZ_INIT_SQL?.trim()||(c?ui(c):"")||void 0;return{name:`${r}/${i}`,config:{type:"postgresql",host:r,port:s,database:i,user:o,password:a,initSql:u}}}if(n==="mysql"){let r=t.hostname||"localhost",s=t.port?Number(t.port):3306,i=t.pathname.replace(/^\//,"")||"mysql",o=decodeURIComponent(t.username||"root"),a=decodeURIComponent(t.password||""),c=process.env.DOTAZ_INIT_SQL?.trim()||void 0;return{name:`${r}/${i}`,config:{type:"mysql",host:r,port:s,database:i,user:o,password:a,initSql:c}}}return console.warn(`DATABASE_URL: unsupported scheme "${n}", ignoring`),null}var re="env-default";function Dt(e,t){if(!t.has(e.id))return e;return{...e,config:Tn(e.config),serverManaged:!0}}function Qe(e,t){return(...n)=>{let r=e(...n);return r instanceof Promise?r.then((s)=>Dt(s,t)):Dt(r,t)}}function Ot(){return Ye}function dr(e,t){let n=crypto.randomUUID(),r=me.create(":memory:"),s=new Nt(r),i=new ce(s,void 0,r),o=new dt(t),a=(h,y)=>{if(d.ws)d.ws.send(JSON.stringify({type:"message",channel:h,payload:y}))},{handlers:c,sessionManager:u}=Vn(s,i,r,void 0,{encryption:o,emitMessage:a,allowServerFileAccess:!1}),l=new Set,m=lr();if(m){let h=Be.size>0?{...m.config,activeDatabases:[...Be]}:m.config;r.createConnectionWithId(re,{name:m.name,config:h}),l.add(re);let y=c["connections.list"];c["connections.list"]=()=>y().map((L)=>Dt(L,l));let w=c["connections.create"];c["connections.create"]=Qe(w,l);let p=c["connections.setReadOnly"];c["connections.setReadOnly"]=Qe(p,l);let S=c["connections.setGroup"];c["connections.setGroup"]=Qe(S,l);let E=c["connections.update"];c["connections.update"]=Qe((v)=>{if(l.has(v.id))throw Error("Server-managed connections cannot be reconfigured");return E(v)},l);let C=c["databases.activate"];c["databases.activate"]=async(v)=>{let L=await C(v);if(v.connectionId===re)Be.add(v.database);return L};let N=c["databases.deactivate"];c["databases.deactivate"]=async(v)=>{let L=await N(v);if(v.connectionId===re)Be.delete(v.database);return L}}let f=s.onSessionDead((h)=>{if(u.handleSessionDead(h.sessionId),d.ws)d.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:h.connectionId,sessions:u.listSessions(h.connectionId)}}))}),g=s.onStatusChanged(async(h)=>{if(d.ws)d.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:h.connectionId,state:h.state,error:h.error,errorCode:h.errorCode,transactionLost:h.transactionLost}}));if(h.state==="disconnected"||h.state==="error"){if(u.handleConnectionLost(h.connectionId),d.ws)d.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:h.connectionId,sessions:[]}}))}if(h.state==="connected")try{let y=await u.handleConnectionRestored(h.connectionId);if(y.length>0&&d.ws)d.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:h.connectionId,sessions:y}}))}catch(y){console.warn("Session restoration failed:",y instanceof Error?y.message:y)}}),d={id:n,appDb:r,connectionManager:s,queryExecutor:i,handlers:c,sessionManager:u,serverManagedIds:l,unsubscribe:()=>{f(),g()},ws:e,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(Ye.set(n,d),m)s.connect(re).catch((h)=>{console.warn("DATABASE_URL auto-connect failed:",h?.message??h)});return d}async function ye(e){if(Ye.delete(e.id),e.ttlTimer)clearTimeout(e.ttlTimer),e.ttlTimer=null;e.unsubscribe(),e.sessionManager.dispose();for(let t of e.queryExecutor.getRunningQueryIds())await e.queryExecutor.cancelQuery(t);await e.connectionManager.disconnectAll(),e.appDb.close()}async function mr(e){if(e.ws=null,e.disconnectedAt=Date.now(),e.activeStreams===0)await ye(e);else e.ttlTimer=setTimeout(async()=>{if(Ye.has(e.id))await ye(e)},_t)}async function It(e){if(e.activeStreams--,e.ws===null&&e.activeStreams===0)await ye(e)}function xt(e,t,n,r,s){let i=crypto.randomUUID();return se.set(i,{session:e,connectionId:n,database:r,params:s,type:t,createdAt:Date.now()}),i}function Lt(e,t){let n=se.get(e);if(!n)return null;if(n.type!==t)return null;if(Date.now()-n.createdAt>ur)return se.delete(e),null;return se.delete(e),n}function pr(){let e=Date.now();for(let[t,n]of se)if(e-n.createdAt>ur)se.delete(t)}var _t=300000,ur=300000,Ye,Be,se;var fr=T(()=>{Jn();cr();mt();xe();ht();le();Ye=new Map,Be=new Set;se=new Map});import{resolve as Pt}from"path";async function hi(e,t){let n=Lt(t,"export");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(d){return new Response(JSON.stringify({error:d?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}r.activeStreams++;let u=pi[a.format]??"application/octet-stream",l=fi[a.format]??"dat",m=`${a.table}.${l}`,f=new AbortController;e.signal.addEventListener("abort",()=>f.abort());let g=new ReadableStream({async start(d){let h={write(y){if(typeof y==="string")d.enqueue(new TextEncoder().encode(y));else d.enqueue(y)},async end(){}};try{let y=await et(c,a,h,f.signal,(w)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:w}}))});if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:y.rowCount}}));d.close()}catch(y){if(f.signal.aborted)try{d.close()}catch{}else d.error(y)}finally{await It(r)}}});return new Response(g,{headers:{"Content-Type":u,"Content-Disposition":`attachment; filename="${m}"`}})}async function gi(e,t){let n=Lt(t,"import");if(!n)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:r,connectionId:s,database:i,params:o}=n,a=o,c;try{c=r.connectionManager.getDriver(s,i)}catch(l){return new Response(JSON.stringify({error:l?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!e.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});r.activeStreams++;let u=new AbortController;e.signal.addEventListener("abort",()=>u.abort());try{let l=await ve(c,e.body,a,u.signal,(m)=>{if(r.ws)r.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:m}}))});return new Response(JSON.stringify({rowCount:l.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(l){return new Response(JSON.stringify({error:l?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await It(r)}}var di,kt,hr,Q,gr,mi=60000,pi,fi,yi;var yr=T(()=>{Kt();tt();rt();fr();di=Number(process.env.DOTAZ_PORT)||6401,kt=process.env.DOTAZ_HOST||"localhost",hr=process.env.DOTAZ_DIST_DIR||Pt(import.meta.dir,"../../dist");try{Q=qt(kt)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}gr=process.env.DOTAZ_ENCRYPTION_KEY;if(!gr)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{pr()},60000);setInterval(async()=>{let e=Date.now();for(let[,t]of Ot())if(t.disconnectedAt!==null&&e-t.disconnectedAt>_t)await ye(t)},mi);pi={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},fi={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};yi=Bun.serve({port:di,hostname:kt,async fetch(e,t){let n=new URL(e.url);if(!Ke(e,Q))return new Response("Host not allowed",{status:403});if(n.pathname==="/api/bootstrap"&&e.method==="GET"){let a=K(e,Q);if(!a.ok)return W(a,"json");return Response.json({ok:!0})}if(n.pathname==="/rpc"){let a=K(e,Q);if(!a.ok)return W(a,"text");if(t.upgrade(e,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let r=n.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(r&&e.method==="GET"){let a=K(e,Q);if(!a.ok)return W(a,"json");return hi(e,r[1])}let s=n.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(s&&e.method==="POST"){let a=K(e,Q);if(!a.ok)return W(a,"json");return gi(e,s[1])}if(n.pathname==="/api/menu-action"&&e.method==="POST"){let a=K(e,Q);if(!a.ok)return W(a,"json");try{let u=(await e.json())?.action;if(!u)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,l]of Ot())if(l.ws)l.ws.send(JSON.stringify({type:"message",channel:"menu.action",payload:{action:u}}));return new Response(JSON.stringify({ok:!0}),{headers:{"Content-Type":"application/json"}})}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}}let i=Pt(hr,n.pathname.slice(1)),o=Bun.file(i);if(await o.exists())return new Response(o);if(i=Pt(hr,"index.html"),o=Bun.file(i),await o.exists())return new Response(o,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open(e){let t=dr(e,gr);Object.assign(e.data,t)},async close(e){await mr(e.data)},async message(e,t){let n=Yt(typeof t==="string"?t:new Uint8Array(t));if(!n){e.send(JSON.stringify(Bt()));return}let s=await Qt(n,(i)=>{if(i==="stream.createExportToken")return({connectionId:o,database:a,...c})=>({token:xt(e.data,"export",o,a,c)});if(i==="stream.createImportToken")return({connectionId:o,database:a,...c})=>({token:xt(e.data,"import",o,a,c)});return e.data.handlers[i]});e.send(JSON.stringify(s))}}});console.log(`Dotaz web server running at http://${kt}:${yi.port}`)});var{secrets:Sr}=globalThis.Bun;import{randomBytes as Si}from"crypto";import{resolve as wi}from"path";function je(e){return typeof e==="string"&&e.trim().length>0}function Ht(e,t){if(je(t))return null;if(Y(e))return null;return"DOTAZ_ENCRYPTION_KEY is required when binding Dotaz to a non-loopback host. Set it to a stable random value so saved credentials remain decryptable across restarts."}var wr="dev.dotaz.server",Er="encryption-key",ie=process.argv.slice(2),Cr=Number(process.env.DOTAZ_PORT)||6401,Mt=process.env.DOTAZ_HOST||"localhost";for(let e=0;e<ie.length;e++){let t=ie[e];if((t==="--port"||t==="-p")&&ie[e+1])Cr=Number(ie[e+1]),e++;else if((t==="--host"||t==="-H")&&ie[e+1])Mt=ie[e+1],e++;else if(t==="--help")console.log(`Usage: dotaz [options]
334
337
 
335
338
  Options:
336
339
  -p, --port <port> Port to listen on (default: 6401)
337
340
  -H, --host <host> Host to bind to (default: localhost)
338
341
  --help Show this help message
339
- `),process.exit(0)}var Jn=Dt(Tt,process.env.DOTAZ_ENCRYPTION_KEY);if(Jn)console.error(Jn),process.exit(1);if(!Me(process.env.DOTAZ_ENCRYPTION_KEY)){let e=await jn.get({service:Wn,name:zn});if(!e){e=As(32).toString("hex");try{await jn.set({service:Wn,name:zn,value:e})}catch{}}process.env.DOTAZ_ENCRYPTION_KEY=e}process.env.DOTAZ_PORT=String(Vn);process.env.DOTAZ_HOST=Tt;process.env.DOTAZ_DIST_DIR=vs(import.meta.dir,"../dist");await Promise.resolve().then(() => (Yn(),{}));
342
+ `),process.exit(0)}var br=Ht(Mt,process.env.DOTAZ_ENCRYPTION_KEY);if(br)console.error(br),process.exit(1);if(!je(process.env.DOTAZ_ENCRYPTION_KEY)){let e=await Sr.get({service:wr,name:Er});if(!e){e=Si(32).toString("hex");try{await Sr.set({service:wr,name:Er,value:e})}catch{}}process.env.DOTAZ_ENCRYPTION_KEY=e}process.env.DOTAZ_PORT=String(Cr);process.env.DOTAZ_HOST=Mt;process.env.DOTAZ_DIST_DIR=wi(import.meta.dir,"../dist");await Promise.resolve().then(() => (yr(),{}));