@dotaz/server 0.0.21 → 0.0.22
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
|
@@ -141,7 +141,7 @@ Database schema:
|
|
|
141
141
|
${Z.schemaContext}
|
|
142
142
|
|
|
143
143
|
Request: ${Z.prompt}`}]})});if(!G.ok){let B=await G.text().catch(()=>"");if(G.status===401)throw Error("Invalid API key. Check your AI settings.");if(G.status===429)throw Error("Rate limited. Please wait and try again.");throw Error(`OpenAI API error (${G.status}): ${B.slice(0,200)}`)}let V=await G.json();return t0(V.choices?.[0]?.message?.content??"")}async function x7($,Z){if(!$.endpoint)throw Error("Custom AI endpoint URL is required. Check your AI settings.");return c0($,Z)}function t0($){let Z=$.trim(),W=Z.match(/^```(?:sql)?\s*\n?([\s\S]*?)\n?```$/);if(W)Z=W[1].trim();return Z}async function i0($,Z){if(!$.apiKey)throw Error("AI API key not configured. Go to AI Settings (command palette) to set it up.");switch($.provider){case"anthropic":return L7($,Z);case"openai":return c0($,Z);case"custom":return x7($,Z);default:throw Error(`Unknown AI provider: ${$.provider}`)}}function _7($){return $.dataType!=="binary"}async function n0($,Z,W,X){let G=performance.now(),V=await $.loadSchema(),B=[];for(let[z,R]of Object.entries(V.tables)){if(Z.scope==="schema"&&Z.schemaName&&z!==Z.schemaName)continue;for(let J of R){if(J.type!=="table")continue;if(Z.scope==="tables"&&Z.tableNames){if(!Z.tableNames.includes(J.name))continue}B.push(J)}}let H=[],U=0,Q=0,Y=$.getDriverType()==="postgresql",j=Y?"ILIKE":"LIKE";for(let z of B){if(X())return{matches:H,searchedTables:Q,totalMatches:U,cancelled:!0,elapsedMs:Math.round(performance.now()-G)};W(z.name,Q,B.length);let R=`${z.schema}.${z.name}`,O=(V.columns[R]??[]).filter(_7);if(O.length===0){Q++;continue}let A=[],L=[],K=0;for(let C of O){K++;let b=$.quoteIdentifier(C.name);A.push(`CAST(${b} AS TEXT) ${j} ${$.placeholder(K)}`),L.push(`%${Z.searchTerm}%`)}let x=$.qualifyTable(z.schema,z.name);K++;let F=$.placeholder(K),_=`SELECT * FROM ${x} WHERE ${A.join(" OR ")} LIMIT ${F}`;L.push(Z.resultsPerTable);try{let C=await $.execute(_,L);for(let b of C.rows){let X$=b;for(let v of O){let Y0=X$[v.name];if(Y0==null)continue;let j0=String(Y0);if(Y?j0.toLowerCase().includes(Z.searchTerm.toLowerCase()):j0.toLowerCase().includes(Z.searchTerm.toLowerCase())){H.push({schema:z.schema,table:z.name,column:v.name,row:X$}),U++;break}}}}catch(C){console.debug(`Search: skipped ${z.schema}.${z.name}:`,C instanceof Error?C.message:C)}Q++}return{matches:H,searchedTables:Q,totalMatches:U,cancelled:!1,elapsedMs:Math.round(performance.now()-G)}}var o0=M(()=>{q()});function N7($){let Z=[],W=0;while(W<$.length){let X=$[W];if(X==="'"||X==='"'){let G=X,V=X;W++;while(W<$.length)if($[W]===G)if(V+=$[W],W++,W<$.length&&$[W]===G)V+=$[W],W++;else break;else V+=$[W],W++;Z.push({type:"string",value:V,upper:V});continue}if(/\s/.test(X)){let G="";while(W<$.length&&/\s/.test($[W]))G+=$[W],W++;Z.push({type:"whitespace",value:G,upper:G});continue}if(/[a-zA-Z_]/.test(X)){let G="";while(W<$.length&&/[a-zA-Z0-9_]/.test($[W]))G+=$[W],W++;Z.push({type:"word",value:G,upper:G.toUpperCase()});continue}Z.push({type:"symbol",value:X,upper:X}),W++}return Z}function P7($,Z,W){let X=W.split(" "),G=Z,V=0;while(V<X.length&&G<$.length){if($[G].type==="whitespace"){G++;continue}if($[G].upper!==X[V])return 0;V++,G++}return V===X.length?G-Z:0}function s0($){let Z=$.trim();if(!Z)return"";let W=N7(Z);for(let U of W)if(U.type==="word"){if(M7.includes(U.upper))U.value=U.upper}let X=[],G="",V=0,B=0;while(V<W.length){let U=W[V];if(U.type==="symbol"&&U.value==="("){B++,G+=U.value,V++;continue}if(U.type==="symbol"&&U.value===")"){if(B>0)B--;G+=U.value,V++;continue}if(B>0){G+=U.value,V++;continue}if(U.type==="word"){let Q=!1,Y=[...r0,...a0].sort((j,z)=>z.split(" ").length-j.split(" ").length);for(let j of Y){let z=P7(W,V,j);if(z>0){let R=[];for(let L=V;L<V+z;L++)R.push(W[L].value);let J=R.filter((L)=>L.trim()).join(" "),O=a0.includes(j);if(r0.includes(j)||O){let L=G.trimEnd();if(L)X.push(L);G=J}else G+=J;V+=z,Q=!0;break}}if(Q)continue;if(F7.includes(U.upper)){let j=G.trimEnd();if(j)X.push(j);G=" "+U.value,V++;continue}}if(U.type==="whitespace"){if(G.trimEnd())G+=" "}else G+=U.value;V++}let H=G.trimEnd();if(H)X.push(H);return X.join(`
|
|
144
|
-
`)}var r0,a0,F7,M7;var e0=M(()=>{r0=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],a0=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],F7=["ON","AND","OR"],M7=["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 t${cm;constructor($){this.cm=$}async begin($,Z,W){let X=this.cm.getDriver($,Z);if(X.inTransaction(W))throw Error("Transaction already active on this connection");await X.beginTransaction(W)}async commit($,Z,W){let X=this.cm.getDriver($,Z);if(!X.inTransaction(W))throw Error("No active transaction to commit");await X.commit(W)}async rollback($,Z,W){let X=this.cm.getDriver($,Z);if(!X.inTransaction(W))throw Error("No active transaction to rollback");await X.rollback(W)}isActive($,Z,W){try{return this.cm.getDriver($,Z).inTransaction(W)}catch{return!1}}async rollbackIfActive($,Z,W){if(this.isActive($,Z,W))await this.rollback($,Z,W)}}class i${cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;constructor($,Z,W,X){this.cm=$;this.queryExecutor=Z;this.appDb=W;this.txManager=new t$($),this.encryption=X?.encryption,this.Utils=X?.Utils,this.emitMessage=X?.emitMessage,this.sessionManager=X?.sessionManager,this.demoDbSourcePath=X?.demoDbSourcePath,this.demoDbTargetPath=X?.demoDbTargetPath}listConnections(){return this.cm.listConnections()}createConnection($){return this.cm.createConnection($)}updateConnection($){return this.cm.updateConnection($)}setConnectionReadOnly($,Z){return this.cm.setConnectionReadOnly($,Z)}setConnectionGroup($,Z){return this.appDb.setConnectionGroup($,Z)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup($,Z){this.appDb.renameConnectionGroup($,Z)}deleteConnectionGroup($){this.appDb.deleteConnectionGroup($)}async deleteConnection($){await this.cm.deleteConnection($)}async testConnection($){return this.cm.testConnection($)}async connect($,Z,W){if(this.encryption){let X;if(W?.config){let G=W.encryptedSecrets?JSON.parse(await this.encryption.decrypt(W.encryptedSecrets)):{};X=h0(W.config,G)}else if(W?.encryptedConfig)X=JSON.parse(await this.encryption.decrypt(W.encryptedConfig));if(X){let G=this.appDb.getConnectionById($),V=W?.name??G?.name??$;if(!G)this.appDb.createConnectionWithId($,{name:V,config:X});else this.appDb.updateConnection({id:$,name:V,config:X})}}await this.cm.connect($,Z?{password:Z}:void 0)}async disconnect($){await this.cm.disconnect($)}async createSession($,Z){if(!this.sessionManager)throw Error("SessionManager not available");let W=await this.sessionManager.createSession($,Z);return this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)}),W}async destroySession($){if(!this.sessionManager)throw Error("SessionManager not available");let Z=this.sessionManager.getSession($);if(await this.sessionManager.destroySession($),Z)this.emitMessage?.("session.changed",{connectionId:Z.connectionId,sessions:this.sessionManager.listSessions(Z.connectionId)})}listSessions($){if(!this.sessionManager)return[];return this.sessionManager.listSessions($)}getDriver($,Z){return this.cm.getDriver($,Z)}async listDatabases($){return this.cm.listDatabases($)}async listDatabasesForConfig($){return this.cm.listDatabasesForConfig($)}async activateDatabase($,Z){await this.cm.activateDatabase($,Z)}async deactivateDatabase($,Z){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase($,Z),this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)});await this.cm.deactivateDatabase($,Z)}async executeQuery($,Z,W,X,G,V,B){return this.queryExecutor.executeQuery($,Z,W,void 0,X,G,V,B)}async executeStatements($,Z,W,X){let G=this.cm.getDriver($,W),V=async(B)=>{let H=G.inTransaction(B);try{if(!H)await G.beginTransaction(B);let U=[];for(let Q of Z){let Y=performance.now();try{let j=await G.execute(Q.sql,Q.params,B),z=Math.round(performance.now()-Y);U.push({...j,durationMs:z}),this.queryExecutor.sessionLog.add($,Q.sql,j.error?"error":"success",z,j.affectedRows??j.rowCount,j.error,W,B)}catch(j){let z=Math.round(performance.now()-Y);throw this.queryExecutor.sessionLog.add($,Q.sql,"error",z,0,j instanceof Error?j.message:String(j),W,B),j}}if(!H)await G.commit(B);return U}catch(U){if(!H)try{await G.rollback(B)}catch(Q){console.debug("Rollback after error failed:",Q instanceof Error?Q.message:Q)}throw U}};if(X)return V(X);return i(G,V)}submitQuery($,Z,W,X,G,V,B){let H=performance.now();this.queryExecutor.executeQuery($,Z,W,0,X,G,V,B).then((U)=>{this.emitMessage?.("query.completed",{queryId:X,results:U,durationMs:Math.round(performance.now()-H)})}).catch((U)=>{let Q=U?.code;this.emitMessage?.("query.completed",{queryId:X,error:U instanceof Error?U.message:String(U),errorCode:Q,durationMs:Math.round(performance.now()-H)})})}submitExplain($,Z,W,X,G,V,B){let H=performance.now();this.queryExecutor.explainQuery($,Z,W,G,V,B).then((U)=>{this.emitMessage?.("query.completed",{queryId:X,explainResult:U,durationMs:Math.round(performance.now()-H)})}).catch((U)=>{this.emitMessage?.("query.completed",{queryId:X,error:U instanceof Error?U.message:String(U),durationMs:Math.round(performance.now()-H)})})}async cancelQuery($){await this.queryExecutor.cancelQuery($)}async beginTransaction($,Z,W){await this.txManager.begin($,Z,W),this.queryExecutor.sessionLog.resetPendingCount($,Z,W)}async commitTransaction($,Z,W){await this.txManager.commit($,Z,W),this.queryExecutor.sessionLog.resetPendingCount($,Z,W)}async rollbackTransaction($,Z,W){await this.txManager.rollback($,Z,W),this.queryExecutor.sessionLog.resetPendingCount($,Z,W)}getTransactionLog($){let Z=this.queryExecutor.sessionLog.getEntries($.connectionId,$.database);if($.statusFilter)Z=Z.filter((G)=>G.status===$.statusFilter);if($.search){let G=$.search.toLowerCase();Z=Z.filter((V)=>V.sql.toLowerCase().includes(G))}let W=this.txManager.isActive($.connectionId,$.database,$.sessionId),X=W?this.queryExecutor.sessionLog.getPendingCount($.connectionId,$.database,$.sessionId):0;return{entries:Z,pendingStatementCount:X,inTransaction:W}}clearTransactionLog($,Z,W){this.queryExecutor.sessionLog.clear($,Z)}listHistory($){return this.appDb.listHistory($)}clearHistory($){this.appDb.clearHistory($)}listSavedViews($,Z,W){return this.appDb.listSavedViews($,Z,W)}createSavedView($){return this.appDb.createSavedView($)}updateSavedView($){return this.appDb.updateSavedView($)}deleteSavedView($){this.appDb.deleteSavedView($)}listSavedViewsByConnection($){return this.appDb.listSavedViewsByConnection($)}getSavedViewById($){return this.appDb.getSavedViewById($)}listBookmarks($,Z){return this.appDb.listBookmarks($,Z)}createBookmark($){return this.appDb.createBookmark($)}updateBookmark($){return this.appDb.updateBookmark($)}deleteBookmark($){this.appDb.deleteBookmark($)}async searchDatabase($){let Z=this.cm.getDriver($.connectionId,$.database);return n0(Z,{searchTerm:$.searchTerm,scope:$.scope,schemaName:$.schemaName,tableNames:$.tableNames,resultsPerTable:$.resultsPerTable??50},()=>{},()=>!1)}async exportData($){let Z=this.cm.getDriver($.connectionId,$.database);if(!$.filePath)throw Error("Export requires a file path");let W=this.emitMessage?(G)=>this.emitMessage("export.progress",{rowCount:G}):void 0;return{...await M0(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,includeHeaders:$.includeHeaders,delimiter:$.delimiter,encoding:$.encoding,utf8Bom:$.utf8Bom,batchSize:$.batchSize,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins},$.filePath,void 0,W),filePath:$.filePath}}async exportPreview($){let Z=this.cm.getDriver($.connectionId,$.database);return N0(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,delimiter:$.delimiter,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins})}async exportPreviewRows($){let Z=this.cm.getDriver($.connectionId,$.database),{sql:W,params:X}=H$({schema:$.schema,table:$.table,format:"csv",columns:$.columns,filters:$.filters,sort:$.sort,autoJoins:$.autoJoins},Z),G=X.length+1,V=`${W} LIMIT ${Z.placeholder(G)}`,H=(await Z.execute(V,[...X,$.limit])).rows,U=H.length>0?Object.keys(H[0]):$.columns??[];return{rows:H,columns:U}}async importData($){let Z=this.cm.getDriver($.connectionId,$.database),W=this.resolveImportStream($.filePath,$.fileContent),X=this.emitMessage?(G)=>this.emitMessage("import.progress",{rowCount:G}):void 0;return Q$(Z,W,{schema:$.schema,table:$.table,format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,mappings:$.mappings,batchSize:$.batchSize},void 0,X)}async importPreview($){let Z=this.resolveImportPreviewStream($.filePath,$.fileContent),W=await E0(Z,{format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,limit:$.limit});if($.filePath)try{let X=Bun.file($.filePath);W.fileSizeBytes=X.size}catch{}return W}resolveImportStream($,Z){if($)return Bun.file($).stream();if(Z!==void 0)return new ReadableStream({start(W){W.enqueue(new TextEncoder().encode(Z)),W.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream($,Z){if($){let G=Bun.file($).stream().getReader(),V=65536,B=0;return new ReadableStream({async pull(H){let{done:U,value:Q}=await G.read();if(U){H.close();return}if(B+=Q.byteLength,B>=65536){H.enqueue(Q),H.close(),G.releaseLock();return}H.enqueue(Q)},cancel(){G.releaseLock()}})}if(Z!==void 0)return new ReadableStream({start(W){W.enqueue(new TextEncoder().encode(Z)),W.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting($,Z){this.appDb.setSetting($,Z)}async encryptSecrets($){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt($)}async decryptConfig($){if(!this.encryption)throw Error("Encryption not available");return this.encryption.decrypt($)}async showOpenDialog({filters:$,multiple:Z}){if(!this.Utils)throw Error("Utils not available");let W=$&&$.length>0?$.flatMap((V)=>V.extensions.map((B)=>`*.${B}`)).join(","):"*",G=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:W,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:Z??!1})).filter((V)=>V!=="");return{paths:G,cancelled:G.length===0}}async showSaveDialog({defaultName:$}){if(!this.Utils)throw Error("Utils not available");let W=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!W||W==="")return{path:null,cancelled:!0};return{path:$?`${W}/${$}`:W,cancelled:!1}}formatSql($){return s0($)}async generateSql($){let Z=this.cm.getDriver($.connectionId,$.database),W=await Z.loadSchema(),X=d0(W),G=p0(this.appDb.getAllSettings());return{sql:await i0(G,{prompt:$.prompt,schemaContext:X,dialect:Z.getDriverType()})}}saveWorkspace($){this.appDb.saveWorkspace($)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let $=Bun.file(this.demoDbSourcePath);if(!await $.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,$);let Z={type:"sqlite",path:this.demoDbTargetPath},W=this.appDb.createConnection({name:"Bookstore (Demo)",config:Z});return await this.cm.connect(W.id),W}getSessionManager(){return this.sessionManager}}var $5=M(()=>{R$();l0();y$();w$();o0();e0()});function Z5($){return{"connections.list":()=>{return $.listConnections()},"connections.create":({name:Z,config:W,readOnly:X,color:G,groupName:V})=>{return $.createConnection({name:Z,config:W,readOnly:X,color:G,groupName:V})},"connections.update":({id:Z,name:W,config:X,readOnly:G,color:V,groupName:B})=>{return $.updateConnection({id:Z,name:W,config:X,readOnly:G,color:V,groupName:B})},"connections.setReadOnly":({id:Z,readOnly:W})=>{return $.setConnectionReadOnly(Z,W)},"connections.setGroup":({id:Z,groupName:W})=>{return $.setConnectionGroup(Z,W)},"connections.listGroups":()=>{return $.listConnectionGroups()},"connections.renameGroup":({oldName:Z,newName:W})=>{$.renameConnectionGroup(Z,W)},"connections.deleteGroup":({groupName:Z})=>{$.deleteConnectionGroup(Z)},"connections.delete":async({id:Z})=>{await $.deleteConnection(Z)},"connections.test":async({config:Z})=>{return $.testConnection(Z)},"connections.connect":async({connectionId:Z,password:W,config:X,encryptedSecrets:G,name:V,encryptedConfig:B})=>{await $.connect(Z,W,{config:X,encryptedSecrets:G,name:V,encryptedConfig:B})},"connections.disconnect":async({connectionId:Z})=>{await $.disconnect(Z)},"session.create":async({connectionId:Z,database:W})=>{return $.createSession(Z,W)},"session.destroy":async({sessionId:Z})=>{await $.destroySession(Z)},"session.list":({connectionId:Z})=>{return $.listSessions(Z)},"databases.list":async({connectionId:Z})=>{return $.listDatabases(Z)},"databases.listForConfig":async({config:Z})=>{return $.listDatabasesForConfig(Z)},"databases.activate":async({connectionId:Z,database:W})=>{await $.activateDatabase(Z,W)},"databases.deactivate":async({connectionId:Z,database:W})=>{await $.deactivateDatabase(Z,W)},"schema.load":async({connectionId:Z,database:W,sessionId:X})=>{return $.getDriver(Z,W).loadSchema(X)},"query.execute":async({connectionId:Z,sql:W,queryId:X,params:G,database:V,statements:B,sessionId:H,searchPath:U})=>{if(B&&B.length>0)return $.executeStatements(Z,B,V,H);return $.executeQuery(Z,W,G,X,V,H,U)},"query.submit":({connectionId:Z,sql:W,queryId:X,params:G,database:V,sessionId:B,searchPath:H})=>{return $.submitQuery(Z,W,G,X,V,B,H),{queryId:X}},"query.submitExplain":({connectionId:Z,sql:W,analyze:X,queryId:G,database:V,sessionId:B,searchPath:H})=>{return $.submitExplain(Z,W,X??!1,G,V,B,H),{queryId:G}},"query.cancel":async({queryId:Z})=>{await $.cancelQuery(Z)},"query.format":({sql:Z})=>{return{sql:$.formatSql(Z)}},"tx.begin":async({connectionId:Z,database:W,sessionId:X})=>{await $.beginTransaction(Z,W,X)},"tx.commit":async({connectionId:Z,database:W,sessionId:X})=>{await $.commitTransaction(Z,W,X)},"tx.rollback":async({connectionId:Z,database:W,sessionId:X})=>{await $.rollbackTransaction(Z,W,X)},"transaction.getLog":(Z)=>{return $.getTransactionLog(Z)},"transaction.clearLog":({connectionId:Z,database:W,sessionId:X})=>{$.clearTransactionLog(Z,W,X)},"search.searchDatabase":async(Z)=>{return $.searchDatabase(Z)},"export.exportData":async(Z)=>{return $.exportData(Z)},"export.preview":async(Z)=>{return{content:await $.exportPreview(Z)}},"export.previewRows":async(Z)=>{return $.exportPreviewRows(Z)},"import.importData":async(Z)=>{return $.importData(Z)},"import.preview":async(Z)=>{return $.importPreview(Z)},"history.list":(Z)=>{return $.listHistory(Z)},"history.clear":({connectionId:Z})=>{$.clearHistory(Z)},"views.save":({connectionId:Z,schemaName:W,tableName:X,name:G,config:V})=>{if(!G||!G.trim())throw Error("View name is required");if(!Z)throw Error("connectionId is required");if(!X)throw Error("tableName is required");if($.listSavedViews(Z,W,X).some((H)=>H.name===G.trim()))throw Error(`A view named "${G.trim()}" already exists for this table`);return $.createSavedView({connectionId:Z,schemaName:W,tableName:X,name:G.trim(),config:V})},"views.update":({id:Z,name:W,config:X})=>{if(!Z)throw Error("View id is required");if(!W||!W.trim())throw Error("View name is required");let G=$.getSavedViewById(Z);if(!G)throw Error(`Saved view not found: ${Z}`);if($.listSavedViews(G.connectionId,G.schemaName,G.tableName).some((B)=>B.id!==Z&&B.name===W.trim()))throw Error(`A view named "${W.trim()}" already exists for this table`);return $.updateSavedView({id:Z,name:W.trim(),config:X})},"views.delete":({id:Z})=>{$.deleteSavedView(Z)},"views.listByConnection":({connectionId:Z})=>{return $.listSavedViewsByConnection(Z)},"bookmarks.list":({connectionId:Z,search:W})=>{return $.listBookmarks(Z,W)},"bookmarks.create":({connectionId:Z,database:W,name:X,description:G,sql:V})=>{if(!X||!X.trim())throw Error("Bookmark name is required");return $.createBookmark({connectionId:Z,database:W,name:X.trim(),description:G,sql:V})},"bookmarks.update":({id:Z,name:W,description:X,sql:G})=>{if(!Z)throw Error("Bookmark id is required");if(!W||!W.trim())throw Error("Bookmark name is required");return $.updateBookmark({id:Z,name:W.trim(),description:X,sql:G})},"bookmarks.delete":({id:Z})=>{$.deleteBookmark(Z)},"settings.getAll":()=>{return $.getAllSettings()},"settings.set":({key:Z,value:W})=>{$.setSetting(Z,W)},"storage.encryptSecrets":async({secrets:Z})=>{if(!$.encryptSecrets)throw Error("Encryption not available");return{encryptedSecrets:await $.encryptSecrets(Z)}},"storage.decryptConfig":async({encryptedConfig:Z})=>{if(!$.decryptConfig)throw Error("Encryption not available");return{config:await $.decryptConfig(Z)}},"ai.generateSql":async(Z)=>{return $.generateSql(Z)},"workspace.save":({data:Z})=>{$.saveWorkspace(Z)},"workspace.load":()=>{return $.loadWorkspace()},"system.showOpenDialog":async(Z)=>{if(!$.showOpenDialog)return{paths:[],cancelled:!0};return $.showOpenDialog(Z)},"system.showSaveDialog":async(Z)=>{if(!$.showSaveDialog)return{path:null,cancelled:!0};return $.showSaveDialog(Z)},"demo.initialize":async()=>{if(!$.initializeDemo)throw Error("Demo initialization is not available");return $.initializeDemo()}}}function k7($){if(!$)throw Error("AppDatabase is required");return $}function W5($,Z,W,X,G){let V=k7(W),B=Z??new n($,void 0,V),H=new c$($,V,(Q,Y,j)=>{B.sessionLog.resetPendingCount(Q,Y,j)}),U=new i$($,B,V,{encryption:G?.encryption,Utils:X,emitMessage:G?.emitMessage,sessionManager:H,demoDbSourcePath:G?.demoDbSourcePath,demoDbTargetPath:G?.demoDbTargetPath});return{handlers:Z5(U),sessionManager:H,adapter:U}}var X5=M(()=>{g$();m0();$5()});class n${inner;constructor($){this.inner=$}log($,Z,W,X){let G=$.replace(/\s+/g," ").trim(),V=Z&&Z.length>0;if(X)console.debug(`[SQL ERROR] ${G}${V?` -- params: ${JSON.stringify(Z)}`:""} (${W}ms)`,X);else if(W!==void 0)console.debug(`[SQL] ${G}${V?` -- params: ${JSON.stringify(Z)}`:""} (${W}ms)`);else console.debug(`[SQL] ${G}${V?` -- params: ${JSON.stringify(Z)}`:""}`)}async execute($,Z,W){let X=performance.now();try{let G=await this.inner.execute($,Z,W);return this.log($,Z,Math.round(performance.now()-X)),G}catch(G){throw this.log($,Z,Math.round(performance.now()-X),G),G}}async*iterate($,Z,W,X,G){this.log($,Z),yield*this.inner.iterate($,Z,W,X,G)}async importBatch($,Z,W,X){let G=`INSERT INTO ${$} (${Z.join(", ")}) VALUES ... [${W.length} rows]`,V=performance.now();try{let B=await this.inner.importBatch($,Z,W,X);return this.log(G,void 0,Math.round(performance.now()-V)),B}catch(B){throw this.log(G,void 0,Math.round(performance.now()-V),B),B}}connect($){return this.inner.connect($)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession($){return this.inner.reserveSession($)}releaseSession($){return this.inner.releaseSession($)}getSessionIds(){return this.inner.getSessionIds()}cancel($){return this.inner.cancel($)}ping(){return this.inner.ping()}async loadSchema($){console.debug("[SQL] loadSchema started"+($?` (session: ${$})`:""));let Z=performance.now();try{let W=await this.inner.loadSchema($),X=Object.values(W.tables).reduce((G,V)=>G+V.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${W.schemas.length} schemas, ${X} tables (${Math.round(performance.now()-Z)}ms)`),W}catch(W){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-Z)}ms)`,W),W}}beginTransaction($){return this.inner.beginTransaction($)}commit($){return this.inner.commit($)}rollback($){return this.inner.rollback($)}inTransaction($){return this.inner.inTransaction($)}isTxAborted($){return this.inner.isTxAborted($)}isIterating($){return this.inner.isIterating($)}getDriverType(){return this.inner.getDriverType()}quoteIdentifier($){return this.inner.quoteIdentifier($)}qualifyTable($,Z){return this.inner.qualifyTable($,Z)}emptyInsertSql($){return this.inner.emptyInsertSql($)}placeholder($){return this.inner.placeholder($)}}var{SQL:C7}=globalThis.Bun;class e{url;resetFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;constructor($,Z){this.url=$;this.resetFn=Z}async connect(){this.systemConn=this.createSql(),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1")}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.systemConn}createConnection(){let $=this.createSql();return this.connections.add($),$}acquireConnection(){if(this.idleConn){let $=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),$}return this.createConnection()}async releaseConnection($){if(!this.idleConn){if(this.resetFn)try{await this.resetFn($)}catch{await this.destroyConnection($);return}this.idleConn=$,this.scheduleIdleTimeout()}else await this.destroyConnection($)}async destroyConnection($){if(this.idleConn===$)this.idleConn=null,this.clearIdleTimer();this.connections.delete($);try{await $.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn){this.connections.delete(this.systemConn);try{await this.systemConn.close()}catch{}}this.systemConn=this.createSql(),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1")}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let $=[...this.connections];this.connections.clear(),this.systemConn=null,await Promise.allSettled($.map((Z)=>Z.close()))}createSql(){return new C7({url:this.url,max:1})}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},E7)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var E7=30000;var o$=()=>{};function r$($){let Z=$ instanceof Error?$.message:String($),W=$?.errno??$?.code;if(/ECONNREFUSED|connection refused/i.test(Z))return new E("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new E("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new E("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections|connection limit/i.test(Z))return new E("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new E("SSL_ERROR",Z,{cause:$});if(W?.startsWith("28")||/authentication failed|password authentication/i.test(Z))return new Y$(Z,{cause:$});if(W==="3D000"||/database .* does not exist/i.test(Z))return new E("DATABASE_NOT_FOUND",Z,{cause:$});if(W==="23505"||/violates unique constraint|duplicate key/i.test(Z))return new D("CONSTRAINT_UNIQUE",Z,{cause:$});if(W==="23503"||/violates foreign key constraint/i.test(Z))return new D("CONSTRAINT_FK",Z,{cause:$});if(W==="23514"||/violates check constraint/i.test(Z))return new D("CONSTRAINT_CHECK",Z,{cause:$});if(W==="23502"||/violates not-null constraint/i.test(Z))return new D("CONSTRAINT_NOT_NULL",Z,{cause:$});if(W==="42601"||/syntax error/i.test(Z))return new k("QUERY_SYNTAX",Z,{cause:$});if(W==="42P01"||/relation .* does not exist/i.test(Z))return new k("TABLE_NOT_FOUND",Z,{cause:$});if(W==="42703"||/column .* does not exist/i.test(Z))return new k("COLUMN_NOT_FOUND",Z,{cause:$});if(W==="42501"||/permission denied/i.test(Z))return new N("PERMISSION_DENIED",Z,{cause:$});if(W==="40001")return new k("SERIALIZATION_FAILURE",Z,{cause:$});if(W==="40P01")return new k("DEADLOCK_DETECTED",Z,{cause:$});if(W==="25P02")return new k("TRANSACTION_ABORTED",Z,{cause:$});if(W?.startsWith("42")||W?.startsWith("22"))return new k("QUERY_EXECUTION",Z,{cause:$});return new N("UNKNOWN",Z,{cause:$})}function a$($){let Z=$ instanceof Error?$.message:String($);if(/unable to open database|cannot open/i.test(Z))return new E("CONNECTION_REFUSED",Z,{cause:$});if(/UNIQUE constraint failed/i.test(Z))return new D("CONSTRAINT_UNIQUE",Z,{cause:$});if(/FOREIGN KEY constraint failed/i.test(Z))return new D("CONSTRAINT_FK",Z,{cause:$});if(/CHECK constraint failed/i.test(Z))return new D("CONSTRAINT_CHECK",Z,{cause:$});if(/NOT NULL constraint failed/i.test(Z))return new D("CONSTRAINT_NOT_NULL",Z,{cause:$});if(/no such table/i.test(Z))return new k("TABLE_NOT_FOUND",Z,{cause:$});if(/no such column/i.test(Z))return new k("COLUMN_NOT_FOUND",Z,{cause:$});if(/syntax error|near /i.test(Z))return new k("QUERY_SYNTAX",Z,{cause:$});if(/authorization denied|not authorized/i.test(Z))return new N("PERMISSION_DENIED",Z,{cause:$});return new N("UNKNOWN",Z,{cause:$})}function s$($){let Z=$ instanceof Error?$.message:String($),W=$?.errno;if(/ECONNREFUSED|connection refused/i.test(Z)||W===2003)return new E("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new E("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new E("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections/i.test(Z)||W===1040)return new E("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new E("SSL_ERROR",Z,{cause:$});if(W===1045||/access denied/i.test(Z))return new Y$(Z,{cause:$});if(W===1049||/unknown database/i.test(Z))return new E("DATABASE_NOT_FOUND",Z,{cause:$});if(W===1062||/duplicate entry/i.test(Z))return new D("CONSTRAINT_UNIQUE",Z,{cause:$});if(W===1451||W===1452||/foreign key constraint/i.test(Z)||/cannot delete or update a parent row/i.test(Z)||/cannot add or update a child row/i.test(Z))return new D("CONSTRAINT_FK",Z,{cause:$});if(W===3819||/check constraint/i.test(Z))return new D("CONSTRAINT_CHECK",Z,{cause:$});if(W===1048||/cannot be null/i.test(Z))return new D("CONSTRAINT_NOT_NULL",Z,{cause:$});if(W===1213||/deadlock found/i.test(Z))return new k("DEADLOCK_DETECTED",Z,{cause:$});if(W===1205||/lock wait timeout exceeded/i.test(Z))return new k("SERIALIZATION_FAILURE",Z,{cause:$});if(W===1064||/syntax error|you have an error in your sql syntax/i.test(Z))return new k("QUERY_SYNTAX",Z,{cause:$});if(W===1146||/table .* doesn't exist/i.test(Z))return new k("TABLE_NOT_FOUND",Z,{cause:$});if(W===1054||/unknown column/i.test(Z))return new k("COLUMN_NOT_FOUND",Z,{cause:$});if(W===1142||W===1143||/command denied|access denied/i.test(Z))return new N("PERMISSION_DENIED",Z,{cause:$});return new N("UNKNOWN",Z,{cause:$})}var x$=M(()=>{y()});function p($){let Z=$;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;return 0}var z4,K4,R4,O4,A4,L4;var G5=M(()=>{q();z4=new Set(["integer","serial","float","numeric"]),K4=new Set(["boolean"]),R4=new Set(["timestamp","date"]),O4=new Set(["text","varchar","char"]),A4=new Set(["json"]),L4=new Set(["array"])});var V5=M(()=>{G5();q()});var B5=M(()=>{B$();V5()});function _$($,Z){let W=b$(Z).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(W)){if($.txActive=!0,"txAborted"in $)$.txAborted=!1}else if(/^(COMMIT|END)\b/.test(W)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}else if(/^ROLLBACK\b/.test(W)&&!/^ROLLBACK\s+TO\b/.test(W)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}}function f($){let Z=$?.code;if(typeof Z==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(Z))return!0;let W=$ instanceof Error?$.message:String($);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(W)}async function l($,Z){if(Z?.rollback)try{await $.unsafe("ROLLBACK")}catch{}try{await $.close()}catch{}}var e$=M(()=>{B5()});function D7($){switch($.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 $0{pool=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect($){if($.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let Z=`mysql://${encodeURIComponent($.user)}:${encodeURIComponent($.password)}@${$.host}:${$.port}/${encodeURIComponent($.database)}`;this.pool=new e(Z,(W)=>W.unsafe("RESET CONNECTION"));try{await this.pool.connect()}catch(W){throw this.pool=null,W instanceof N?W:s$(W)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,$]of this.sessions)await l($.conn,{rollback:$.txActive});if(this.sessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=this.pool.createConnection();this.sessions.set($,{conn:Z,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession($){let Z=this.sessions.get($);if(!Z)return;this.sessions.delete($),await l(Z.conn,{rollback:!0})}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==T)}async execute($,Z,W,X){this.ensureConnected();let G=this.resolveSession(W),V=G?G.conn:this.pool.getSystemConnection(),B=performance.now(),H=V.unsafe($,Z??[]),U=G?void 0:X??Symbol();if(G)G.activeQueries.add(H);else this.poolActiveQueries.set(U,H);try{let Q=await H,Y=Math.round(performance.now()-B),j=[...Q];if(G)_$(G,$);return{columns:j.length>0?Object.keys(j[0]).map((R)=>({name:R,dataType:"unknown"})):[],rows:j,rowCount:j.length,affectedRows:p(Q),durationMs:Y}}catch(Q){throw Q instanceof N?Q:s$(Q)}finally{if(G)G.activeQueries.delete(H);else this.poolActiveQueries.delete(U)}}async cancel($,Z){if($){let W=this.sessions.get($);if(W){for(let X of W.activeQueries)X.cancel();W.activeQueries.clear()}}else if(Z){let W=this.poolActiveQueries.get(Z);if(W)W.cancel(),this.poolActiveQueries.delete(Z)}else{for(let W of this.poolActiveQueries.values())W.cancel();this.poolActiveQueries.clear()}}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),W=Z?Z.conn:this.pool.getSystemConnection(),X=await this.getSchemas(W),G=X.map((J)=>J.name),V={};for(let J of X)V[J.name]=await this.getTables(W,J.name);let[B,H,U,Q]=await Promise.all([W.unsafe(`SELECT
|
|
144
|
+
`)}var r0,a0,F7,M7;var e0=M(()=>{r0=["SELECT","FROM","WHERE","ORDER BY","GROUP BY","HAVING","LIMIT","OFFSET","UNION","UNION ALL","INTERSECT","EXCEPT","INSERT INTO","UPDATE","SET","DELETE FROM","VALUES"],a0=["LEFT OUTER JOIN","RIGHT OUTER JOIN","FULL OUTER JOIN","CROSS JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","NATURAL JOIN","JOIN"],F7=["ON","AND","OR"],M7=["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 t${cm;constructor($){this.cm=$}async begin($,Z,W){let X=this.cm.getDriver($,Z);if(X.inTransaction(W))throw Error("Transaction already active on this connection");await X.beginTransaction(W)}async commit($,Z,W){let X=this.cm.getDriver($,Z);if(!X.inTransaction(W))throw Error("No active transaction to commit");await X.commit(W)}async rollback($,Z,W){let X=this.cm.getDriver($,Z);if(!X.inTransaction(W))throw Error("No active transaction to rollback");await X.rollback(W)}isActive($,Z,W){try{return this.cm.getDriver($,Z).inTransaction(W)}catch{return!1}}async rollbackIfActive($,Z,W){if(this.isActive($,Z,W))await this.rollback($,Z,W)}}class i${cm;queryExecutor;appDb;txManager;encryption;Utils;emitMessage;sessionManager;demoDbSourcePath;demoDbTargetPath;constructor($,Z,W,X){this.cm=$;this.queryExecutor=Z;this.appDb=W;this.txManager=new t$($),this.encryption=X?.encryption,this.Utils=X?.Utils,this.emitMessage=X?.emitMessage,this.sessionManager=X?.sessionManager,this.demoDbSourcePath=X?.demoDbSourcePath,this.demoDbTargetPath=X?.demoDbTargetPath}listConnections(){return this.cm.listConnections()}createConnection($){return this.cm.createConnection($)}updateConnection($){return this.cm.updateConnection($)}setConnectionReadOnly($,Z){return this.cm.setConnectionReadOnly($,Z)}setConnectionGroup($,Z){return this.appDb.setConnectionGroup($,Z)}listConnectionGroups(){return this.appDb.listConnectionGroups()}renameConnectionGroup($,Z){this.appDb.renameConnectionGroup($,Z)}deleteConnectionGroup($){this.appDb.deleteConnectionGroup($)}async deleteConnection($){await this.cm.deleteConnection($)}async testConnection($){return this.cm.testConnection($)}async connect($,Z,W){if(this.encryption){let X;if(W?.config){let G=W.encryptedSecrets?JSON.parse(await this.encryption.decrypt(W.encryptedSecrets)):{};X=h0(W.config,G)}else if(W?.encryptedConfig)X=JSON.parse(await this.encryption.decrypt(W.encryptedConfig));if(X){let G=this.appDb.getConnectionById($),V=W?.name??G?.name??$;if(!G)this.appDb.createConnectionWithId($,{name:V,config:X});else this.appDb.updateConnection({id:$,name:V,config:X})}}await this.cm.connect($,Z?{password:Z}:void 0)}async disconnect($){await this.cm.disconnect($)}async createSession($,Z){if(!this.sessionManager)throw Error("SessionManager not available");let W=await this.sessionManager.createSession($,Z);return this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)}),W}async destroySession($){if(!this.sessionManager)throw Error("SessionManager not available");let Z=this.sessionManager.getSession($);if(await this.sessionManager.destroySession($),Z)this.emitMessage?.("session.changed",{connectionId:Z.connectionId,sessions:this.sessionManager.listSessions(Z.connectionId)})}listSessions($){if(!this.sessionManager)return[];return this.sessionManager.listSessions($)}getDriver($,Z){return this.cm.getDriver($,Z)}async listDatabases($){return this.cm.listDatabases($)}async listDatabasesForConfig($){return this.cm.listDatabasesForConfig($)}async activateDatabase($,Z){await this.cm.activateDatabase($,Z)}async deactivateDatabase($,Z){if(this.sessionManager)await this.sessionManager.destroySessionsForDatabase($,Z),this.emitMessage?.("session.changed",{connectionId:$,sessions:this.sessionManager.listSessions($)});await this.cm.deactivateDatabase($,Z)}async executeQuery($,Z,W,X,G,V,B){return this.queryExecutor.executeQuery($,Z,W,void 0,X,G,V,B)}async executeStatements($,Z,W,X){let G=this.cm.getDriver($,W),V=async(B)=>{let H=G.inTransaction(B);try{if(!H)await G.beginTransaction(B);let U=[];for(let Q of Z){let Y=performance.now();try{let j=await G.execute(Q.sql,Q.params,B),z=Math.round(performance.now()-Y);U.push({...j,durationMs:z}),this.queryExecutor.sessionLog.add($,Q.sql,j.error?"error":"success",z,j.affectedRows??j.rowCount,j.error,W,B)}catch(j){let z=Math.round(performance.now()-Y);throw this.queryExecutor.sessionLog.add($,Q.sql,"error",z,0,j instanceof Error?j.message:String(j),W,B),j}}if(!H)await G.commit(B);return U}catch(U){if(!H)try{await G.rollback(B)}catch(Q){console.debug("Rollback after error failed:",Q instanceof Error?Q.message:Q)}throw U}};if(X)return V(X);return i(G,V)}submitQuery($,Z,W,X,G,V,B){let H=performance.now();this.queryExecutor.executeQuery($,Z,W,0,X,G,V,B).then((U)=>{this.emitMessage?.("query.completed",{queryId:X,results:U,durationMs:Math.round(performance.now()-H)})}).catch((U)=>{let Q=U?.code;this.emitMessage?.("query.completed",{queryId:X,error:U instanceof Error?U.message:String(U),errorCode:Q,durationMs:Math.round(performance.now()-H)})})}submitExplain($,Z,W,X,G,V,B){let H=performance.now();this.queryExecutor.explainQuery($,Z,W,G,V,B).then((U)=>{this.emitMessage?.("query.completed",{queryId:X,explainResult:U,durationMs:Math.round(performance.now()-H)})}).catch((U)=>{this.emitMessage?.("query.completed",{queryId:X,error:U instanceof Error?U.message:String(U),durationMs:Math.round(performance.now()-H)})})}async cancelQuery($){await this.queryExecutor.cancelQuery($)}async beginTransaction($,Z,W){await this.txManager.begin($,Z,W),this.queryExecutor.sessionLog.resetPendingCount($,Z,W)}async commitTransaction($,Z,W){await this.txManager.commit($,Z,W),this.queryExecutor.sessionLog.resetPendingCount($,Z,W)}async rollbackTransaction($,Z,W){await this.txManager.rollback($,Z,W),this.queryExecutor.sessionLog.resetPendingCount($,Z,W)}getTransactionLog($){let Z=this.queryExecutor.sessionLog.getEntries($.connectionId,$.database);if($.statusFilter)Z=Z.filter((G)=>G.status===$.statusFilter);if($.search){let G=$.search.toLowerCase();Z=Z.filter((V)=>V.sql.toLowerCase().includes(G))}let W=this.txManager.isActive($.connectionId,$.database,$.sessionId),X=W?this.queryExecutor.sessionLog.getPendingCount($.connectionId,$.database,$.sessionId):0;return{entries:Z,pendingStatementCount:X,inTransaction:W}}clearTransactionLog($,Z,W){this.queryExecutor.sessionLog.clear($,Z)}listHistory($){return this.appDb.listHistory($)}clearHistory($){this.appDb.clearHistory($)}listSavedViews($,Z,W){return this.appDb.listSavedViews($,Z,W)}createSavedView($){return this.appDb.createSavedView($)}updateSavedView($){return this.appDb.updateSavedView($)}deleteSavedView($){this.appDb.deleteSavedView($)}listSavedViewsByConnection($){return this.appDb.listSavedViewsByConnection($)}getSavedViewById($){return this.appDb.getSavedViewById($)}listBookmarks($,Z){return this.appDb.listBookmarks($,Z)}createBookmark($){return this.appDb.createBookmark($)}updateBookmark($){return this.appDb.updateBookmark($)}deleteBookmark($){this.appDb.deleteBookmark($)}async searchDatabase($){let Z=this.cm.getDriver($.connectionId,$.database);return n0(Z,{searchTerm:$.searchTerm,scope:$.scope,schemaName:$.schemaName,tableNames:$.tableNames,resultsPerTable:$.resultsPerTable??50},()=>{},()=>!1)}async exportData($){let Z=this.cm.getDriver($.connectionId,$.database);if(!$.filePath)throw Error("Export requires a file path");let W=this.emitMessage?(G)=>this.emitMessage("export.progress",{rowCount:G}):void 0;return{...await M0(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,includeHeaders:$.includeHeaders,delimiter:$.delimiter,encoding:$.encoding,utf8Bom:$.utf8Bom,batchSize:$.batchSize,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins},$.filePath,void 0,W),filePath:$.filePath}}async exportPreview($){let Z=this.cm.getDriver($.connectionId,$.database);return N0(Z,{schema:$.schema,table:$.table,format:$.format,columns:$.columns,delimiter:$.delimiter,filters:$.filters,sort:$.sort,limit:$.limit,autoJoins:$.autoJoins})}async exportPreviewRows($){let Z=this.cm.getDriver($.connectionId,$.database),{sql:W,params:X}=H$({schema:$.schema,table:$.table,format:"csv",columns:$.columns,filters:$.filters,sort:$.sort,autoJoins:$.autoJoins},Z),G=X.length+1,V=`${W} LIMIT ${Z.placeholder(G)}`,H=(await Z.execute(V,[...X,$.limit])).rows,U=H.length>0?Object.keys(H[0]):$.columns??[];return{rows:H,columns:U}}async importData($){let Z=this.cm.getDriver($.connectionId,$.database),W=this.resolveImportStream($.filePath,$.fileContent),X=this.emitMessage?(G)=>this.emitMessage("import.progress",{rowCount:G}):void 0;return Q$(Z,W,{schema:$.schema,table:$.table,format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,mappings:$.mappings,batchSize:$.batchSize},void 0,X)}async importPreview($){let Z=this.resolveImportPreviewStream($.filePath,$.fileContent),W=await E0(Z,{format:$.format,delimiter:$.delimiter,hasHeader:$.hasHeader,limit:$.limit});if($.filePath)try{let X=Bun.file($.filePath);W.fileSizeBytes=X.size}catch{}return W}resolveImportStream($,Z){if($)return Bun.file($).stream();if(Z!==void 0)return new ReadableStream({start(W){W.enqueue(new TextEncoder().encode(Z)),W.close()}});throw Error("Import requires either filePath or fileContent")}resolveImportPreviewStream($,Z){if($){let G=Bun.file($).stream().getReader(),V=65536,B=0;return new ReadableStream({async pull(H){let{done:U,value:Q}=await G.read();if(U){H.close();return}if(B+=Q.byteLength,B>=65536){H.enqueue(Q),H.close(),G.releaseLock();return}H.enqueue(Q)},cancel(){G.releaseLock()}})}if(Z!==void 0)return new ReadableStream({start(W){W.enqueue(new TextEncoder().encode(Z)),W.close()}});throw Error("Import preview requires either filePath or fileContent")}getAllSettings(){return this.appDb.getAllSettings()}setSetting($,Z){this.appDb.setSetting($,Z)}async encryptSecrets($){if(!this.encryption)throw Error("Encryption not available");return this.encryption.encrypt($)}async decryptConfig($){if(!this.encryption)throw Error("Encryption not available");return this.encryption.decrypt($)}async showOpenDialog({filters:$,multiple:Z}){if(!this.Utils)throw Error("Utils not available");let W=$&&$.length>0?$.flatMap((V)=>V.extensions.map((B)=>`*.${B}`)).join(","):"*",G=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:W,canChooseFiles:!0,canChooseDirectory:!1,allowsMultipleSelection:Z??!1})).filter((V)=>V!=="");return{paths:G,cancelled:G.length===0}}async showSaveDialog({defaultName:$}){if(!this.Utils)throw Error("Utils not available");let W=(await this.Utils.openFileDialog({startingFolder:"~/",allowedFileTypes:"*",canChooseFiles:!1,canChooseDirectory:!0,allowsMultipleSelection:!1}))[0];if(!W||W==="")return{path:null,cancelled:!0};return{path:$?`${W}/${$}`:W,cancelled:!1}}formatSql($){return s0($)}async generateSql($){let Z=this.cm.getDriver($.connectionId,$.database),W=await Z.loadSchema(),X=d0(W),G=p0(this.appDb.getAllSettings());return{sql:await i0(G,{prompt:$.prompt,schemaContext:X,dialect:Z.getDriverType()})}}saveWorkspace($){this.appDb.saveWorkspace($)}loadWorkspace(){return this.appDb.loadWorkspace()}async initializeDemo(){if(!this.demoDbSourcePath||!this.demoDbTargetPath)throw Error("Demo database paths not configured");let $=Bun.file(this.demoDbSourcePath);if(!await $.exists())throw Error('Demo database source not found. Run "bun run seed:sqlite" first.');await Bun.write(this.demoDbTargetPath,$);let Z={type:"sqlite",path:this.demoDbTargetPath},W=this.appDb.createConnection({name:"Bookstore (Demo)",config:Z});return await this.cm.connect(W.id),W}getSessionManager(){return this.sessionManager}}var $5=M(()=>{R$();l0();y$();w$();o0();e0()});function Z5($){return{"connections.list":()=>{return $.listConnections()},"connections.create":({name:Z,config:W,readOnly:X,color:G,groupName:V})=>{return $.createConnection({name:Z,config:W,readOnly:X,color:G,groupName:V})},"connections.update":({id:Z,name:W,config:X,readOnly:G,color:V,groupName:B})=>{return $.updateConnection({id:Z,name:W,config:X,readOnly:G,color:V,groupName:B})},"connections.setReadOnly":({id:Z,readOnly:W})=>{return $.setConnectionReadOnly(Z,W)},"connections.setGroup":({id:Z,groupName:W})=>{return $.setConnectionGroup(Z,W)},"connections.listGroups":()=>{return $.listConnectionGroups()},"connections.renameGroup":({oldName:Z,newName:W})=>{$.renameConnectionGroup(Z,W)},"connections.deleteGroup":({groupName:Z})=>{$.deleteConnectionGroup(Z)},"connections.delete":async({id:Z})=>{await $.deleteConnection(Z)},"connections.test":async({config:Z})=>{return $.testConnection(Z)},"connections.connect":async({connectionId:Z,password:W,config:X,encryptedSecrets:G,name:V,encryptedConfig:B})=>{await $.connect(Z,W,{config:X,encryptedSecrets:G,name:V,encryptedConfig:B})},"connections.disconnect":async({connectionId:Z})=>{await $.disconnect(Z)},"session.create":async({connectionId:Z,database:W})=>{return $.createSession(Z,W)},"session.destroy":async({sessionId:Z})=>{await $.destroySession(Z)},"session.list":({connectionId:Z})=>{return $.listSessions(Z)},"databases.list":async({connectionId:Z})=>{return $.listDatabases(Z)},"databases.listForConfig":async({config:Z})=>{return $.listDatabasesForConfig(Z)},"databases.activate":async({connectionId:Z,database:W})=>{await $.activateDatabase(Z,W)},"databases.deactivate":async({connectionId:Z,database:W})=>{await $.deactivateDatabase(Z,W)},"schema.load":async({connectionId:Z,database:W,sessionId:X})=>{return $.getDriver(Z,W).loadSchema(X)},"query.execute":async({connectionId:Z,sql:W,queryId:X,params:G,database:V,statements:B,sessionId:H,searchPath:U})=>{if(B&&B.length>0)return $.executeStatements(Z,B,V,H);return $.executeQuery(Z,W,G,X,V,H,U)},"query.submit":({connectionId:Z,sql:W,queryId:X,params:G,database:V,sessionId:B,searchPath:H})=>{return $.submitQuery(Z,W,G,X,V,B,H),{queryId:X}},"query.submitExplain":({connectionId:Z,sql:W,analyze:X,queryId:G,database:V,sessionId:B,searchPath:H})=>{return $.submitExplain(Z,W,X??!1,G,V,B,H),{queryId:G}},"query.cancel":async({queryId:Z})=>{await $.cancelQuery(Z)},"query.format":({sql:Z})=>{return{sql:$.formatSql(Z)}},"tx.begin":async({connectionId:Z,database:W,sessionId:X})=>{await $.beginTransaction(Z,W,X)},"tx.commit":async({connectionId:Z,database:W,sessionId:X})=>{await $.commitTransaction(Z,W,X)},"tx.rollback":async({connectionId:Z,database:W,sessionId:X})=>{await $.rollbackTransaction(Z,W,X)},"transaction.getLog":(Z)=>{return $.getTransactionLog(Z)},"transaction.clearLog":({connectionId:Z,database:W,sessionId:X})=>{$.clearTransactionLog(Z,W,X)},"search.searchDatabase":async(Z)=>{return $.searchDatabase(Z)},"export.exportData":async(Z)=>{return $.exportData(Z)},"export.preview":async(Z)=>{return{content:await $.exportPreview(Z)}},"export.previewRows":async(Z)=>{return $.exportPreviewRows(Z)},"import.importData":async(Z)=>{return $.importData(Z)},"import.preview":async(Z)=>{return $.importPreview(Z)},"history.list":(Z)=>{return $.listHistory(Z)},"history.clear":({connectionId:Z})=>{$.clearHistory(Z)},"views.save":({connectionId:Z,schemaName:W,tableName:X,name:G,config:V})=>{if(!G?.trim())throw Error("View name is required");if(!Z)throw Error("connectionId is required");if(!X)throw Error("tableName is required");if($.listSavedViews(Z,W,X).some((H)=>H.name===G.trim()))throw Error(`A view named "${G.trim()}" already exists for this table`);return $.createSavedView({connectionId:Z,schemaName:W,tableName:X,name:G.trim(),config:V})},"views.update":({id:Z,name:W,config:X})=>{if(!Z)throw Error("View id is required");if(!W?.trim())throw Error("View name is required");let G=$.getSavedViewById(Z);if(!G)throw Error(`Saved view not found: ${Z}`);if($.listSavedViews(G.connectionId,G.schemaName,G.tableName).some((B)=>B.id!==Z&&B.name===W.trim()))throw Error(`A view named "${W.trim()}" already exists for this table`);return $.updateSavedView({id:Z,name:W.trim(),config:X})},"views.delete":({id:Z})=>{$.deleteSavedView(Z)},"views.listByConnection":({connectionId:Z})=>{return $.listSavedViewsByConnection(Z)},"bookmarks.list":({connectionId:Z,search:W})=>{return $.listBookmarks(Z,W)},"bookmarks.create":({connectionId:Z,database:W,name:X,description:G,sql:V})=>{if(!X?.trim())throw Error("Bookmark name is required");return $.createBookmark({connectionId:Z,database:W,name:X.trim(),description:G,sql:V})},"bookmarks.update":({id:Z,name:W,description:X,sql:G})=>{if(!Z)throw Error("Bookmark id is required");if(!W?.trim())throw Error("Bookmark name is required");return $.updateBookmark({id:Z,name:W.trim(),description:X,sql:G})},"bookmarks.delete":({id:Z})=>{$.deleteBookmark(Z)},"settings.getAll":()=>{return $.getAllSettings()},"settings.set":({key:Z,value:W})=>{$.setSetting(Z,W)},"storage.encryptSecrets":async({secrets:Z})=>{if(!$.encryptSecrets)throw Error("Encryption not available");return{encryptedSecrets:await $.encryptSecrets(Z)}},"storage.decryptConfig":async({encryptedConfig:Z})=>{if(!$.decryptConfig)throw Error("Encryption not available");return{config:await $.decryptConfig(Z)}},"ai.generateSql":async(Z)=>{return $.generateSql(Z)},"workspace.save":({data:Z})=>{$.saveWorkspace(Z)},"workspace.load":()=>{return $.loadWorkspace()},"system.showOpenDialog":async(Z)=>{if(!$.showOpenDialog)return{paths:[],cancelled:!0};return $.showOpenDialog(Z)},"system.showSaveDialog":async(Z)=>{if(!$.showSaveDialog)return{path:null,cancelled:!0};return $.showSaveDialog(Z)},"demo.initialize":async()=>{if(!$.initializeDemo)throw Error("Demo initialization is not available");return $.initializeDemo()}}}function k7($){if(!$)throw Error("AppDatabase is required");return $}function W5($,Z,W,X,G){let V=k7(W),B=Z??new n($,void 0,V),H=new c$($,V,(Q,Y,j)=>{B.sessionLog.resetPendingCount(Q,Y,j)}),U=new i$($,B,V,{encryption:G?.encryption,Utils:X,emitMessage:G?.emitMessage,sessionManager:H,demoDbSourcePath:G?.demoDbSourcePath,demoDbTargetPath:G?.demoDbTargetPath});return{handlers:Z5(U),sessionManager:H,adapter:U}}var X5=M(()=>{g$();m0();$5()});class n${inner;constructor($){this.inner=$}log($,Z,W,X){let G=$.replace(/\s+/g," ").trim(),V=Z&&Z.length>0;if(X)console.debug(`[SQL ERROR] ${G}${V?` -- params: ${JSON.stringify(Z)}`:""} (${W}ms)`,X);else if(W!==void 0)console.debug(`[SQL] ${G}${V?` -- params: ${JSON.stringify(Z)}`:""} (${W}ms)`);else console.debug(`[SQL] ${G}${V?` -- params: ${JSON.stringify(Z)}`:""}`)}async execute($,Z,W){let X=performance.now();try{let G=await this.inner.execute($,Z,W);return this.log($,Z,Math.round(performance.now()-X)),G}catch(G){throw this.log($,Z,Math.round(performance.now()-X),G),G}}async*iterate($,Z,W,X,G){this.log($,Z),yield*this.inner.iterate($,Z,W,X,G)}async importBatch($,Z,W,X){let G=`INSERT INTO ${$} (${Z.join(", ")}) VALUES ... [${W.length} rows]`,V=performance.now();try{let B=await this.inner.importBatch($,Z,W,X);return this.log(G,void 0,Math.round(performance.now()-V)),B}catch(B){throw this.log(G,void 0,Math.round(performance.now()-V),B),B}}connect($){return this.inner.connect($)}disconnect(){return this.inner.disconnect()}isConnected(){return this.inner.isConnected()}reserveSession($){return this.inner.reserveSession($)}releaseSession($){return this.inner.releaseSession($)}getSessionIds(){return this.inner.getSessionIds()}cancel($){return this.inner.cancel($)}ping(){return this.inner.ping()}async loadSchema($){console.debug("[SQL] loadSchema started"+($?` (session: ${$})`:""));let Z=performance.now();try{let W=await this.inner.loadSchema($),X=Object.values(W.tables).reduce((G,V)=>G+V.length,0);return console.debug(`[SQL] loadSchema completed \u2014 ${W.schemas.length} schemas, ${X} tables (${Math.round(performance.now()-Z)}ms)`),W}catch(W){throw console.debug(`[SQL ERROR] loadSchema failed (${Math.round(performance.now()-Z)}ms)`,W),W}}beginTransaction($){return this.inner.beginTransaction($)}commit($){return this.inner.commit($)}rollback($){return this.inner.rollback($)}inTransaction($){return this.inner.inTransaction($)}isTxAborted($){return this.inner.isTxAborted($)}isIterating($){return this.inner.isIterating($)}getDriverType(){return this.inner.getDriverType()}quoteIdentifier($){return this.inner.quoteIdentifier($)}qualifyTable($,Z){return this.inner.qualifyTable($,Z)}emptyInsertSql($){return this.inner.emptyInsertSql($)}placeholder($){return this.inner.placeholder($)}}var{SQL:C7}=globalThis.Bun;class e{url;resetFn;systemConn=null;idleConn=null;idleTimer=null;connections=new Set;constructor($,Z){this.url=$;this.resetFn=Z}async connect(){this.systemConn=this.createSql(),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1")}getSystemConnection(){if(!this.systemConn)throw Error("ConnectionPool is not connected");return this.systemConn}createConnection(){let $=this.createSql();return this.connections.add($),$}acquireConnection(){if(this.idleConn){let $=this.idleConn;return this.idleConn=null,this.clearIdleTimer(),$}return this.createConnection()}async releaseConnection($){if(!this.idleConn){if(this.resetFn)try{await this.resetFn($)}catch{await this.destroyConnection($);return}this.idleConn=$,this.scheduleIdleTimeout()}else await this.destroyConnection($)}async destroyConnection($){if(this.idleConn===$)this.idleConn=null,this.clearIdleTimer();this.connections.delete($);try{await $.close()}catch{}}async reconnectSystemConnection(){if(this.systemConn){this.connections.delete(this.systemConn);try{await this.systemConn.close()}catch{}}this.systemConn=this.createSql(),this.connections.add(this.systemConn),await this.systemConn.unsafe("SELECT 1")}async disconnectAll(){this.clearIdleTimer(),this.idleConn=null;let $=[...this.connections];this.connections.clear(),this.systemConn=null,await Promise.allSettled($.map((Z)=>Z.close()))}createSql(){return new C7({url:this.url,max:1})}scheduleIdleTimeout(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{if(this.idleConn)this.destroyConnection(this.idleConn)},E7)}clearIdleTimer(){if(this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null}}var E7=30000;var o$=()=>{};function r$($){let Z=$ instanceof Error?$.message:String($),W=$?.errno??$?.code;if(/ECONNREFUSED|connection refused/i.test(Z))return new E("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new E("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new E("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections|connection limit/i.test(Z))return new E("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new E("SSL_ERROR",Z,{cause:$});if(W?.startsWith("28")||/authentication failed|password authentication/i.test(Z))return new Y$(Z,{cause:$});if(W==="3D000"||/database .* does not exist/i.test(Z))return new E("DATABASE_NOT_FOUND",Z,{cause:$});if(W==="23505"||/violates unique constraint|duplicate key/i.test(Z))return new D("CONSTRAINT_UNIQUE",Z,{cause:$});if(W==="23503"||/violates foreign key constraint/i.test(Z))return new D("CONSTRAINT_FK",Z,{cause:$});if(W==="23514"||/violates check constraint/i.test(Z))return new D("CONSTRAINT_CHECK",Z,{cause:$});if(W==="23502"||/violates not-null constraint/i.test(Z))return new D("CONSTRAINT_NOT_NULL",Z,{cause:$});if(W==="42601"||/syntax error/i.test(Z))return new k("QUERY_SYNTAX",Z,{cause:$});if(W==="42P01"||/relation .* does not exist/i.test(Z))return new k("TABLE_NOT_FOUND",Z,{cause:$});if(W==="42703"||/column .* does not exist/i.test(Z))return new k("COLUMN_NOT_FOUND",Z,{cause:$});if(W==="42501"||/permission denied/i.test(Z))return new N("PERMISSION_DENIED",Z,{cause:$});if(W==="40001")return new k("SERIALIZATION_FAILURE",Z,{cause:$});if(W==="40P01")return new k("DEADLOCK_DETECTED",Z,{cause:$});if(W==="25P02")return new k("TRANSACTION_ABORTED",Z,{cause:$});if(W?.startsWith("42")||W?.startsWith("22"))return new k("QUERY_EXECUTION",Z,{cause:$});return new N("UNKNOWN",Z,{cause:$})}function a$($){let Z=$ instanceof Error?$.message:String($);if(/unable to open database|cannot open/i.test(Z))return new E("CONNECTION_REFUSED",Z,{cause:$});if(/UNIQUE constraint failed/i.test(Z))return new D("CONSTRAINT_UNIQUE",Z,{cause:$});if(/FOREIGN KEY constraint failed/i.test(Z))return new D("CONSTRAINT_FK",Z,{cause:$});if(/CHECK constraint failed/i.test(Z))return new D("CONSTRAINT_CHECK",Z,{cause:$});if(/NOT NULL constraint failed/i.test(Z))return new D("CONSTRAINT_NOT_NULL",Z,{cause:$});if(/no such table/i.test(Z))return new k("TABLE_NOT_FOUND",Z,{cause:$});if(/no such column/i.test(Z))return new k("COLUMN_NOT_FOUND",Z,{cause:$});if(/syntax error|near /i.test(Z))return new k("QUERY_SYNTAX",Z,{cause:$});if(/authorization denied|not authorized/i.test(Z))return new N("PERMISSION_DENIED",Z,{cause:$});return new N("UNKNOWN",Z,{cause:$})}function s$($){let Z=$ instanceof Error?$.message:String($),W=$?.errno;if(/ECONNREFUSED|connection refused/i.test(Z)||W===2003)return new E("CONNECTION_REFUSED",Z,{cause:$});if(/timeout|timed out/i.test(Z))return new E("CONNECTION_TIMEOUT",Z,{cause:$});if(/ENOTFOUND|getaddrinfo/i.test(Z))return new E("HOST_NOT_FOUND",Z,{cause:$});if(/too many connections/i.test(Z)||W===1040)return new E("CONNECTION_LIMIT",Z,{cause:$});if(/SSL|TLS|certificate/i.test(Z))return new E("SSL_ERROR",Z,{cause:$});if(W===1045||/access denied/i.test(Z))return new Y$(Z,{cause:$});if(W===1049||/unknown database/i.test(Z))return new E("DATABASE_NOT_FOUND",Z,{cause:$});if(W===1062||/duplicate entry/i.test(Z))return new D("CONSTRAINT_UNIQUE",Z,{cause:$});if(W===1451||W===1452||/foreign key constraint/i.test(Z)||/cannot delete or update a parent row/i.test(Z)||/cannot add or update a child row/i.test(Z))return new D("CONSTRAINT_FK",Z,{cause:$});if(W===3819||/check constraint/i.test(Z))return new D("CONSTRAINT_CHECK",Z,{cause:$});if(W===1048||/cannot be null/i.test(Z))return new D("CONSTRAINT_NOT_NULL",Z,{cause:$});if(W===1213||/deadlock found/i.test(Z))return new k("DEADLOCK_DETECTED",Z,{cause:$});if(W===1205||/lock wait timeout exceeded/i.test(Z))return new k("SERIALIZATION_FAILURE",Z,{cause:$});if(W===1064||/syntax error|you have an error in your sql syntax/i.test(Z))return new k("QUERY_SYNTAX",Z,{cause:$});if(W===1146||/table .* doesn't exist/i.test(Z))return new k("TABLE_NOT_FOUND",Z,{cause:$});if(W===1054||/unknown column/i.test(Z))return new k("COLUMN_NOT_FOUND",Z,{cause:$});if(W===1142||W===1143||/command denied|access denied/i.test(Z))return new N("PERMISSION_DENIED",Z,{cause:$});return new N("UNKNOWN",Z,{cause:$})}var x$=M(()=>{y()});function p($){let Z=$;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;return 0}var z4,K4,R4,O4,A4,L4;var G5=M(()=>{q();z4=new Set(["integer","serial","float","numeric"]),K4=new Set(["boolean"]),R4=new Set(["timestamp","date"]),O4=new Set(["text","varchar","char"]),A4=new Set(["json"]),L4=new Set(["array"])});var V5=M(()=>{G5();q()});var B5=M(()=>{B$();V5()});function _$($,Z){let W=b$(Z).trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(W)){if($.txActive=!0,"txAborted"in $)$.txAborted=!1}else if(/^(COMMIT|END)\b/.test(W)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}else if(/^ROLLBACK\b/.test(W)&&!/^ROLLBACK\s+TO\b/.test(W)){if($.txActive=!1,"txAborted"in $)$.txAborted=!1}}function f($){let Z=$?.code;if(typeof Z==="string"&&/^(ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|ENOTCONN)$/.test(Z))return!0;let W=$ instanceof Error?$.message:String($);return/ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|connection (terminated|ended|closed|lost|reset)|socket.*(closed|hang up|end)|write after end|broken pipe|network/i.test(W)}async function l($,Z){if(Z?.rollback)try{await $.unsafe("ROLLBACK")}catch{}try{await $.close()}catch{}}var e$=M(()=>{B5()});function D7($){switch($.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 $0{pool=null;connected=!1;sessions=new Map;defaultSessionPending=!1;poolActiveQueries=new Map;async connect($){if($.type!=="mysql")throw Error("MysqlDriver requires a mysql connection config");let Z=`mysql://${encodeURIComponent($.user)}:${encodeURIComponent($.password)}@${$.host}:${$.port}/${encodeURIComponent($.database)}`;this.pool=new e(Z,(W)=>W.unsafe("RESET CONNECTION"));try{await this.pool.connect()}catch(W){throw this.pool=null,W instanceof N?W:s$(W)}this.connected=!0}async disconnect(){this.connected=!1;for(let[,$]of this.sessions)await l($.conn,{rollback:$.txActive});if(this.sessions.clear(),this.pool)await this.pool.disconnectAll(),this.pool=null}isConnected(){return this.connected}async reserveSession($){if(this.ensureConnected(),this.sessions.has($))throw Error(`Session "${$}" already exists`);let Z=this.pool.createConnection();this.sessions.set($,{conn:Z,txActive:!1,iterating:!1,activeQueries:new Set})}async releaseSession($){let Z=this.sessions.get($);if(!Z)return;this.sessions.delete($),await l(Z.conn,{rollback:!0})}getSessionIds(){return[...this.sessions.keys()].filter(($)=>$!==T)}async execute($,Z,W,X){this.ensureConnected();let G=this.resolveSession(W),V=G?G.conn:this.pool.getSystemConnection(),B=performance.now(),H=V.unsafe($,Z??[]),U=G?void 0:X??Symbol();if(G)G.activeQueries.add(H);else this.poolActiveQueries.set(U,H);try{let Q=await H,Y=Math.round(performance.now()-B),j=[...Q];if(G)_$(G,$);return{columns:j.length>0?Object.keys(j[0]).map((R)=>({name:R,dataType:"unknown"})):[],rows:j,rowCount:j.length,affectedRows:p(Q),durationMs:Y}}catch(Q){throw Q instanceof N?Q:s$(Q)}finally{if(G)G.activeQueries.delete(H);else this.poolActiveQueries.delete(U)}}async cancel($,Z){if($){let W=this.sessions.get($);if(W){for(let X of W.activeQueries)X.cancel();W.activeQueries.clear()}}else if(Z){let W=this.poolActiveQueries.get(Z);if(W)W.cancel(),this.poolActiveQueries.delete(Z)}else{for(let W of this.poolActiveQueries.values())W.cancel();this.poolActiveQueries.clear()}}async loadSchema($){this.ensureConnected();let Z=this.resolveSession($),W=Z?Z.conn:this.pool.getSystemConnection(),X=await this.getSchemas(W),G=X.map((J)=>J.name),V={};for(let J of X)V[J.name]=await this.getTables(W,J.name);let[B,H,U,Q]=await Promise.all([W.unsafe(`SELECT
|
|
145
145
|
c.TABLE_SCHEMA AS table_schema,
|
|
146
146
|
c.TABLE_NAME AS table_name,
|
|
147
147
|
c.COLUMN_NAME AS column_name,
|
|
@@ -329,7 +329,7 @@ Request: ${Z.prompt}`}]})});if(!G.ok){let B=await G.text().catch(()=>"");if(G.st
|
|
|
329
329
|
WHERE schemaname = $1
|
|
330
330
|
ORDER BY matviewname`,[Z])].map((X)=>({schema:Z,name:X.matviewname,type:"materialized-view"}))}async ping(){this.ensureConnected();try{await this.pool.getSystemConnection().unsafe("SELECT 1")}catch{await this.pool.reconnectSystemConnection()}}async beginTransaction($){if(this.ensureConnected(),$){let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);await Z.conn.unsafe("BEGIN"),Z.txActive=!0,Z.txAborted=!1}else{if(this.sessions.has(S)||this.defaultSessionPending)throw Error("A default transaction is already active. Commit or rollback before starting a new one.");this.defaultSessionPending=!0;try{let Z=this.pool.acquireConnection();try{await Z.unsafe("BEGIN")}catch(W){throw await this.pool.releaseConnection(Z),W}this.sessions.set(S,{conn:Z,txActive:!0,txAborted:!1,iterating:!1,activeQueries:new Set})}finally{this.defaultSessionPending=!1}}}async commit($){this.ensureConnected();let Z=$??S,W=this.sessions.get(Z);if(!W)throw Error("No active transaction");if(W.iterating)throw Error("Cannot commit during active iteration");try{await W.conn.unsafe("COMMIT"),W.txActive=!1,W.txAborted=!1}catch(X){if(f(X))throw W.txActive=!1,W.txAborted=!1,new N("COMMIT_UNCERTAIN","Connection lost during COMMIT \u2014 the transaction may have been committed. Verify your data before retrying.",{cause:X});try{await W.conn.unsafe("ROLLBACK"),W.txActive=!1,W.txAborted=!1}catch{}throw X}finally{if(Z===S)this.sessions.delete(S),await this.pool.releaseConnection(W.conn)}}async rollback($){this.ensureConnected();let Z=$??S,W=this.sessions.get(Z);if(!W)throw Error("No active transaction");if(W.iterating)throw Error("Cannot rollback during active iteration");try{await W.conn.unsafe("ROLLBACK"),W.txActive=!1,W.txAborted=!1}catch(X){if(f(X))W.txActive=!1,W.txAborted=!1;throw X}finally{if(Z===S)this.sessions.delete(S),await this.pool.releaseConnection(W.conn)}}inTransaction($){let Z=$??S;return this.sessions.get(Z)?.txActive??!1}isTxAborted($){let Z=$??S;return this.sessions.get(Z)?.txAborted??!1}isIterating($){let Z=$??S;return this.sessions.get(Z)?.iterating??!1}getDriverType(){return"postgresql"}quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}qualifyTable($,Z){return`${this.quoteIdentifier($)}.${this.quoteIdentifier(Z)}`}emptyInsertSql($){return`INSERT INTO ${$} DEFAULT VALUES`}placeholder($){return`$${$}`}async*iterate($,Z,W=1000,X,G){this.ensureConnected();let V=`dotaz_iter_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=G?this.sessions.get(G):void 0;if(G&&!B)throw Error(`Session "${G}" not found`);if(B?.txActive)throw Error("Cannot iterate on a session with an active transaction");let H=B?B.conn:this.pool.acquireConnection(),U=!B;if(B)B.txActive=!0,B.iterating=!0;let Q=!1;try{await H.unsafe("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"),await H.unsafe(`DECLARE ${V} NO SCROLL CURSOR FOR ${$}`,Z??[]);try{while(!0){if(X?.aborted)throw new DOMException("Aborted","AbortError");let j=[...await H.unsafe(`FETCH FORWARD ${W} FROM ${V}`)];if(j.length===0)break;if(yield j,j.length<W)break}}finally{try{await H.unsafe(`CLOSE ${V}`)}catch{}}await H.unsafe("COMMIT")}catch(Y){Q=!0;try{await H.unsafe("ROLLBACK")}catch{}throw Y}finally{if(B)B.txActive=!1,B.iterating=!1;if(U)await this.pool.releaseConnection(H);else if(B&&!Q)try{await H.unsafe("ROLLBACK")}catch{}}}async importBatch($,Z,W,X){if(this.ensureConnected(),W.length===0)return 0;let G=Z.map((Q)=>this.quoteIdentifier(Q)).join(", "),V=[],B=[];for(let Q=0;Q<W.length;Q++){let Y=[];for(let j=0;j<Z.length;j++)V.push(W[Q][Z[j]]),Y.push(this.placeholder(V.length));B.push(`(${Y.join(", ")})`)}let H=`INSERT INTO ${$} (${G}) VALUES ${B.join(", ")}`;return(await this.execute(H,V,X)).affectedRows??W.length}ensureConnected(){if(!this.pool||!this.connected)throw Error("Not connected. Call connect() first.")}resolveSession($){if(!$)return;let Z=this.sessions.get($);if(!Z)throw Error(`Session "${$}" not found`);return Z}mapDataType($,Z){if($==="ARRAY")return"array";if($==="USER-DEFINED"){let W=Z.toLowerCase();if(W==="json"||W==="jsonb")return"json";return"enum"}return S7($)}}var S="__default__";var U5=M(()=>{q();y();o$();x$();e$()});var{SQL:Q5}=globalThis.Bun;function T7($){let Z=$.toUpperCase();if(Z==="INTEGER"||Z==="INT"||Z==="BIGINT"||Z==="SMALLINT"||Z==="TINYINT"||Z==="MEDIUMINT")return"integer";if(Z==="REAL"||Z==="FLOAT"||Z==="DOUBLE")return"float";if(Z==="NUMERIC"||Z==="DECIMAL")return"numeric";if(Z==="BOOLEAN"||Z==="BOOL")return"boolean";if(Z==="TEXT")return"text";if(Z.includes("VARCHAR")||Z.includes("VARYING"))return"varchar";if(Z.includes("CHAR")&&!Z.includes("VARCHAR"))return"char";if(Z==="DATE")return"date";if(Z==="TIME")return"time";if(Z==="DATETIME"||Z.includes("TIMESTAMP"))return"timestamp";if(Z==="JSON"||Z==="JSONB")return"json";if(Z==="BLOB"||Z==="BINARY"||Z.includes("VARBINARY"))return"binary";return"unknown"}class W0{db=null;dbPath=null;connected=!1;txActive=!1;txOwnerSession=null;sessionIds=new Set;iterating=!1;iterateDb=null;async connect($){if($.type!=="sqlite")throw Error("SqliteDriver requires a sqlite connection config");try{this.db=new Q5(`sqlite:${$.path}`),this.dbPath=$.path,await this.db.unsafe("PRAGMA journal_mode = WAL"),await this.db.unsafe("PRAGMA foreign_keys = ON")}catch(Z){throw this.db=null,this.dbPath=null,Z instanceof N?Z:a$(Z)}this.connected=!0}async disconnect(){if(this.connected=!1,this.iterateDb){try{await this.iterateDb.close()}catch{}this.iterateDb=null}if(this.db)await this.db.close(),this.db=null,this.dbPath=null,this.txActive=!1,this.txOwnerSession=null,this.sessionIds.clear()}isConnected(){return this.connected}async reserveSession($){this.sessionIds.add($)}async releaseSession($){if(this.txActive&&this.txOwnerSession===$){try{await this.db.unsafe("ROLLBACK")}catch{}this.txActive=!1,this.txOwnerSession=null}this.sessionIds.delete($)}getSessionIds(){return[...this.sessionIds]}async execute($,Z,W){this.ensureConnected(),this.ensureSessionCanExecute(W);let X=performance.now();try{let G=await this.db.unsafe($,Z??[]),V=Math.round(performance.now()-X),B=[...G],H=$.trim().toUpperCase();if(/^(BEGIN|START\s+TRANSACTION)\b/.test(H))this.txActive=!0,this.txOwnerSession=W??null;else if(/^(COMMIT|END)\b/.test(H))this.txActive=!1,this.txOwnerSession=null;else if(/^ROLLBACK\b/.test(H)&&!/^ROLLBACK\s+TO\b/.test(H))this.txActive=!1,this.txOwnerSession=null;return{columns:B.length>0?Object.keys(B[0]).map((Q)=>({name:Q,dataType:"unknown"})):[],rows:B,rowCount:B.length,affectedRows:p(G),durationMs:V}}catch(G){throw G instanceof N?G:a$(G)}}async cancel($,Z){}async loadSchema($){this.ensureConnected();let Z=await this.getSchemas(),W=Z[0].name,X=await this.getTables(W),G={[W]:X},V={},B={},H={},U={},Q=new Map;for(let Y of X){let j=`${W}.${Y.name}`;V[j]=await this.getColumns(W,Y.name),B[j]=await this.getIndexes(W,Y.name);let z=await this.getForeignKeys(W,Y.name);H[j]=z;for(let R of z){let J=`${R.referencedSchema}.${R.referencedTable}`;if(!Q.has(J))Q.set(J,[]);Q.get(J).push({constraintName:R.name,referencingSchema:W,referencingTable:Y.name,referencingColumns:R.columns,referencedColumns:R.referencedColumns})}}for(let Y of X){let j=`${W}.${Y.name}`;U[j]=Q.get(j)??[]}return{schemas:Z,tables:G,columns:V,indexes:B,foreignKeys:H,referencingForeignKeys:U}}async getSchemas(){return[{name:"main"}]}async getTables($){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((W)=>({schema:$,name:W.name,type:W.type}))}async getColumns($,Z){this.ensureConnected();let W=[...await this.db.unsafe(`PRAGMA table_info(${this.quoteIdentifier(Z)})`)],X=W.filter((G)=>G.pk>0).length;return W.map((G)=>({name:G.name,dataType:T7(G.type||"BLOB"),nullable:G.notnull===0&&G.pk===0,defaultValue:G.dflt_value,isPrimaryKey:G.pk>0,isAutoIncrement:G.pk>0&&X===1&&G.type?.toUpperCase()==="INTEGER"}))}async getIndexes($,Z){this.ensureConnected();let W=[...await this.db.unsafe(`PRAGMA index_list(${this.quoteIdentifier(Z)})`)],X=[];for(let G of W){let V=[...await this.db.unsafe(`PRAGMA index_info(${this.quoteIdentifier(G.name)})`)];X.push({name:G.name,columns:V.map((B)=>B.name),isUnique:G.unique===1,isPrimary:G.origin==="pk"})}return X}async getForeignKeys($,Z){this.ensureConnected();let W=[...await this.db.unsafe(`PRAGMA foreign_key_list(${this.quoteIdentifier(Z)})`)],X=new Map;for(let G of W){let V=X.get(G.id);if(V)V.columns.push(G.from),V.referencedColumns.push(G.to);else X.set(G.id,{name:`fk_${Z}_${G.id}`,columns:[G.from],referencedSchema:"main",referencedTable:G.table,referencedColumns:[G.to],onUpdate:G.on_update,onDelete:G.on_delete})}return Array.from(X.values())}async ping(){this.ensureConnected(),await this.db.unsafe("SELECT 1")}async*iterate($,Z,W=1000,X,G){this.ensureConnected();let V=this.dbPath===":memory:",B=V?this.db:this.getIterateDb();if(V){if(this.ensureSessionCanExecute(G),this.txActive)throw Error("Cannot iterate with an active transaction");this.txActive=!0,this.txOwnerSession=G??null,this.iterating=!0}await B.unsafe("BEGIN");let H=!1;try{let U=0;while(!0){if(X?.aborted)throw new DOMException("Aborted","AbortError");let Q=`${$} LIMIT ? OFFSET ?`,j=[...await B.unsafe(Q,[...Z??[],W,U])];if(j.length===0)break;if(yield j,j.length<W)break;U+=W}await B.unsafe("COMMIT"),H=!0}catch(U){try{await B.unsafe("ROLLBACK")}catch{}throw U}finally{if(!H)try{await B.unsafe("ROLLBACK")}catch{}if(V)this.iterating=!1,this.txActive=!1,this.txOwnerSession=null}}getIterateDb(){if(!this.iterateDb)this.iterateDb=new Q5(`sqlite:${this.dbPath}`);return this.iterateDb}async importBatch($,Z,W,X){if(this.ensureConnected(),W.length===0)return 0;let G=Z.map((Q)=>this.quoteIdentifier(Q)).join(", "),V=[],B=[];for(let Q=0;Q<W.length;Q++){let Y=[];for(let j=0;j<Z.length;j++)V.push(W[Q][Z[j]]),Y.push(this.placeholder(V.length));B.push(`(${Y.join(", ")})`)}let H=`INSERT INTO ${$} (${G}) VALUES ${B.join(", ")}`;return(await this.execute(H,V,X)).affectedRows??W.length}async beginTransaction($){if(this.ensureConnected(),this.txActive)throw Error($&&this.txOwnerSession!==$?`Another session ("${this.txOwnerSession}") already has an active transaction`:"A transaction is already active");await this.db.unsafe("BEGIN"),this.txActive=!0,this.txOwnerSession=$??null}async commit($){if(this.ensureConnected(),this.ensureSessionOwnsTx($),this.iterating)throw Error("Cannot commit during active iteration");await this.db.unsafe("COMMIT"),this.txActive=!1,this.txOwnerSession=null}async rollback($){if(this.ensureConnected(),this.ensureSessionOwnsTx($),this.iterating)throw Error("Cannot rollback during active iteration");try{await this.db.unsafe("ROLLBACK")}finally{this.txActive=!1,this.txOwnerSession=null}}inTransaction($){if($!==void 0)return this.txActive&&this.txOwnerSession===$;return this.txActive&&this.txOwnerSession===null}isTxAborted($){return!1}isIterating($){return this.iterating}getDriverType(){return"sqlite"}quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}qualifyTable($,Z){if($==="main")return this.quoteIdentifier(Z);return`${this.quoteIdentifier($)}.${this.quoteIdentifier(Z)}`}emptyInsertSql($){return`INSERT INTO ${$} DEFAULT VALUES`}placeholder($){return`$${$}`}ensureSessionCanExecute($){if(!this.txActive)return;if(this.iterating)throw Error("Cannot execute: iteration is in progress on the shared connection");if(this.txOwnerSession===null){if($!==void 0)throw Error("Cannot execute: a sessionless transaction is active. SQLite uses a single connection shared by all sessions.");return}if($===void 0||$!==this.txOwnerSession)throw Error(`Cannot execute: session "${this.txOwnerSession}" has an active transaction. SQLite uses a single connection shared by all sessions.`)}ensureSessionOwnsTx($){if(!this.txActive)throw Error("No active transaction");if(!($===void 0?this.txOwnerSession===null:this.txOwnerSession===$))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.")}}var Y5=M(()=>{q();y();x$()});import{chmodSync as q7,unlinkSync as y7,writeFileSync as h7}from"fs";import{tmpdir as w7}from"os";import{join as b7}from"path";async function f7(){return new Promise(($,Z)=>{let W=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){},open(){},close(){},error(){}}}),X=W.port;if(W.stop(!0),X>0)$(X);else Z(Error("Could not find a free port"))})}async function u7($,Z,W){let X=Date.now()+Z;while(Date.now()<X){if(W&&W.exitCode!==null)return;try{(await Bun.connect({hostname:"127.0.0.1",port:$,socket:{data(){},open(V){V.end()},close(){},error(){}}})).end();return}catch{await Bun.sleep(g7)}}throw Error(`SSH tunnel port ${$} did not become available within ${Z/1000}s`)}async function F$($,Z,W){let X=$.localPort||await f7(),G=null,V=null;try{let B=["ssh","-N","-L",`${X}:${Z}:${W}`,"-p",String($.port||22),"-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30","-o","ExitOnForwardFailure=yes"],H={...process.env};if($.authMethod==="key"&&$.keyPath)B.push("-i",$.keyPath),B.push("-o","BatchMode=yes");else if($.password)G=b7(w7(),`dotaz-askpass-${process.pid}-${Date.now()}`),h7(G,`#!/bin/sh
|
|
331
331
|
echo '${$.password.replace(/'/g,"'\\''")}'`),q7(G,448),H.SSH_ASKPASS=G,H.SSH_ASKPASS_REQUIRE="force",H.DISPLAY=H.DISPLAY||":0";if(B.push(`${$.username}@${$.host}`),V=Bun.spawn(B,{stdin:"pipe",stdout:"ignore",stderr:"pipe",env:H}),V.stdin&&typeof V.stdin!=="number")V.stdin.end();let U=V.stderr&&typeof V.stderr!=="number"?V.stderr:null,Q=u7(X,v7,V),Y=V.exited.then(async(z)=>{if(z!==0){let R=await I7(U),J=m7(R)||`SSH process exited with code ${z}`;throw Error(J)}});return await Promise.race([Q,Y]),{localPort:X,close:async()=>{if(V)V.kill(),V=null;j5(G)}}}catch(B){if(V)V.kill();if(j5(G),B instanceof Error)throw p7(B);throw Error(`SSH tunnel error: ${String(B)}`)}}function j5($){if($)try{y7($)}catch{}}async function I7($){if(!$)return"";try{let Z=$.getReader(),W=[];while(!0){let{done:X,value:G}=await Z.read();if(X)break;W.push(G)}return Buffer.concat(W).toString("utf-8")}catch{return""}}function m7($){if(!$.trim())return null;let Z=$.trim().split(`
|
|
332
|
-
`);for(let W of Z){let X=W.toLowerCase();if(X.includes("permission denied")||X.includes("authentication"))return`SSH authentication failed: ${W.trim()}`;if(X.includes("connection refused"))return`SSH host unreachable: ${W.trim()}`;if(X.includes("timed out")||X.includes("timeout"))return`SSH connection timed out: ${W.trim()}`;if(X.includes("no such file")||X.includes("no such identity"))return`SSH key file not found: ${W.trim()}`;if(X.includes("could not resolve"))return`SSH host unreachable: ${W.trim()}`}return Z[Z.length-1]?.trim()||null}function p7($){let Z=$.message.toLowerCase();if(Z.includes("authentication")||Z.includes("permission denied"))return Error(`SSH authentication failed: ${$.message}`);if(Z.includes("econnrefused")||Z.includes("connection refused")||Z.includes("unreachable"))return Error(`SSH host unreachable: ${$.message}`);if(Z.includes("timeout")||Z.includes("timed out"))return Error(`SSH connection timed out: ${$.message}`);return Error(`SSH tunnel error: ${$.message}`)}var v7=15000,g7=100;var J5=()=>{};class X0{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($,Z){this.appDb=$,this.opts={...d7,...Z}}async connect($,Z){let W=this.appDb.getConnectionById($);if(!W)throw Error(`Connection not found: ${$}`);this.cancelAutoReconnect($);let X=(this.connectAttempt.get($)??0)+1;if(this.connectAttempt.set($,X),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),await this.setConnectionState($,"connecting");try{let G=Z?{...W.config,...Z}:W.config;if(Z$(G),w(G))this.passwords.set($,G.password);G=await this.setupSshTunnel($,G);let V=u(G),B=$$(G);if(await B.connect(G),this.connectAttempt.get($)!==X){await B.disconnect().catch(()=>{});return}let H=new Map;if(H.set(V,B),this.drivers.set($,H),h[G.type].supportsMultiDatabase&&"activeDatabases"in G&&G.activeDatabases){let U=G,Q=(U.activeDatabases??[]).filter((Y)=>Y!==U.database).map((Y)=>this.connectDatabase($,U,Y));await Promise.allSettled(Q)}await this.setConnectionState($,"connected"),this.startHealthCheck($)}catch(G){if(this.connectAttempt.get($)!==X)return;await this.closeTunnel($);let V=G instanceof Error?G.message:"Unknown connection error",B=G instanceof N?G.code:void 0;throw await this.setConnectionState($,"error",V,B),G}}async disconnect($){this.connectAttempt.set($,(this.connectAttempt.get($)??0)+1),this.cancelAutoReconnect($),this.stopHealthCheck($),await this.gracefulDisconnect($),await this.closeTunnel($),this.passwords.delete($),await this.setConnectionState($,"disconnected")}async reconnect($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.gracefulDisconnect($);await this.connect($)}getDriver($,Z){let W=this.drivers.get($);if(!W)throw Error(`No active connection for id: ${$}`);let X=Z??this.getDefaultDatabaseName($),G=W.get(X);if(!G)throw Error(`No active driver for database "${X}" on connection ${$}`);return G}getConnectionState($){return this.states.get($)?.state??"disconnected"}async listDatabases($){let Z=this.appDb.getConnectionById($);if(!Z||!h[Z.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let W=u(Z.config),X=this.getDriver($,W),G=Z.config.type==="postgresql"?K5:z5,V=await X.execute(G),B=this.drivers.get($),H=B?[...B.keys()]:[W];return V.rows.map((U)=>({name:U.name,isDefault:U.name===W,isActive:H.includes(U.name)}))}async activateDatabase($,Z){let W=this.appDb.getConnectionById($);if(!W||!h[W.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let X=W.config,G=this.drivers.get($);if(!G)throw Error(`No active connection for id: ${$}`);if(G.has(Z))return;let V=this.passwords.get($)??X.password,B={...X,database:Z,password:V};await this.connectDatabase($,B,Z);let H=[...new Set([...X.activeDatabases??[],Z])];this.appDb.updateConnection({id:$,name:W.name,config:{...X,activeDatabases:H}})}async deactivateDatabase($,Z){let W=this.appDb.getConnectionById($);if(!W||!h[W.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let X=W.config;if(Z===u(X))throw Error("Cannot deactivate the default database");let G=this.drivers.get($);if(G){let B=G.get(Z);if(B)try{await B.disconnect()}finally{G.delete(Z)}}let V=(X.activeDatabases??[]).filter((B)=>B!==Z);this.appDb.updateConnection({id:$,name:W.name,config:{...X,activeDatabases:V.length>0?V:void 0}})}listConnections(){return this.appDb.listConnections().map((Z)=>({...Z,state:this.getConnectionState(Z.id),error:this.states.get(Z.id)?.error}))}createConnection($,Z=!1){return Z$($.config,Z),this.appDb.createConnection($)}updateConnection($){return Z$($.config),{...this.appDb.updateConnection($),state:this.getConnectionState($.id),error:this.states.get($.id)?.error}}setConnectionReadOnly($,Z){return{...this.appDb.setConnectionReadOnly($,Z),state:this.getConnectionState($),error:this.states.get($)?.error}}async deleteConnection($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),this.passwords.delete($),this.states.delete($),this.appDb.deleteConnection($)}async testConnection($){Z$($);let Z=null,W=$;try{if($.type==="postgresql"&&$.sshTunnel?.enabled)Z=await F$($.sshTunnel,$.host,$.port),W={...$,host:"127.0.0.1",port:Z.localPort};let X=$$(W);return await X.connect(W),await X.disconnect(),{success:!0}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Unknown connection error"}}finally{if(Z)await Z.close()}}async listDatabasesForConfig($){if($.type!=="postgresql"&&$.type!=="mysql")throw Error(`Listing databases is not supported for connection type: ${$.type}`);let Z=$.type==="postgresql"?"postgres":"information_schema",W=$.database?$:{...$,database:Z};Z$(W);let X=null;try{if(W.type==="postgresql"&&W.sshTunnel?.enabled)X=await F$(W.sshTunnel,W.host,W.port),W={...W,host:"127.0.0.1",port:X.localPort};let G=$$(W);try{await G.connect(W);let V=W.type==="postgresql"?K5:z5;return(await G.execute(V)).rows.map((H)=>H.name)}finally{await G.disconnect().catch(()=>{})}}finally{if(X)await X.close().catch(()=>{})}}onStatusChanged($){return this.listeners.push($),()=>{let Z=this.listeners.indexOf($);if(Z>=0)this.listeners.splice(Z,1)}}onSessionDead($){return this.sessionDeadListeners.push($),()=>{let Z=this.sessionDeadListeners.indexOf($);if(Z>=0)this.sessionDeadListeners.splice(Z,1)}}async disconnectAll(){for(let Z of[...this.reconnectStates.keys()])this.cancelAutoReconnect(Z);for(let Z of[...this.healthTimers.keys()])this.stopHealthCheck(Z);let $=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let Z of $)await this.disconnect(Z)}startHealthCheck($){this.stopHealthCheck($);let Z=setInterval(()=>{this.performHealthCheck($)},this.opts.healthCheckIntervalMs);this.healthTimers.set($,Z)}stopHealthCheck($){let Z=this.healthTimers.get($);if(Z)clearInterval(Z),this.healthTimers.delete($)}async performHealthCheck($){if(this.healthCheckRunning.has($))return;this.healthCheckRunning.add($);try{let Z=this.drivers.get($);if(!Z)return;for(let W of Z.values()){try{await Promise.race([W.ping(),new Promise((X,G)=>setTimeout(()=>G(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let X=!1;for(let G of Z.values()){if(G.inTransaction()){X=!0;break}for(let V of G.getSessionIds())if(G.inTransaction(V)){X=!0;break}if(X)break}this.stopHealthCheck($);try{await this.disconnectAllDrivers($)}catch{}await this.setConnectionState($,"disconnected","Connection lost"),this.startAutoReconnect($,X);return}for(let X of W.getSessionIds())try{await W.execute("SELECT 1",void 0,X)}catch{try{await W.releaseSession(X)}catch{}for(let G of this.sessionDeadListeners)try{await G({connectionId:$,sessionId:X})}catch{}}}}finally{this.healthCheckRunning.delete($)}}startAutoReconnect($,Z=!1){this.cancelAutoReconnect($);let W={attempt:0,timer:null,cancelled:!1,hadTransaction:Z};this.reconnectStates.set($,W),this.scheduleReconnectAttempt($,W)}cancelAutoReconnect($){let Z=this.reconnectStates.get($);if(Z){if(Z.cancelled=!0,Z.timer)clearTimeout(Z.timer);this.reconnectStates.delete($)}}async scheduleReconnectAttempt($,Z){if(Z.cancelled)return;if(Z.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete($),await this.setConnectionState($,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let W=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,Z.attempt),this.opts.reconnectMaxDelayMs);Z.timer=setTimeout(()=>{if(Z.cancelled)return;this.attemptReconnect($,Z).catch(()=>{})},W)}async attemptReconnect($,Z){if(Z.cancelled)return;let W=this.appDb.getConnectionById($);if(!W){this.cancelAutoReconnect($);return}Z.attempt++,await this.setConnectionState($,"reconnecting");try{await this.closeTunnel($);let X=this.passwords.get($),G=X?{...W.config,password:X}:W.config;G=await this.setupSshTunnel($,G);let V=u(G),B=$$(G);if(await B.connect(G),Z.cancelled){await B.disconnect(),await this.closeTunnel($);return}let H=new Map;if(H.set(V,B),this.drivers.set($,H),h[G.type].supportsMultiDatabase&&"activeDatabases"in G&&G.activeDatabases){let Q=G,Y=(Q.activeDatabases??[]).filter((j)=>j!==Q.database).map((j)=>this.connectDatabase($,Q,j));await Promise.allSettled(Y)}let U=Z.hadTransaction;this.reconnectStates.delete($),await this.setConnectionState($,"connected",void 0,void 0,U),this.startHealthCheck($)}catch{if(Z.cancelled)return;await this.closeTunnel($),this.scheduleReconnectAttempt($,Z)}}async gracefulDisconnect($){let Z=this.drivers.get($);if(!Z)return;for(let[W,X]of Z)try{for(let G of X.getSessionIds()){try{await X.cancel(G)}catch{}if(X.inTransaction(G))try{await X.rollback(G)}catch{}}if(X.inTransaction())try{await X.rollback()}catch{}try{await X.cancel()}catch{}}finally{try{await X.disconnect()}finally{Z.delete(W)}}this.drivers.delete($)}async disconnectAllDrivers($){let Z=this.drivers.get($);if(!Z)return;for(let[W,X]of Z)try{await X.disconnect()}finally{Z.delete(W)}this.drivers.delete($)}async connectDatabase($,Z,W){let X=this.drivers.get($);if(!X)throw Error(`No active connection for id: ${$}`);let G=this.tunnels.get($),V=G?{host:"127.0.0.1",port:G.localPort}:{},B={...Z,...V,database:W},H=$$(B);await H.connect(B),X.set(W,H)}async setupSshTunnel($,Z){if(Z.type!=="postgresql"||!Z.sshTunnel?.enabled)return Z;let W=await F$(Z.sshTunnel,Z.host,Z.port);return this.tunnels.set($,W),{...Z,host:"127.0.0.1",port:W.localPort}}async closeTunnel($){let Z=this.tunnels.get($);if(Z)await Z.close(),this.tunnels.delete($)}getActiveDatabases($){let Z=this.drivers.get($);if(!Z)return[];return[...Z.keys()]}getDefaultDatabaseName($){let Z=this.appDb.getConnectionById($);if(!Z)throw Error(`Connection not found: ${$}`);return u(Z.config)}async setConnectionState($,Z,W,X,G){this.states.set($,{state:Z,error:W});let V=this.listeners.map((B)=>B({connectionId:$,state:Z,error:W,errorCode:X,transactionLost:G||void 0}));await Promise.allSettled(V)}}function $$($){let Z;switch($.type){case"postgresql":Z=new Z0;break;case"sqlite":Z=new W0;break;case"mysql":Z=new $0;break;default:throw Error(`Unsupported connection type: ${$.type}`)}if(process.env.DEBUG_SQL)Z=new n$(Z);return Z}function Z$($,Z=!1){if(!$||!$.type)throw Error("Connection config must have a type");let W=h[$.type];if(!W)throw Error(`Unsupported connection type: ${$.type}`);if(W.hasHost&&w($)){let X=W.label;if(!$.host)throw Error(`${X} host is required`);if(!$.port)throw Error(`${X} port is required`);if(!$.database)throw Error(`${X} database is required`);if(!$.user)throw Error(`${X} user is required`);if(!Z&&($.password===void 0||$.password===null))throw Error(`${X} password is required`)}else if($.type==="sqlite"){if(!$.path)throw Error("SQLite path is required")}}var l7,z5,K5="SELECT datname AS name FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname",d7;var R5=M(()=>{R$();y();H5();U5();Y5();J5();l7=["mysql","information_schema","performance_schema","sys"],z5=`SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN (${l7.map(($)=>`'${$}'`).join(", ")}) ORDER BY schema_name`,d7={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5}});function O5(){let $=process.env.DATABASE_URL;if(!$)return null;let Z;try{Z=new URL($)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let W=Z.protocol.replace(/:$/,"");if(W==="postgresql"||W==="postgres"){let X=Z.hostname||"localhost",G=Z.port?Number(Z.port):5432,V=Z.pathname.replace(/^\//,"")||"postgres",B=decodeURIComponent(Z.username||"postgres"),H=decodeURIComponent(Z.password||"");return{name:`${X}/${V}`,config:{type:"postgresql",host:X,port:G,database:V,user:B,password:H}}}if(W==="mysql"){let X=Z.hostname||"localhost",G=Z.port?Number(Z.port):3306,V=Z.pathname.replace(/^\//,"")||"mysql",B=decodeURIComponent(Z.username||"root"),H=decodeURIComponent(Z.password||"");return{name:`${X}/${V}`,config:{type:"mysql",host:X,port:G,database:V,user:B,password:H}}}return console.warn(`DATABASE_URL: unsupported scheme "${W}", ignoring`),null}var M$="env-default";function V0(){return P$}function L5($,Z){let W=crypto.randomUUID(),X=s.create(":memory:"),G=new X0(X),V=new n(G,void 0,X),B=new I$(Z),H=(J,O)=>{if(R.ws)R.ws.send(JSON.stringify({type:"message",channel:J,payload:O}))},{handlers:U,sessionManager:Q}=W5(G,V,X,void 0,{encryption:B,emitMessage:H}),Y=new Set;if(N$){X.createConnectionWithId(M$,{name:N$.name,config:N$.config}),Y.add(M$);let J=U["connections.list"];U["connections.list"]=()=>{return J().map((A)=>Y.has(A.id)?{...A,serverManaged:!0}:A)}}let j=G.onSessionDead((J)=>{if(Q.handleSessionDead(J.sessionId),R.ws)R.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:Q.listSessions(J.connectionId)}}))}),z=G.onStatusChanged(async(J)=>{if(R.ws)R.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:J.connectionId,state:J.state,error:J.error,errorCode:J.errorCode,transactionLost:J.transactionLost}}));if(J.state==="disconnected"||J.state==="error"){if(Q.handleConnectionLost(J.connectionId),R.ws)R.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:[]}}))}if(J.state==="connected")try{let O=await Q.handleConnectionRestored(J.connectionId);if(O.length>0&&R.ws)R.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:O}}))}catch(O){console.warn("Session restoration failed:",O instanceof Error?O.message:O)}}),R={id:W,appDb:X,connectionManager:G,queryExecutor:V,handlers:U,sessionManager:Q,serverManagedIds:Y,unsubscribe:()=>{j(),z()},ws:$,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(P$.set(W,R),N$)G.connect(M$).catch((J)=>{console.warn("DATABASE_URL auto-connect failed:",J?.message??J)});return R}async function W$($){if(P$.delete($.id),$.ttlTimer)clearTimeout($.ttlTimer),$.ttlTimer=null;$.unsubscribe(),$.sessionManager.dispose();for(let Z of $.queryExecutor.getRunningQueryIds())await $.queryExecutor.cancelQuery(Z);await $.connectionManager.disconnectAll(),$.appDb.close()}async function x5($){if($.ws=null,$.disconnectedAt=Date.now(),$.activeStreams===0)await W$($);else $.ttlTimer=setTimeout(async()=>{if(P$.has($.id))await W$($)},G0)}async function B0($){if($.activeStreams--,$.ws===null&&$.activeStreams===0)await W$($)}function H0($,Z,W,X,G){let V=crypto.randomUUID();return d.set(V,{session:$,connectionId:W,database:X,params:G,type:Z,createdAt:Date.now()}),V}function U0($,Z){let W=d.get($);if(!W)return null;if(W.type!==Z)return null;if(Date.now()-W.createdAt>A5)return d.delete($),null;return d.delete($),W}function _5(){let $=Date.now();for(let[Z,W]of d)if($-W.createdAt>A5)d.delete(Z)}var G0=300000,A5=300000,N$,P$,d;var F5=M(()=>{X5();R5();m$();g$();d$();N$=O5(),P$=new Map;d=new Map});var s7={};import{resolve as Q0}from"path";async function o7($,Z){let W=U0(Z,"export");if(!W)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:X,connectionId:G,database:V,params:B}=W,H=B,U;try{U=X.connectionManager.getDriver(G,V)}catch(J){return new Response(JSON.stringify({error:J?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}X.activeStreams++;let Q=i7[H.format]??"application/octet-stream",Y=n7[H.format]??"dat",j=`${H.table}.${Y}`,z=new AbortController;$.signal.addEventListener("abort",()=>z.abort());let R=new ReadableStream({async start(J){let O={write(A){if(typeof A==="string")J.enqueue(new TextEncoder().encode(A));else J.enqueue(A)},async end(){}};try{let A=await q$(U,H,O,z.signal,(L)=>{if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:L}}))});if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:A.rowCount}}));J.close()}catch(A){if(z.signal.aborted)try{J.close()}catch{}else J.error(A)}finally{await B0(X)}}});return new Response(R,{headers:{"Content-Type":Q,"Content-Disposition":`attachment; filename="${j}"`}})}async function r7($,Z){let W=U0(Z,"import");if(!W)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:X,connectionId:G,database:V,params:B}=W,H=B,U;try{U=X.connectionManager.getDriver(G,V)}catch(Y){return new Response(JSON.stringify({error:Y?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!$.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});X.activeStreams++;let Q=new AbortController;$.signal.addEventListener("abort",()=>Q.abort());try{let Y=await Q$(U,$.body,H,Q.signal,(j)=>{if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:j}}))});return new Response(JSON.stringify({rowCount:Y.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(Y){return new Response(JSON.stringify({error:Y?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await B0(X)}}var c7,N5,M5,P5,t7=60000,i7,n7,a7;var k5=M(()=>{y$();w$();y();F5();c7=Number(process.env.DOTAZ_PORT)||6401,N5=process.env.DOTAZ_HOST||"localhost",M5=process.env.DOTAZ_DIST_DIR||Q0(import.meta.dir,"../../dist"),P5=process.env.DOTAZ_ENCRYPTION_KEY;if(!P5)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{_5()},60000);setInterval(async()=>{let $=Date.now();for(let[,Z]of V0())if(Z.disconnectedAt!==null&&$-Z.disconnectedAt>G0)await W$(Z)},t7);i7={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},n7={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};a7=Bun.serve({port:c7,hostname:N5,async fetch($,Z){let W=new URL($.url);if(W.pathname==="/rpc"){if(Z.upgrade($,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let X=W.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(X&&$.method==="GET")return o7($,X[1]);let G=W.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(G&&$.method==="POST")return r7($,G[1]);if(W.pathname==="/api/menu-action"&&$.method==="POST")try{let U=(await $.json())?.action;if(!U)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,Q]of V0())if(Q.ws)Q.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 V=Q0(M5,W.pathname.slice(1)),B=Bun.file(V);if(await B.exists())return new Response(B);if(V=Q0(M5,"index.html"),B=Bun.file(V),await B.exists())return new Response(B,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open($){let Z=L5($,P5);Object.assign($.data,Z)},async close($){await x5($.data)},async message($,Z){let W;try{W=JSON.parse(typeof Z==="string"?Z:new TextDecoder().decode(Z))}catch{$.send(JSON.stringify({type:"response",id:0,success:!1,error:"Invalid JSON"}));return}if(W.type==="request"){if(W.method==="stream.createExportToken"){let{connectionId:G,database:V,...B}=W.params,H=H0($.data,"export",G,V,B);$.send(JSON.stringify({type:"response",id:W.id,success:!0,payload:{token:H}}));return}if(W.method==="stream.createImportToken"){let{connectionId:G,database:V,...B}=W.params,H=H0($.data,"import",G,V,B);$.send(JSON.stringify({type:"response",id:W.id,success:!0,payload:{token:H}}));return}let X=$.data.handlers[W.method];if(!X){$.send(JSON.stringify({type:"response",id:W.id,success:!1,error:`Unknown method: ${W.method}`}));return}try{let G=await X(W.params);$.send(JSON.stringify({type:"response",id:W.id,success:!0,payload:G}))}catch(G){$.send(JSON.stringify({type:"response",id:W.id,success:!1,error:G?.message??String(G),errorCode:G instanceof N?G.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${N5}:${a7.port}`)});var{secrets:C5}=globalThis.Bun;import{randomBytes as e7}from"crypto";import{resolve as $9}from"path";var E5="dev.dotaz.server",D5="encryption-key",c=process.argv.slice(2),S5=Number(process.env.DOTAZ_PORT)||6401,T5=process.env.DOTAZ_HOST||"localhost";for(let $=0;$<c.length;$++){let Z=c[$];if((Z==="--port"||Z==="-p")&&c[$+1])S5=Number(c[$+1]),$++;else if((Z==="--host"||Z==="-H")&&c[$+1])T5=c[$+1],$++;else if(Z==="--help")console.log(`Usage: dotaz [options]
|
|
332
|
+
`);for(let W of Z){let X=W.toLowerCase();if(X.includes("permission denied")||X.includes("authentication"))return`SSH authentication failed: ${W.trim()}`;if(X.includes("connection refused"))return`SSH host unreachable: ${W.trim()}`;if(X.includes("timed out")||X.includes("timeout"))return`SSH connection timed out: ${W.trim()}`;if(X.includes("no such file")||X.includes("no such identity"))return`SSH key file not found: ${W.trim()}`;if(X.includes("could not resolve"))return`SSH host unreachable: ${W.trim()}`}return Z[Z.length-1]?.trim()||null}function p7($){let Z=$.message.toLowerCase();if(Z.includes("authentication")||Z.includes("permission denied"))return Error(`SSH authentication failed: ${$.message}`);if(Z.includes("econnrefused")||Z.includes("connection refused")||Z.includes("unreachable"))return Error(`SSH host unreachable: ${$.message}`);if(Z.includes("timeout")||Z.includes("timed out"))return Error(`SSH connection timed out: ${$.message}`);return Error(`SSH tunnel error: ${$.message}`)}var v7=15000,g7=100;var J5=()=>{};class X0{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($,Z){this.appDb=$,this.opts={...d7,...Z}}async connect($,Z){let W=this.appDb.getConnectionById($);if(!W)throw Error(`Connection not found: ${$}`);this.cancelAutoReconnect($);let X=(this.connectAttempt.get($)??0)+1;if(this.connectAttempt.set($,X),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),await this.setConnectionState($,"connecting");try{let G=Z?{...W.config,...Z}:W.config;if(Z$(G),w(G))this.passwords.set($,G.password);G=await this.setupSshTunnel($,G);let V=u(G),B=$$(G);if(await B.connect(G),this.connectAttempt.get($)!==X){await B.disconnect().catch(()=>{});return}let H=new Map;if(H.set(V,B),this.drivers.set($,H),h[G.type].supportsMultiDatabase&&"activeDatabases"in G&&G.activeDatabases){let U=G,Q=(U.activeDatabases??[]).filter((Y)=>Y!==U.database).map((Y)=>this.connectDatabase($,U,Y));await Promise.allSettled(Q)}await this.setConnectionState($,"connected"),this.startHealthCheck($)}catch(G){if(this.connectAttempt.get($)!==X)return;await this.closeTunnel($);let V=G instanceof Error?G.message:"Unknown connection error",B=G instanceof N?G.code:void 0;throw await this.setConnectionState($,"error",V,B),G}}async disconnect($){this.connectAttempt.set($,(this.connectAttempt.get($)??0)+1),this.cancelAutoReconnect($),this.stopHealthCheck($),await this.gracefulDisconnect($),await this.closeTunnel($),this.passwords.delete($),await this.setConnectionState($,"disconnected")}async reconnect($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.gracefulDisconnect($);await this.connect($)}getDriver($,Z){let W=this.drivers.get($);if(!W)throw Error(`No active connection for id: ${$}`);let X=Z??this.getDefaultDatabaseName($),G=W.get(X);if(!G)throw Error(`No active driver for database "${X}" on connection ${$}`);return G}getConnectionState($){return this.states.get($)?.state??"disconnected"}async listDatabases($){let Z=this.appDb.getConnectionById($);if(!Z||!h[Z.config.type].supportsMultiDatabase)throw Error("listDatabases is only supported for connections with multi-database support");let W=u(Z.config),X=this.getDriver($,W),G=Z.config.type==="postgresql"?K5:z5,V=await X.execute(G),B=this.drivers.get($),H=B?[...B.keys()]:[W];return V.rows.map((U)=>({name:U.name,isDefault:U.name===W,isActive:H.includes(U.name)}))}async activateDatabase($,Z){let W=this.appDb.getConnectionById($);if(!W||!h[W.config.type].supportsMultiDatabase)throw Error("activateDatabase is only supported for connections with multi-database support");let X=W.config,G=this.drivers.get($);if(!G)throw Error(`No active connection for id: ${$}`);if(G.has(Z))return;let V=this.passwords.get($)??X.password,B={...X,database:Z,password:V};await this.connectDatabase($,B,Z);let H=[...new Set([...X.activeDatabases??[],Z])];this.appDb.updateConnection({id:$,name:W.name,config:{...X,activeDatabases:H}})}async deactivateDatabase($,Z){let W=this.appDb.getConnectionById($);if(!W||!h[W.config.type].supportsMultiDatabase)throw Error("deactivateDatabase is only supported for connections with multi-database support");let X=W.config;if(Z===u(X))throw Error("Cannot deactivate the default database");let G=this.drivers.get($);if(G){let B=G.get(Z);if(B)try{await B.disconnect()}finally{G.delete(Z)}}let V=(X.activeDatabases??[]).filter((B)=>B!==Z);this.appDb.updateConnection({id:$,name:W.name,config:{...X,activeDatabases:V.length>0?V:void 0}})}listConnections(){return this.appDb.listConnections().map((Z)=>({...Z,state:this.getConnectionState(Z.id),error:this.states.get(Z.id)?.error}))}createConnection($,Z=!1){return Z$($.config,Z),this.appDb.createConnection($)}updateConnection($){return Z$($.config),{...this.appDb.updateConnection($),state:this.getConnectionState($.id),error:this.states.get($.id)?.error}}setConnectionReadOnly($,Z){return{...this.appDb.setConnectionReadOnly($,Z),state:this.getConnectionState($),error:this.states.get($)?.error}}async deleteConnection($){if(this.cancelAutoReconnect($),this.stopHealthCheck($),this.drivers.has($))await this.disconnectAllDrivers($);await this.closeTunnel($),this.passwords.delete($),this.states.delete($),this.appDb.deleteConnection($)}async testConnection($){Z$($);let Z=null,W=$;try{if($.type==="postgresql"&&$.sshTunnel?.enabled)Z=await F$($.sshTunnel,$.host,$.port),W={...$,host:"127.0.0.1",port:Z.localPort};let X=$$(W);return await X.connect(W),await X.disconnect(),{success:!0}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Unknown connection error"}}finally{if(Z)await Z.close()}}async listDatabasesForConfig($){if($.type!=="postgresql"&&$.type!=="mysql")throw Error(`Listing databases is not supported for connection type: ${$.type}`);let Z=$.type==="postgresql"?"postgres":"information_schema",W=$.database?$:{...$,database:Z};Z$(W);let X=null;try{if(W.type==="postgresql"&&W.sshTunnel?.enabled)X=await F$(W.sshTunnel,W.host,W.port),W={...W,host:"127.0.0.1",port:X.localPort};let G=$$(W);try{await G.connect(W);let V=W.type==="postgresql"?K5:z5;return(await G.execute(V)).rows.map((H)=>H.name)}finally{await G.disconnect().catch(()=>{})}}finally{if(X)await X.close().catch(()=>{})}}onStatusChanged($){return this.listeners.push($),()=>{let Z=this.listeners.indexOf($);if(Z>=0)this.listeners.splice(Z,1)}}onSessionDead($){return this.sessionDeadListeners.push($),()=>{let Z=this.sessionDeadListeners.indexOf($);if(Z>=0)this.sessionDeadListeners.splice(Z,1)}}async disconnectAll(){for(let Z of[...this.reconnectStates.keys()])this.cancelAutoReconnect(Z);for(let Z of[...this.healthTimers.keys()])this.stopHealthCheck(Z);let $=[...new Set([...this.drivers.keys(),...this.tunnels.keys()])];for(let Z of $)await this.disconnect(Z)}startHealthCheck($){this.stopHealthCheck($);let Z=setInterval(()=>{this.performHealthCheck($)},this.opts.healthCheckIntervalMs);this.healthTimers.set($,Z)}stopHealthCheck($){let Z=this.healthTimers.get($);if(Z)clearInterval(Z),this.healthTimers.delete($)}async performHealthCheck($){if(this.healthCheckRunning.has($))return;this.healthCheckRunning.add($);try{let Z=this.drivers.get($);if(!Z)return;for(let W of Z.values()){try{await Promise.race([W.ping(),new Promise((X,G)=>setTimeout(()=>G(Error("Health check timed out")),this.opts.healthCheckTimeoutMs))])}catch{let X=!1;for(let G of Z.values()){if(G.inTransaction()){X=!0;break}for(let V of G.getSessionIds())if(G.inTransaction(V)){X=!0;break}if(X)break}this.stopHealthCheck($);try{await this.disconnectAllDrivers($)}catch{}await this.setConnectionState($,"disconnected","Connection lost"),this.startAutoReconnect($,X);return}for(let X of W.getSessionIds())try{await W.execute("SELECT 1",void 0,X)}catch{try{await W.releaseSession(X)}catch{}for(let G of this.sessionDeadListeners)try{await G({connectionId:$,sessionId:X})}catch{}}}}finally{this.healthCheckRunning.delete($)}}startAutoReconnect($,Z=!1){this.cancelAutoReconnect($);let W={attempt:0,timer:null,cancelled:!1,hadTransaction:Z};this.reconnectStates.set($,W),this.scheduleReconnectAttempt($,W)}cancelAutoReconnect($){let Z=this.reconnectStates.get($);if(Z){if(Z.cancelled=!0,Z.timer)clearTimeout(Z.timer);this.reconnectStates.delete($)}}async scheduleReconnectAttempt($,Z){if(Z.cancelled)return;if(Z.attempt>=this.opts.reconnectMaxAttempts){this.reconnectStates.delete($),await this.setConnectionState($,"error",`Reconnect failed after ${this.opts.reconnectMaxAttempts} attempts`);return}let W=Math.min(this.opts.reconnectBaseDelayMs*Math.pow(2,Z.attempt),this.opts.reconnectMaxDelayMs);Z.timer=setTimeout(()=>{if(Z.cancelled)return;this.attemptReconnect($,Z).catch(()=>{})},W)}async attemptReconnect($,Z){if(Z.cancelled)return;let W=this.appDb.getConnectionById($);if(!W){this.cancelAutoReconnect($);return}Z.attempt++,await this.setConnectionState($,"reconnecting");try{await this.closeTunnel($);let X=this.passwords.get($),G=X?{...W.config,password:X}:W.config;G=await this.setupSshTunnel($,G);let V=u(G),B=$$(G);if(await B.connect(G),Z.cancelled){await B.disconnect(),await this.closeTunnel($);return}let H=new Map;if(H.set(V,B),this.drivers.set($,H),h[G.type].supportsMultiDatabase&&"activeDatabases"in G&&G.activeDatabases){let Q=G,Y=(Q.activeDatabases??[]).filter((j)=>j!==Q.database).map((j)=>this.connectDatabase($,Q,j));await Promise.allSettled(Y)}let U=Z.hadTransaction;this.reconnectStates.delete($),await this.setConnectionState($,"connected",void 0,void 0,U),this.startHealthCheck($)}catch{if(Z.cancelled)return;await this.closeTunnel($),this.scheduleReconnectAttempt($,Z)}}async gracefulDisconnect($){let Z=this.drivers.get($);if(!Z)return;for(let[W,X]of Z)try{for(let G of X.getSessionIds()){try{await X.cancel(G)}catch{}if(X.inTransaction(G))try{await X.rollback(G)}catch{}}if(X.inTransaction())try{await X.rollback()}catch{}try{await X.cancel()}catch{}}finally{try{await X.disconnect()}finally{Z.delete(W)}}this.drivers.delete($)}async disconnectAllDrivers($){let Z=this.drivers.get($);if(!Z)return;for(let[W,X]of Z)try{await X.disconnect()}finally{Z.delete(W)}this.drivers.delete($)}async connectDatabase($,Z,W){let X=this.drivers.get($);if(!X)throw Error(`No active connection for id: ${$}`);let G=this.tunnels.get($),V=G?{host:"127.0.0.1",port:G.localPort}:{},B={...Z,...V,database:W},H=$$(B);await H.connect(B),X.set(W,H)}async setupSshTunnel($,Z){if(Z.type!=="postgresql"||!Z.sshTunnel?.enabled)return Z;let W=await F$(Z.sshTunnel,Z.host,Z.port);return this.tunnels.set($,W),{...Z,host:"127.0.0.1",port:W.localPort}}async closeTunnel($){let Z=this.tunnels.get($);if(Z)await Z.close(),this.tunnels.delete($)}getActiveDatabases($){let Z=this.drivers.get($);if(!Z)return[];return[...Z.keys()]}getDefaultDatabaseName($){let Z=this.appDb.getConnectionById($);if(!Z)throw Error(`Connection not found: ${$}`);return u(Z.config)}async setConnectionState($,Z,W,X,G){this.states.set($,{state:Z,error:W});let V=this.listeners.map((B)=>B({connectionId:$,state:Z,error:W,errorCode:X,transactionLost:G||void 0}));await Promise.allSettled(V)}}function $$($){let Z;switch($.type){case"postgresql":Z=new Z0;break;case"sqlite":Z=new W0;break;case"mysql":Z=new $0;break;default:throw Error(`Unsupported connection type: ${$.type}`)}if(process.env.DEBUG_SQL)Z=new n$(Z);return Z}function Z$($,Z=!1){if(!$?.type)throw Error("Connection config must have a type");let W=h[$.type];if(!W)throw Error(`Unsupported connection type: ${$.type}`);if(W.hasHost&&w($)){let X=W.label;if(!$.host)throw Error(`${X} host is required`);if(!$.port)throw Error(`${X} port is required`);if(!$.database)throw Error(`${X} database is required`);if(!$.user)throw Error(`${X} user is required`);if(!Z&&($.password===void 0||$.password===null))throw Error(`${X} password is required`)}else if($.type==="sqlite"){if(!$.path)throw Error("SQLite path is required")}}var l7,z5,K5="SELECT datname AS name FROM pg_database WHERE datistemplate = false AND datallowconn = true ORDER BY datname",d7;var R5=M(()=>{R$();y();H5();U5();Y5();J5();l7=["mysql","information_schema","performance_schema","sys"],z5=`SELECT schema_name AS name FROM information_schema.schemata WHERE schema_name NOT IN (${l7.map(($)=>`'${$}'`).join(", ")}) ORDER BY schema_name`,d7={healthCheckIntervalMs:30000,healthCheckTimeoutMs:1e4,reconnectBaseDelayMs:1000,reconnectMaxDelayMs:30000,reconnectMaxAttempts:5}});function O5(){let $=process.env.DATABASE_URL;if(!$)return null;let Z;try{Z=new URL($)}catch{return console.warn("DATABASE_URL: invalid URL, ignoring"),null}let W=Z.protocol.replace(/:$/,"");if(W==="postgresql"||W==="postgres"){let X=Z.hostname||"localhost",G=Z.port?Number(Z.port):5432,V=Z.pathname.replace(/^\//,"")||"postgres",B=decodeURIComponent(Z.username||"postgres"),H=decodeURIComponent(Z.password||"");return{name:`${X}/${V}`,config:{type:"postgresql",host:X,port:G,database:V,user:B,password:H}}}if(W==="mysql"){let X=Z.hostname||"localhost",G=Z.port?Number(Z.port):3306,V=Z.pathname.replace(/^\//,"")||"mysql",B=decodeURIComponent(Z.username||"root"),H=decodeURIComponent(Z.password||"");return{name:`${X}/${V}`,config:{type:"mysql",host:X,port:G,database:V,user:B,password:H}}}return console.warn(`DATABASE_URL: unsupported scheme "${W}", ignoring`),null}var M$="env-default";function V0(){return P$}function L5($,Z){let W=crypto.randomUUID(),X=s.create(":memory:"),G=new X0(X),V=new n(G,void 0,X),B=new I$(Z),H=(J,O)=>{if(R.ws)R.ws.send(JSON.stringify({type:"message",channel:J,payload:O}))},{handlers:U,sessionManager:Q}=W5(G,V,X,void 0,{encryption:B,emitMessage:H}),Y=new Set;if(N$){X.createConnectionWithId(M$,{name:N$.name,config:N$.config}),Y.add(M$);let J=U["connections.list"];U["connections.list"]=()=>{return J().map((A)=>Y.has(A.id)?{...A,serverManaged:!0}:A)}}let j=G.onSessionDead((J)=>{if(Q.handleSessionDead(J.sessionId),R.ws)R.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:Q.listSessions(J.connectionId)}}))}),z=G.onStatusChanged(async(J)=>{if(R.ws)R.ws.send(JSON.stringify({type:"message",channel:"connections.statusChanged",payload:{connectionId:J.connectionId,state:J.state,error:J.error,errorCode:J.errorCode,transactionLost:J.transactionLost}}));if(J.state==="disconnected"||J.state==="error"){if(Q.handleConnectionLost(J.connectionId),R.ws)R.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:[]}}))}if(J.state==="connected")try{let O=await Q.handleConnectionRestored(J.connectionId);if(O.length>0&&R.ws)R.ws.send(JSON.stringify({type:"message",channel:"session.changed",payload:{connectionId:J.connectionId,sessions:O}}))}catch(O){console.warn("Session restoration failed:",O instanceof Error?O.message:O)}}),R={id:W,appDb:X,connectionManager:G,queryExecutor:V,handlers:U,sessionManager:Q,serverManagedIds:Y,unsubscribe:()=>{j(),z()},ws:$,activeStreams:0,disconnectedAt:null,ttlTimer:null};if(P$.set(W,R),N$)G.connect(M$).catch((J)=>{console.warn("DATABASE_URL auto-connect failed:",J?.message??J)});return R}async function W$($){if(P$.delete($.id),$.ttlTimer)clearTimeout($.ttlTimer),$.ttlTimer=null;$.unsubscribe(),$.sessionManager.dispose();for(let Z of $.queryExecutor.getRunningQueryIds())await $.queryExecutor.cancelQuery(Z);await $.connectionManager.disconnectAll(),$.appDb.close()}async function x5($){if($.ws=null,$.disconnectedAt=Date.now(),$.activeStreams===0)await W$($);else $.ttlTimer=setTimeout(async()=>{if(P$.has($.id))await W$($)},G0)}async function B0($){if($.activeStreams--,$.ws===null&&$.activeStreams===0)await W$($)}function H0($,Z,W,X,G){let V=crypto.randomUUID();return d.set(V,{session:$,connectionId:W,database:X,params:G,type:Z,createdAt:Date.now()}),V}function U0($,Z){let W=d.get($);if(!W)return null;if(W.type!==Z)return null;if(Date.now()-W.createdAt>A5)return d.delete($),null;return d.delete($),W}function _5(){let $=Date.now();for(let[Z,W]of d)if($-W.createdAt>A5)d.delete(Z)}var G0=300000,A5=300000,N$,P$,d;var F5=M(()=>{X5();R5();m$();g$();d$();N$=O5(),P$=new Map;d=new Map});var s7={};import{resolve as Q0}from"path";async function o7($,Z){let W=U0(Z,"export");if(!W)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:X,connectionId:G,database:V,params:B}=W,H=B,U;try{U=X.connectionManager.getDriver(G,V)}catch(J){return new Response(JSON.stringify({error:J?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}X.activeStreams++;let Q=i7[H.format]??"application/octet-stream",Y=n7[H.format]??"dat",j=`${H.table}.${Y}`,z=new AbortController;$.signal.addEventListener("abort",()=>z.abort());let R=new ReadableStream({async start(J){let O={write(A){if(typeof A==="string")J.enqueue(new TextEncoder().encode(A));else J.enqueue(A)},async end(){}};try{let A=await q$(U,H,O,z.signal,(L)=>{if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"export.progress",payload:{rowCount:L}}))});if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"export.complete",payload:{rowCount:A.rowCount}}));J.close()}catch(A){if(z.signal.aborted)try{J.close()}catch{}else J.error(A)}finally{await B0(X)}}});return new Response(R,{headers:{"Content-Type":Q,"Content-Disposition":`attachment; filename="${j}"`}})}async function r7($,Z){let W=U0(Z,"import");if(!W)return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:403,headers:{"Content-Type":"application/json"}});let{session:X,connectionId:G,database:V,params:B}=W,H=B,U;try{U=X.connectionManager.getDriver(G,V)}catch(Y){return new Response(JSON.stringify({error:Y?.message??"Failed to get driver"}),{status:500,headers:{"Content-Type":"application/json"}})}if(!$.body)return new Response(JSON.stringify({error:"Request body is required"}),{status:400,headers:{"Content-Type":"application/json"}});X.activeStreams++;let Q=new AbortController;$.signal.addEventListener("abort",()=>Q.abort());try{let Y=await Q$(U,$.body,H,Q.signal,(j)=>{if(X.ws)X.ws.send(JSON.stringify({type:"message",channel:"import.progress",payload:{rowCount:j}}))});return new Response(JSON.stringify({rowCount:Y.rowCount}),{headers:{"Content-Type":"application/json"}})}catch(Y){return new Response(JSON.stringify({error:Y?.message??"Import failed"}),{status:500,headers:{"Content-Type":"application/json"}})}finally{await B0(X)}}var c7,N5,M5,P5,t7=60000,i7,n7,a7;var k5=M(()=>{y$();w$();y();F5();c7=Number(process.env.DOTAZ_PORT)||6401,N5=process.env.DOTAZ_HOST||"localhost",M5=process.env.DOTAZ_DIST_DIR||Q0(import.meta.dir,"../../dist"),P5=process.env.DOTAZ_ENCRYPTION_KEY;if(!P5)console.error("DOTAZ_ENCRYPTION_KEY is required for web mode"),process.exit(1);setInterval(()=>{_5()},60000);setInterval(async()=>{let $=Date.now();for(let[,Z]of V0())if(Z.disconnectedAt!==null&&$-Z.disconnectedAt>G0)await W$(Z)},t7);i7={csv:"text/csv",json:"application/json",sql:"application/sql",markdown:"text/markdown",sql_update:"application/sql",html:"text/html",xml:"application/xml"},n7={csv:"csv",json:"json",sql:"sql",markdown:"md",sql_update:"sql",html:"html",xml:"xml"};a7=Bun.serve({port:c7,hostname:N5,async fetch($,Z){let W=new URL($.url);if(W.pathname==="/rpc"){if(Z.upgrade($,{data:{}}))return;return new Response("WebSocket upgrade failed",{status:400})}let X=W.pathname.match(/^\/api\/stream\/export\/([a-f0-9-]+)$/);if(X&&$.method==="GET")return o7($,X[1]);let G=W.pathname.match(/^\/api\/stream\/import\/([a-f0-9-]+)$/);if(G&&$.method==="POST")return r7($,G[1]);if(W.pathname==="/api/menu-action"&&$.method==="POST")try{let U=(await $.json())?.action;if(!U)return new Response(JSON.stringify({error:"Missing action"}),{status:400,headers:{"Content-Type":"application/json"}});for(let[,Q]of V0())if(Q.ws)Q.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 V=Q0(M5,W.pathname.slice(1)),B=Bun.file(V);if(await B.exists())return new Response(B);if(V=Q0(M5,"index.html"),B=Bun.file(V),await B.exists())return new Response(B,{headers:{"Content-Type":"text/html"}});return new Response("Not found",{status:404})},websocket:{open($){let Z=L5($,P5);Object.assign($.data,Z)},async close($){await x5($.data)},async message($,Z){let W;try{W=JSON.parse(typeof Z==="string"?Z:new TextDecoder().decode(Z))}catch{$.send(JSON.stringify({type:"response",id:0,success:!1,error:"Invalid JSON"}));return}if(W.type==="request"){if(W.method==="stream.createExportToken"){let{connectionId:G,database:V,...B}=W.params,H=H0($.data,"export",G,V,B);$.send(JSON.stringify({type:"response",id:W.id,success:!0,payload:{token:H}}));return}if(W.method==="stream.createImportToken"){let{connectionId:G,database:V,...B}=W.params,H=H0($.data,"import",G,V,B);$.send(JSON.stringify({type:"response",id:W.id,success:!0,payload:{token:H}}));return}let X=$.data.handlers[W.method];if(!X){$.send(JSON.stringify({type:"response",id:W.id,success:!1,error:`Unknown method: ${W.method}`}));return}try{let G=await X(W.params);$.send(JSON.stringify({type:"response",id:W.id,success:!0,payload:G}))}catch(G){$.send(JSON.stringify({type:"response",id:W.id,success:!1,error:G?.message??String(G),errorCode:G instanceof N?G.code:void 0}))}}}}});console.log(`Dotaz web server running at http://${N5}:${a7.port}`)});var{secrets:C5}=globalThis.Bun;import{randomBytes as e7}from"crypto";import{resolve as $9}from"path";var E5="dev.dotaz.server",D5="encryption-key",c=process.argv.slice(2),S5=Number(process.env.DOTAZ_PORT)||6401,T5=process.env.DOTAZ_HOST||"localhost";for(let $=0;$<c.length;$++){let Z=c[$];if((Z==="--port"||Z==="-p")&&c[$+1])S5=Number(c[$+1]),$++;else if((Z==="--host"||Z==="-H")&&c[$+1])T5=c[$+1],$++;else if(Z==="--help")console.log(`Usage: dotaz [options]
|
|
333
333
|
|
|
334
334
|
Options:
|
|
335
335
|
-p, --port <port> Port to listen on (default: 6401)
|