duckdb-terminal 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/duckdb-terminal.js
CHANGED
|
@@ -1654,13 +1654,21 @@ function ge(s, t = it) {
|
|
|
1654
1654
|
}
|
|
1655
1655
|
async function Tt(s) {
|
|
1656
1656
|
return new Promise((t) => {
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
},
|
|
1657
|
+
let e = !1;
|
|
1658
|
+
const i = (o) => {
|
|
1659
|
+
e || (e = !0, r.remove(), t(o));
|
|
1660
|
+
}, r = document.createElement("input");
|
|
1661
|
+
r.type = "file", r.multiple = s?.multiple ?? !0, r.accept = s?.accept ?? ".csv,.parquet,.json,.db,.duckdb", r.style.position = "fixed", r.style.left = "-9999px", r.style.opacity = "0", document.body.appendChild(r), r.onchange = () => {
|
|
1662
|
+
i(Array.from(r.files ?? []));
|
|
1663
|
+
}, r.oncancel = () => {
|
|
1664
|
+
i([]);
|
|
1665
|
+
};
|
|
1666
|
+
const n = () => {
|
|
1667
|
+
setTimeout(() => {
|
|
1668
|
+
e || i([]);
|
|
1669
|
+
}, 300);
|
|
1670
|
+
};
|
|
1671
|
+
window.addEventListener("focus", n, { once: !0 }), r.click();
|
|
1664
1672
|
});
|
|
1665
1673
|
}
|
|
1666
1674
|
async function we(s, t = it) {
|
|
@@ -4391,7 +4399,7 @@ class Si {
|
|
|
4391
4399
|
fontSize: this.config.fontSize,
|
|
4392
4400
|
theme: this.getCurrentThemeObject(),
|
|
4393
4401
|
scrollback: this.config.scrollback
|
|
4394
|
-
}), this.config.welcomeMessage !== !1 && (this.write(se), this.writeln(""), this.writeln(L("DuckDB Terminal") + " v0.5.
|
|
4402
|
+
}), this.config.welcomeMessage !== !1 && (this.write(se), this.writeln(""), this.writeln(L("DuckDB Terminal") + " v0.5.1"), this.write(d("Loading DuckDB WASM...", T))), await Promise.all([
|
|
4395
4403
|
this.database.init(),
|
|
4396
4404
|
this.history.init()
|
|
4397
4405
|
]), await this.database.loadPoachedExtension(), this.config.welcomeMessage !== !1 && (this.write(re), this.write("\r" + C), this.writeln(d("Powered by DuckDB WASM and Ghostty", T)), this.writeln(""), this.writeln("Type " + d(".help", v) + " for available commands"), this.writeln("Enter SQL statements ending with " + d(";", F)), this.writeln("")), this.terminalAdapter.onData(this.handleInput.bind(this)), this.inputBuffer.setTerminalWidth(this.terminalAdapter.cols), this.terminalAdapter.onResize((e) => {
|
|
@@ -4825,7 +4833,9 @@ class Si {
|
|
|
4825
4833
|
return;
|
|
4826
4834
|
}
|
|
4827
4835
|
if (t.trim().startsWith(".") && this.state !== "collecting") {
|
|
4828
|
-
this.writeln("")
|
|
4836
|
+
this.writeln("");
|
|
4837
|
+
const r = this.history.add(t.trim());
|
|
4838
|
+
await this.executeCommand(t.trim()), await r, this.inputBuffer.clear(), this.writeln(""), this.showPrompt();
|
|
4829
4839
|
return;
|
|
4830
4840
|
}
|
|
4831
4841
|
this.collectedSQL.push(t);
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
`)}function Q(s,t){const e=r=>{const n=N(r,"");return n.includes(",")||n.includes('"')||n.includes(`
|
|
19
19
|
`)?'"'+n.replace(/"/g,'""')+'"':n},i=[];i.push(s.map(e).join(","));for(const r of t)i.push(r.map(e).join(","));return i.join(`
|
|
20
20
|
`)}function H(s,t){const e=r=>N(r,"").replace(/\t/g," ").replace(/\n/g," "),i=[];i.push(s.map(e).join(" "));for(const r of t)i.push(r.map(e).join(" "));return i.join(`
|
|
21
|
-
`)}function _(s,t){const e=t.map(i=>{const r={};return s.forEach((n,o)=>{r[n]=i[o]??null}),r});return JSON.stringify(e,St,2)}const st=100*1024*1024;class Se extends Error{constructor(t,e,i=st){super(`File "${t}" (${z(e)}) exceeds maximum size of ${z(i)}`),this.filename=t,this.size=e,this.maxSize=i,this.name="FileSizeError"}}function Le(s,t=st){if(s.size>t)throw new Se(s.name,s.size,t)}async function Lt(s){return new Promise(t=>{const e=document.createElement("input");
|
|
21
|
+
`)}function _(s,t){const e=t.map(i=>{const r={};return s.forEach((n,o)=>{r[n]=i[o]??null}),r});return JSON.stringify(e,St,2)}const st=100*1024*1024;class Se extends Error{constructor(t,e,i=st){super(`File "${t}" (${z(e)}) exceeds maximum size of ${z(i)}`),this.filename=t,this.size=e,this.maxSize=i,this.name="FileSizeError"}}function Le(s,t=st){if(s.size>t)throw new Se(s.name,s.size,t)}async function Lt(s){return new Promise(t=>{let e=!1;const i=o=>{e||(e=!0,r.remove(),t(o))},r=document.createElement("input");r.type="file",r.multiple=s?.multiple??!0,r.accept=s?.accept??".csv,.parquet,.json,.db,.duckdb",r.style.position="fixed",r.style.left="-9999px",r.style.opacity="0",document.body.appendChild(r),r.onchange=()=>{i(Array.from(r.files??[]))},r.oncancel=()=>{i([])};const n=()=>{setTimeout(()=>{e||i([])},300)};window.addEventListener("focus",n,{once:!0}),r.click()})}async function Pe(s,t=st){return Le(s,t),new Promise((e,i)=>{const r=new FileReader;r.onload=()=>{e(new Uint8Array(r.result))},r.onerror=()=>i(r.error),r.readAsArrayBuffer(s)})}function z(s){if(s===0)return"0 B";const t=1024,e=["B","KB","MB","GB"],i=Math.floor(Math.log(s)/Math.log(t));return parseFloat((s/Math.pow(t,i)).toFixed(2))+" "+e[i]}function Pt(s){const t=s.lastIndexOf(".");return t===-1?"":s.substring(t+1).toLowerCase()}function ke(s){return{name:s.name,size:s.size,type:s.type||Pt(s.name),lastModified:new Date(s.lastModified)}}function Ie(s,t,e="application/octet-stream"){const i=s instanceof Uint8Array?[new Uint8Array(s)]:[s],r=new Blob(i,{type:e}),n=URL.createObjectURL(r),o=document.createElement("a");o.href=n,o.download=t,o.click(),URL.revokeObjectURL(n)}function $e(s,t){const e=n=>{n.preventDefault(),n.stopPropagation(),s.classList.add("drag-over")},i=n=>{n.preventDefault(),n.stopPropagation(),s.classList.remove("drag-over")},r=n=>{n.preventDefault(),n.stopPropagation(),s.classList.remove("drag-over");const o=Array.from(n.dataTransfer?.files??[]);o.length>0&&t(o)};return s.addEventListener("dragover",e),s.addEventListener("dragleave",i),s.addEventListener("drop",r),()=>{s.removeEventListener("dragover",e),s.removeEventListener("dragleave",i),s.removeEventListener("drop",r)}}async function Z(s){try{if(navigator.clipboard&&navigator.clipboard.writeText)return await navigator.clipboard.writeText(s),!0;const t=document.createElement("textarea");t.value=s,t.style.position="fixed",t.style.left="-9999px",t.style.top="-9999px",document.body.appendChild(t),t.select();try{return document.execCommand("copy"),!0}finally{document.body.removeChild(t)}}catch{return!1}}async function kt(){try{return navigator.clipboard&&navigator.clipboard.readText?await navigator.clipboard.readText():null}catch{return null}}function Re(){return!!(navigator.clipboard&&navigator.clipboard.writeText)}function Ae(s){switch(s){case"KEYWORD":return K;case"IDENTIFIER":return"";case"OPERATOR":return X;case"NUMERIC_CONSTANT":return bt;case"STRING_CONSTANT":return C;case"COMMENT":return x;case"ERROR":return y;default:return""}}function tt(s,t){if(t.length===0)return s;let e="",i=0;for(let r=0;r<t.length;r++){const n=t[r],o=t[r+1],a=n.position,l=o?o.position:s.length;a>i&&(e+=s.slice(i,a));const c=s.slice(a,l),m=Ae(n.category);m?e+=m+c+B:e+=c,i=l}return i<s.length&&(e+=s.slice(i)),e}function It(s){const t=s.trim();if(!t)return!1;let e=!1,i=!1,r=!1,n=!1,o="";for(let a=0;a<t.length;a++){const l=t[a],c=t[a+1];if(r){l===`
|
|
22
22
|
`&&(r=!1);continue}if(n){l==="*"&&c==="/"&&(n=!1,a++);continue}if(e){l==="'"&&c==="'"?a++:l==="'"&&(e=!1);continue}if(i){l==='"'&&(i=!1);continue}if(l==="-"&&c==="-"){r=!0,a++;continue}if(l==="/"&&c==="*"){n=!0,a++;continue}if(l==="'"){e=!0;continue}if(l==='"'){i=!0;continue}/\s/.test(l)||(o=l)}return o===";"}function Ne(s,t){let e=null;const i=function(...r){e!==null&&clearTimeout(e),e=setTimeout(()=>{s.apply(this,r),e=null},t)};return i.cancel=()=>{e!==null&&(clearTimeout(e),e=null)},i}function Me(s){const t=[];let e="",i=null,r=!1,n=!1;for(let o=0;o<s.length;o++){const a=s[o];if(r){switch(a){case"n":e+=`
|
|
23
23
|
`;break;case"t":e+=" ";break;case"r":e+="\r";break;case"\\":e+="\\";break;case'"':e+='"';break;case"'":e+="'";break;case" ":e+=" ";break;default:e+="\\"+a}r=!1;continue}if(a==="\\"&&i!=="'"){r=!0;continue}if((a==='"'||a==="'")&&!i){i=a,n=!0;continue}if(a===i){i=null;continue}if(a===" "&&!i){(e||n)&&(t.push(e),e="",n=!1);continue}e+=a}return(e||n)&&t.push(e),t}function Be(s){const t=Me(s),e=t[0]?.toLowerCase()??"",i=t.slice(1);return{command:e,args:i,allArgs:t}}const $=/https?:\/\/[^\s<>"\])\[}{'|^`\\]+/gi,De="\x1B]8;;",Ue="\x07",Oe="\x1B]8;;\x07";function Fe(s){return $.lastIndex=0,$.test(s)}function Qe(s){return $.lastIndex=0,s.match($)||[]}function $t(s,t){return`${De}${s}${Ue}${t??s}${Oe}`}function Rt(s){return $.lastIndex=0,s.replace($,t=>$t(t))}function He(s){try{return new URL(s),!0}catch{return!1}}function _e(s,t=60){if(s.length<=t)return s;try{const e=new URL(s),i=e.host,r=e.pathname+e.search+e.hash,n=i.length,o=t-n-8;if(o<10)return s.substring(0,t-3)+"...";const a=r.substring(0,Math.floor(o/2)),l=r.substring(r.length-Math.floor(o/2));return`${e.protocol}//${i}${a}...${l}`}catch{return s.substring(0,t-3)+"..."}}class At{constructor(){h(this,"enabled",!0);h(this,"maxURLLength",80)}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}setMaxURLLength(t){this.maxURLLength=t}process(t){return this.enabled?Rt(t):t}processWithTruncation(t){return this.enabled?($.lastIndex=0,t.replace($,e=>{const i=_e(e,this.maxURLLength);return $t(e,i)})):t}}const ze={widthPercent:80,heightPercent:70,padding:20,minWidth:400,minHeight:300},Nt="https://cdn.jsdelivr.net/npm/uplot",qe=()=>`${Nt}@1.6.32/dist/uPlot.iife.min.js`,je=()=>`${Nt}@1.6.32/dist/uPlot.min.css`;class We{constructor(){h(this,"state","idle");h(this,"uplot",null);h(this,"loadPromise",null);h(this,"error",null);h(this,"LOAD_TIMEOUT",1e4)}getState(){return this.state}isLoaded(){return this.state==="loaded"&&this.uplot!==null}getUPlot(){return this.uplot}getError(){return this.error}async load(){if(this.state==="loaded"&&this.uplot)return this.uplot;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;if(this.state==="error"&&this.error)throw this.error;this.state="loading",this.loadPromise=this.doLoad();try{return this.uplot=await this.loadPromise,this.state="loaded",this.uplot}catch(t){throw this.state="error",this.error=t instanceof Error?t:new Error(String(t)),this.error}}reset(){this.state="idle",this.uplot=null,this.loadPromise=null,this.error=null}async doLoad(){await Promise.all([this.loadCSS(),this.loadJS()]);const t=window.uPlot;if(!t)throw new Error("uPlot not found on window after loading");return t}loadJS(){return new Promise((t,e)=>{if(window.uPlot){t();return}const i=document.createElement("script");i.src=qe(),i.async=!0;const r=setTimeout(()=>{e(new Error("Timeout loading uPlot JavaScript"))},this.LOAD_TIMEOUT);i.onload=()=>{clearTimeout(r),t()},i.onerror=()=>{clearTimeout(r),e(new Error("Failed to load uPlot JavaScript from CDN"))},document.head.appendChild(i)})}loadCSS(){return new Promise((t,e)=>{if(document.querySelector('link[href*="uPlot.min.css"]')){t();return}const r=document.createElement("link");r.rel="stylesheet",r.href=je();const n=setTimeout(()=>{e(new Error("Timeout loading uPlot CSS"))},this.LOAD_TIMEOUT);r.onload=()=>{clearTimeout(n),t()},r.onerror=()=>{clearTimeout(n),e(new Error("Failed to load uPlot CSS from CDN"))},document.head.appendChild(r)})}}const Ge=new We;class Ve{constructor(t,e={},i=ze){h(this,"container");h(this,"overlay",null);h(this,"chartContainer",null);h(this,"loadingIndicator",null);h(this,"state","hidden");h(this,"resizeObserver",null);h(this,"events");h(this,"dimensions");h(this,"keyHandler",null);h(this,"clickHandler",null);h(this,"TRANSITION_DURATION",200);this.container=t,this.events=e,this.dimensions=i}getState(){return this.state}isVisible(){return this.state==="visible"||this.state==="showing"}getChartContainer(){return this.chartContainer}getChartDimensions(){const t=this.container.getBoundingClientRect(),e=Math.max(this.dimensions.minWidth,Math.floor(t.width*this.dimensions.widthPercent/100-this.dimensions.padding*2)),i=Math.max(this.dimensions.minHeight,Math.floor(t.height*this.dimensions.heightPercent/100-this.dimensions.padding*2));return{width:e,height:i}}show(){return this.state==="visible"||this.state==="showing"?Promise.resolve():(this.state="showing",this.createOverlay(),this.setupKeyboardHandler(),this.setupResizeObserver(),new Promise(t=>{this.overlay?.offsetHeight,this.overlay&&(this.overlay.style.opacity="1"),setTimeout(()=>{this.state="visible",t()},this.TRANSITION_DURATION)}))}hide(){return this.state==="hidden"||this.state==="hiding"?Promise.resolve():(this.state="hiding",this.overlay&&(this.overlay.style.opacity="0"),new Promise(t=>{setTimeout(()=>{this.destroyOverlay(),this.state="hidden",t()},this.TRANSITION_DURATION)}))}toggle(){return this.isVisible()?this.hide():this.show()}showLoading(){if(!this.chartContainer||this.loadingIndicator)return;this.loadingIndicator=document.createElement("div"),this.loadingIndicator.className="duckdb-chart-loading",this.loadingIndicator.style.cssText=`
|
|
24
24
|
position: absolute;
|
|
@@ -300,10 +300,10 @@ Press ESC to close the chart, Ctrl+S to export as PNG.`}function Ci(s,t){const e
|
|
|
300
300
|
text-overflow: ellipsis;
|
|
301
301
|
`,o.textContent=t.query,o.title=t.query,i.appendChild(r),i.appendChild(n),i.appendChild(o),i.addEventListener("click",()=>{this.focusedIndex=e,this.updateFocusedItem(),this.toggleSelection(e)}),i}updateQueryItemUI(t){const e=this.displayedQueries[t];if(!e||!this.queryListContainer)return;const i=this.queryListContainer.querySelector(`[data-index="${t}"]`);if(!i)return;const r=i.querySelector(".query-checkbox");r&&(r.style.borderColor=e.selected?"#007acc":"rgba(255, 255, 255, 0.3)",r.style.background=e.selected?"#007acc":"transparent",r.innerHTML=e.selected?`<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
|
|
302
302
|
<path d="M2 6L5 9L10 3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
|
303
|
-
</svg>`:""),e.selected?i.classList.add("selected"):i.classList.remove("selected")}updateFooter(){if(!this.footerContainer)return;const t=this.footerContainer.querySelector(".sharing-char-count"),e=this.footerContainer.querySelector(".duckdb-sharing-copy-btn"),i=this.getCurrentURLLength(),r=this.selectedIndices.size;t&&(t.textContent=`${i} / ${this.config.maxUrlLength} characters`,i>this.config.maxUrlLength*.9?t.style.color="#dc3545":i>this.config.maxUrlLength*.7?t.style.color="#ffc107":t.style.color="var(--modal-text-dim, #858585)"),e&&(e.disabled=r===0,e.textContent=r>0?`Copy shareable link (${r} ${r===1?"query":"queries"})`:"Copy shareable link")}updateFocusedItem(){if(!this.queryListContainer)return;if(this.queryListContainer.querySelectorAll(".duckdb-sharing-query-item").forEach(e=>e.classList.remove("focused")),this.focusedIndex>=0){const e=this.queryListContainer.querySelector(`[data-index="${this.focusedIndex}"]`);e&&(e.classList.add("focused"),e.scrollIntoView({block:"nearest"}))}}async copyAndClose(){const t=this.getSelectedQueries();if(t.length===0)return;const{url:e}=j(t);await Z(e)&&(this.events.onCopy?.(e),await this.hide())}destroyOverlay(){this.removeKeyboardHandler(),this.removeClickHandler(),this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.modalContainer=null,this.queryListContainer=null,this.footerContainer=null,this.displayedQueries=[],this.selectedIndices.clear()}setupKeyboardHandler(){this.keyHandler=t=>{if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.hide(),this.events.onDismiss?.();return}if(t.key==="Enter"&&this.selectedIndices.size>0){t.preventDefault(),t.stopPropagation(),this.copyAndClose();return}if(t.key===" "&&this.focusedIndex>=0){t.preventDefault(),t.stopPropagation(),this.toggleSelection(this.focusedIndex);return}if(t.key==="ArrowDown"){t.preventDefault(),t.stopPropagation(),this.moveFocusDown();return}if(t.key==="ArrowUp"){t.preventDefault(),t.stopPropagation(),this.moveFocusUp();return}},document.addEventListener("keydown",this.keyHandler,!0)}moveFocusDown(){if(this.displayedQueries.length===0)return;const t=this.focusedIndex-1;t>=0&&(this.focusedIndex=t,this.updateFocusedItem())}moveFocusUp(){if(this.displayedQueries.length===0)return;const t=this.focusedIndex+1;t<this.displayedQueries.length?(this.focusedIndex=t,this.updateFocusedItem()):this.hasMoreQueries()&&(this.loadMoreQueries(),this.focusedIndex=this.displayedQueries.length-1,this.updateFocusedItem())}removeKeyboardHandler(){this.keyHandler&&(document.removeEventListener("keydown",this.keyHandler,!0),this.keyHandler=null)}setupClickHandler(){this.clickHandler=t=>{t.target===this.overlay&&(t.preventDefault(),t.stopPropagation(),this.hide(),this.events.onDismiss?.())},this.overlay?.addEventListener("click",this.clickHandler)}removeClickHandler(){this.clickHandler&&this.overlay&&this.overlay.removeEventListener("click",this.clickHandler),this.clickHandler=null}}const ki={background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selection:"#264f78",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#ffffff"},Ii={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",selection:"#add6ff",black:"#000000",red:"#cd3131",green:"#008000",yellow:"#795e00",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},jt={name:"dark",colors:ki},Wt={name:"light",colors:Ii};function ot(s){return s==="light"?Wt:jt}function Gt(){try{const s=localStorage.getItem("duckdb-terminal-theme");if(s==="light"||s==="dark")return s}catch{}return"dark"}function Vt(s){try{localStorage.setItem("duckdb-terminal-theme",s)}catch{}}const at="duckdb-terminal-ai-settings",lt="http://localhost:4000",ct="claude";function ht(){return lt}function Yt(){return ct}function ut(){try{const s=localStorage.getItem(at);if(s){const t=JSON.parse(s);return{endpoint:t.endpoint||lt,provider:t.provider||ct}}}catch{}return{endpoint:lt,provider:ct}}function W(s){try{const e={...ut(),...s};localStorage.setItem(at,JSON.stringify(e))}catch{}}function $i(){try{localStorage.removeItem(at)}catch{}}class I extends Error{constructor(t,e,i){super(t),this.statusCode=e,this.endpoint=i,this.name="AIClientError"}}function dt(s){return s.replace(/\/$/,"")}async function it(s){const t=`${dt(s)}/providers`;try{return(await fetch(t,{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function ft(s){const t=`${dt(s)}/providers`;try{const e=await fetch(t,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new I(`Failed to fetch providers: ${e.statusText}`,e.status,t);return(await e.json()).providers||[]}catch(e){throw e instanceof I?e:new I(`Network error connecting to ${t}: ${e instanceof Error?e.message:"Unknown error"}`,void 0,t)}}async function Kt(s,t,e,i){const r=`${dt(s)}/generate-sql`,n={ddl:t,question:e};i&&(n.provider=i);try{const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!o.ok){const l=await o.text().catch(()=>o.statusText);throw new I(`Failed to generate SQL: ${l}`,o.status,r)}return(await o.json()).sql}catch(o){throw o instanceof I?o:new I(`Network error connecting to ${r}: ${o instanceof Error?o.message:"Unknown error"}`,void 0,r)}}const Xt="🦆 ",Jt=" > ";class Zt{constructor(t){h(this,"terminalAdapter");h(this,"database");h(this,"inputBuffer");h(this,"history");h(this,"state","idle");h(this,"collectedSQL",[]);h(this,"commands",new Map);h(this,"showTimer",!1);h(this,"outputMode","table");h(this,"currentThemeName");h(this,"customTheme",null);h(this,"config");h(this,"loadedFiles",new Map);h(this,"syntaxHighlighting",!0);h(this,"lastQueryResult",null);h(this,"linkProvider");h(this,"chartManager",null);h(this,"sharingModal",null);h(this,"eventListeners",new Map);h(this,"pageSize",0);h(this,"paginationQuery",null);h(this,"currentPage",0);h(this,"totalRows",0);h(this,"prompt");h(this,"continuationPrompt");h(this,"debouncedHighlight",Ne(()=>this.redrawLineHighlighted(),150));h(this,"queryQueue",Promise.resolve(null));h(this,"dragDropCleanup",null);h(this,"aiSettingsLoaded",!1);h(this,"aiEndpoint","http://localhost:4000");h(this,"aiProvider","claude");this.config=t,this.terminalAdapter=new pt,this.database=new gt({storage:t.storage??"memory",databasePath:t.databasePath}),this.inputBuffer=new Ct,this.history=new vt,this.linkProvider=new At,t.linkDetection===!1&&this.linkProvider.setEnabled(!1),this.prompt=t.prompt??Xt,this.continuationPrompt=t.continuationPrompt??Jt,typeof t.theme=="object"?(this.customTheme=t.theme,this.currentThemeName="custom"):this.currentThemeName=t.theme??Gt(),this.registerCommands()}on(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t).add(e),()=>this.off(t,e)}off(t,e){this.eventListeners.get(t)?.delete(e)}emit(t,e){this.eventListeners.get(t)?.forEach(i=>{try{i(e)}catch(r){console.error(`Error in ${t} event listener:`,r)}})}setState(t){const e=this.state;e!==t&&(this.state=t,this.emit("stateChange",{state:t,previous:e}))}async getHighlightedSQLAsync(t){if(!this.syntaxHighlighting)return t;if(this.database.isPoachedLoaded()){const e=await this.database.tokenizeSQL(t);if(e)return tt(t,e)}return t}async redrawLineHighlighted(){if(!this.syntaxHighlighting)return;const t=this.inputBuffer.getContent();if(t.length===0)return;const e=this.inputBuffer.getCursorPosition(),i=this.inputBuffer.getEndPosition();let r;if(this.database.isPoachedLoaded()){const c=await this.database.tokenizeSQL(t);c?r=tt(t,c):r=t}else r=t;if(t!==this.inputBuffer.getContent())return;const n={col:this.inputBuffer.getPromptLength()};let o="";e.row>0&&(o+=U(e.row)),o+=L(n.col+1),this.write(o),this.write(E);for(let c=1;c<=i.row;c++)this.write(R(1)),this.write(L(1)),this.write(E);i.row>0&&this.write(U(i.row)),this.write(L(n.col+1)),this.write(r);const a=this.inputBuffer.getEndPosition();let l="";a.row>e.row&&(l+=U(a.row-e.row)),l+=L(e.col+1),this.write(l)}getCurrentThemeObject(){return this.customTheme?this.customTheme:ot(this.currentThemeName)}async start(){const t=this.resolveContainer();await this.terminalAdapter.init(t,{fontFamily:this.config.fontFamily,fontSize:this.config.fontSize,theme:this.getCurrentThemeObject(),scrollback:this.config.scrollback}),this.config.welcomeMessage!==!1&&(this.write(pe),this.writeln(""),this.writeln(P("DuckDB Terminal")+" v0.5.0"),this.write(d("Loading DuckDB WASM...",x))),await Promise.all([this.database.init(),this.history.init()]),await this.database.loadPoachedExtension(),this.config.welcomeMessage!==!1&&(this.write(ge),this.write("\r"+E),this.writeln(d("Powered by DuckDB WASM and Ghostty",x)),this.writeln(""),this.writeln("Type "+d(".help",T)+" for available commands"),this.writeln("Enter SQL statements ending with "+d(";",D)),this.writeln("")),this.terminalAdapter.onData(this.handleInput.bind(this)),this.inputBuffer.setTerminalWidth(this.terminalAdapter.cols),this.terminalAdapter.onResize(e=>{this.handleResize(e)}),this.dragDropCleanup=$e(t,e=>{this.handleDroppedFiles(e)}),this.showPrompt(),this.emit("ready",{})}destroy(){this.dragDropCleanup&&(this.dragDropCleanup(),this.dragDropCleanup=null),this.chartManager&&(this.chartManager.destroy(),this.chartManager=null),this.sharingModal&&(this.sharingModal.destroy(),this.sharingModal=null),this.eventListeners.clear(),this.debouncedHighlight.cancel()}openSharingModal(){if(this.state==="executing")return;if(!this.sharingModal){const i=this.resolveContainer();this.sharingModal=new qt(i,{},{maxUrlLength:2e3,initialQueryCount:5,loadMoreCount:5})}const e=this.history.getAll().filter(i=>!i.trim().startsWith("."));this.sharingModal.show(e)}async handleDroppedFiles(t){const e=await Promise.allSettled(t.map(n=>this.loadFile(n))),i=e.filter(n=>n.status==="fulfilled"&&n.value).length,r=e.length-i;r>0&&i>0&&this.writeln(p(`Loaded ${i} of ${e.length} files (${r} failed)`)),this.showPrompt()}async loadFile(t){const e=Pt(t.name),i=ke(t);try{const r=await Pe(t);await this.database.registerFile(t.name,r),this.loadedFiles.set(t.name,i),this.emit("fileLoaded",{filename:t.name,size:t.size,type:e}),this.writeln(""),this.writeln(d(`Loaded: ${t.name}`,C)+` (${z(t.size)})`);const n=t.name.replace(/'/g,"''");if(e==="csv"){const o=t.name.replace(/\.[^.]+$/,"").replace(/[^a-zA-Z0-9_]/g,"_");this.writeln(p(`Hint: SELECT * FROM read_csv('${n}');`)),this.writeln(p(` or: CREATE TABLE ${o} AS SELECT * FROM read_csv('${n}');`))}else e==="parquet"?this.writeln(p(`Hint: SELECT * FROM read_parquet('${n}');`)):e==="json"&&this.writeln(p(`Hint: SELECT * FROM read_json('${n}');`));return!0}catch(r){const n=r instanceof Error?r.message:String(r);return this.writeln(d(`Error loading ${t.name}: ${n}`,y)),!1}}resolveContainer(){if(typeof this.config.container=="string"){const t=document.querySelector(this.config.container);if(!t)throw new Error(`Container not found: ${this.config.container}`);return t}return this.config.container}registerCommands(){this.commands.set(".help",{name:".help",description:"Show available commands",handler:()=>this.cmdHelp()}),this.commands.set(".clear",{name:".clear",description:"Clear the terminal",handler:()=>this.clear()}),this.commands.set(".tables",{name:".tables",description:"List all tables",handler:()=>this.cmdTables()}),this.commands.set(".schema",{name:".schema",description:"Show table schema",usage:".schema <table_name>",handler:t=>this.cmdSchema(t)}),this.commands.set(".timer",{name:".timer",description:"Toggle query timing",usage:".timer on|off",handler:t=>this.cmdTimer(t)}),this.commands.set(".mode",{name:".mode",description:"Set output mode",usage:".mode table|csv|tsv|json",handler:t=>this.cmdMode(t)}),this.commands.set(".theme",{name:".theme",description:"Set color theme (clears screen)",usage:".theme dark|light",handler:t=>this.cmdTheme(t)}),this.commands.set(".examples",{name:".examples",description:"Show example queries",handler:()=>this.cmdExamples()}),this.commands.set(".files",{name:".files",description:"Manage loaded files",usage:".files [list|add|remove <name|index>]",handler:t=>this.cmdFiles(t)}),this.commands.set(".open",{name:".open",description:"Open a file picker to load files",handler:()=>this.cmdOpen()}),this.commands.set(".copy",{name:".copy",description:"Copy last result to clipboard",handler:async()=>{await this.copyLastResult()}}),this.commands.set(".download",{name:".download",description:"Download last result as file",usage:".download [filename]",handler:t=>this.cmdDownload(t)}),this.commands.set(".highlight",{name:".highlight",description:"Toggle syntax highlighting",usage:".highlight on|off",handler:t=>this.cmdHighlight(t)}),this.commands.set(".links",{name:".links",description:"Toggle clickable URL detection",usage:".links on|off",handler:t=>this.cmdLinks(t)}),this.commands.set(".pagesize",{name:".pagesize",description:"Enable pagination for large results (default: off)",usage:".pagesize <number> (0 = disabled)",handler:t=>this.cmdPageSize(t)}),this.commands.set(".reset",{name:".reset",description:"Reset database and all settings to defaults",handler:()=>this.cmdReset()}),this.commands.set(".prompt",{name:".prompt",description:"Get or set the command prompt",usage:".prompt [primary [continuation]]",handler:t=>this.cmdPrompt(t)}),this.commands.set(".chart",{name:".chart",description:"Show chart of last query result",usage:".chart [type=line|bar|scatter|histogram] [x=col] [y=col,...]",handler:t=>this.cmdChart(t)}),this.commands.set(".clearhistory",{name:".clearhistory",description:"Clear command history",handler:()=>this.cmdClearHistory()}),this.commands.set(".share",{name:".share",description:"Open sharing modal to share queries",handler:()=>this.openSharingModal()}),this.commands.set(".ai",{name:".ai",description:"AI-powered natural language to SQL",usage:".ai query <question> | .ai provider list|set <name> | .ai endpoint get|set <url>",handler:t=>this.cmdAI(t)})}showPrompt(){const t=this.state==="collecting"?this.continuationPrompt:this.prompt;this.inputBuffer.setPromptLength(be(t)),this.write(d(t,C)),this.state!=="collecting"&&this.setState("idle")}handleResize(t){const e=this.inputBuffer.getTerminalWidth(),i=this.inputBuffer.getContent();if(t===e||i.length===0||this.state==="executing"){this.inputBuffer.setTerminalWidth(t);return}const r=this.inputBuffer.getCursorPosition(),n=this.inputBuffer.getEndPosition();this.inputBuffer.setTerminalWidth(t),this.redrawInputLine(r,n)}redrawInputLine(t,e){const i=this.inputBuffer.getContent(),r=this.inputBuffer.getCursorPosition(),n=this.inputBuffer.getEndPosition();let o="";o+=`\r
|
|
303
|
+
</svg>`:""),e.selected?i.classList.add("selected"):i.classList.remove("selected")}updateFooter(){if(!this.footerContainer)return;const t=this.footerContainer.querySelector(".sharing-char-count"),e=this.footerContainer.querySelector(".duckdb-sharing-copy-btn"),i=this.getCurrentURLLength(),r=this.selectedIndices.size;t&&(t.textContent=`${i} / ${this.config.maxUrlLength} characters`,i>this.config.maxUrlLength*.9?t.style.color="#dc3545":i>this.config.maxUrlLength*.7?t.style.color="#ffc107":t.style.color="var(--modal-text-dim, #858585)"),e&&(e.disabled=r===0,e.textContent=r>0?`Copy shareable link (${r} ${r===1?"query":"queries"})`:"Copy shareable link")}updateFocusedItem(){if(!this.queryListContainer)return;if(this.queryListContainer.querySelectorAll(".duckdb-sharing-query-item").forEach(e=>e.classList.remove("focused")),this.focusedIndex>=0){const e=this.queryListContainer.querySelector(`[data-index="${this.focusedIndex}"]`);e&&(e.classList.add("focused"),e.scrollIntoView({block:"nearest"}))}}async copyAndClose(){const t=this.getSelectedQueries();if(t.length===0)return;const{url:e}=j(t);await Z(e)&&(this.events.onCopy?.(e),await this.hide())}destroyOverlay(){this.removeKeyboardHandler(),this.removeClickHandler(),this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.modalContainer=null,this.queryListContainer=null,this.footerContainer=null,this.displayedQueries=[],this.selectedIndices.clear()}setupKeyboardHandler(){this.keyHandler=t=>{if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.hide(),this.events.onDismiss?.();return}if(t.key==="Enter"&&this.selectedIndices.size>0){t.preventDefault(),t.stopPropagation(),this.copyAndClose();return}if(t.key===" "&&this.focusedIndex>=0){t.preventDefault(),t.stopPropagation(),this.toggleSelection(this.focusedIndex);return}if(t.key==="ArrowDown"){t.preventDefault(),t.stopPropagation(),this.moveFocusDown();return}if(t.key==="ArrowUp"){t.preventDefault(),t.stopPropagation(),this.moveFocusUp();return}},document.addEventListener("keydown",this.keyHandler,!0)}moveFocusDown(){if(this.displayedQueries.length===0)return;const t=this.focusedIndex-1;t>=0&&(this.focusedIndex=t,this.updateFocusedItem())}moveFocusUp(){if(this.displayedQueries.length===0)return;const t=this.focusedIndex+1;t<this.displayedQueries.length?(this.focusedIndex=t,this.updateFocusedItem()):this.hasMoreQueries()&&(this.loadMoreQueries(),this.focusedIndex=this.displayedQueries.length-1,this.updateFocusedItem())}removeKeyboardHandler(){this.keyHandler&&(document.removeEventListener("keydown",this.keyHandler,!0),this.keyHandler=null)}setupClickHandler(){this.clickHandler=t=>{t.target===this.overlay&&(t.preventDefault(),t.stopPropagation(),this.hide(),this.events.onDismiss?.())},this.overlay?.addEventListener("click",this.clickHandler)}removeClickHandler(){this.clickHandler&&this.overlay&&this.overlay.removeEventListener("click",this.clickHandler),this.clickHandler=null}}const ki={background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selection:"#264f78",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#ffffff"},Ii={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",selection:"#add6ff",black:"#000000",red:"#cd3131",green:"#008000",yellow:"#795e00",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},jt={name:"dark",colors:ki},Wt={name:"light",colors:Ii};function ot(s){return s==="light"?Wt:jt}function Gt(){try{const s=localStorage.getItem("duckdb-terminal-theme");if(s==="light"||s==="dark")return s}catch{}return"dark"}function Vt(s){try{localStorage.setItem("duckdb-terminal-theme",s)}catch{}}const at="duckdb-terminal-ai-settings",lt="http://localhost:4000",ct="claude";function ht(){return lt}function Yt(){return ct}function ut(){try{const s=localStorage.getItem(at);if(s){const t=JSON.parse(s);return{endpoint:t.endpoint||lt,provider:t.provider||ct}}}catch{}return{endpoint:lt,provider:ct}}function W(s){try{const e={...ut(),...s};localStorage.setItem(at,JSON.stringify(e))}catch{}}function $i(){try{localStorage.removeItem(at)}catch{}}class I extends Error{constructor(t,e,i){super(t),this.statusCode=e,this.endpoint=i,this.name="AIClientError"}}function dt(s){return s.replace(/\/$/,"")}async function it(s){const t=`${dt(s)}/providers`;try{return(await fetch(t,{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function ft(s){const t=`${dt(s)}/providers`;try{const e=await fetch(t,{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)throw new I(`Failed to fetch providers: ${e.statusText}`,e.status,t);return(await e.json()).providers||[]}catch(e){throw e instanceof I?e:new I(`Network error connecting to ${t}: ${e instanceof Error?e.message:"Unknown error"}`,void 0,t)}}async function Kt(s,t,e,i){const r=`${dt(s)}/generate-sql`,n={ddl:t,question:e};i&&(n.provider=i);try{const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!o.ok){const l=await o.text().catch(()=>o.statusText);throw new I(`Failed to generate SQL: ${l}`,o.status,r)}return(await o.json()).sql}catch(o){throw o instanceof I?o:new I(`Network error connecting to ${r}: ${o instanceof Error?o.message:"Unknown error"}`,void 0,r)}}const Xt="🦆 ",Jt=" > ";class Zt{constructor(t){h(this,"terminalAdapter");h(this,"database");h(this,"inputBuffer");h(this,"history");h(this,"state","idle");h(this,"collectedSQL",[]);h(this,"commands",new Map);h(this,"showTimer",!1);h(this,"outputMode","table");h(this,"currentThemeName");h(this,"customTheme",null);h(this,"config");h(this,"loadedFiles",new Map);h(this,"syntaxHighlighting",!0);h(this,"lastQueryResult",null);h(this,"linkProvider");h(this,"chartManager",null);h(this,"sharingModal",null);h(this,"eventListeners",new Map);h(this,"pageSize",0);h(this,"paginationQuery",null);h(this,"currentPage",0);h(this,"totalRows",0);h(this,"prompt");h(this,"continuationPrompt");h(this,"debouncedHighlight",Ne(()=>this.redrawLineHighlighted(),150));h(this,"queryQueue",Promise.resolve(null));h(this,"dragDropCleanup",null);h(this,"aiSettingsLoaded",!1);h(this,"aiEndpoint","http://localhost:4000");h(this,"aiProvider","claude");this.config=t,this.terminalAdapter=new pt,this.database=new gt({storage:t.storage??"memory",databasePath:t.databasePath}),this.inputBuffer=new Ct,this.history=new vt,this.linkProvider=new At,t.linkDetection===!1&&this.linkProvider.setEnabled(!1),this.prompt=t.prompt??Xt,this.continuationPrompt=t.continuationPrompt??Jt,typeof t.theme=="object"?(this.customTheme=t.theme,this.currentThemeName="custom"):this.currentThemeName=t.theme??Gt(),this.registerCommands()}on(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t).add(e),()=>this.off(t,e)}off(t,e){this.eventListeners.get(t)?.delete(e)}emit(t,e){this.eventListeners.get(t)?.forEach(i=>{try{i(e)}catch(r){console.error(`Error in ${t} event listener:`,r)}})}setState(t){const e=this.state;e!==t&&(this.state=t,this.emit("stateChange",{state:t,previous:e}))}async getHighlightedSQLAsync(t){if(!this.syntaxHighlighting)return t;if(this.database.isPoachedLoaded()){const e=await this.database.tokenizeSQL(t);if(e)return tt(t,e)}return t}async redrawLineHighlighted(){if(!this.syntaxHighlighting)return;const t=this.inputBuffer.getContent();if(t.length===0)return;const e=this.inputBuffer.getCursorPosition(),i=this.inputBuffer.getEndPosition();let r;if(this.database.isPoachedLoaded()){const c=await this.database.tokenizeSQL(t);c?r=tt(t,c):r=t}else r=t;if(t!==this.inputBuffer.getContent())return;const n={col:this.inputBuffer.getPromptLength()};let o="";e.row>0&&(o+=U(e.row)),o+=L(n.col+1),this.write(o),this.write(E);for(let c=1;c<=i.row;c++)this.write(R(1)),this.write(L(1)),this.write(E);i.row>0&&this.write(U(i.row)),this.write(L(n.col+1)),this.write(r);const a=this.inputBuffer.getEndPosition();let l="";a.row>e.row&&(l+=U(a.row-e.row)),l+=L(e.col+1),this.write(l)}getCurrentThemeObject(){return this.customTheme?this.customTheme:ot(this.currentThemeName)}async start(){const t=this.resolveContainer();await this.terminalAdapter.init(t,{fontFamily:this.config.fontFamily,fontSize:this.config.fontSize,theme:this.getCurrentThemeObject(),scrollback:this.config.scrollback}),this.config.welcomeMessage!==!1&&(this.write(pe),this.writeln(""),this.writeln(P("DuckDB Terminal")+" v0.5.1"),this.write(d("Loading DuckDB WASM...",x))),await Promise.all([this.database.init(),this.history.init()]),await this.database.loadPoachedExtension(),this.config.welcomeMessage!==!1&&(this.write(ge),this.write("\r"+E),this.writeln(d("Powered by DuckDB WASM and Ghostty",x)),this.writeln(""),this.writeln("Type "+d(".help",T)+" for available commands"),this.writeln("Enter SQL statements ending with "+d(";",D)),this.writeln("")),this.terminalAdapter.onData(this.handleInput.bind(this)),this.inputBuffer.setTerminalWidth(this.terminalAdapter.cols),this.terminalAdapter.onResize(e=>{this.handleResize(e)}),this.dragDropCleanup=$e(t,e=>{this.handleDroppedFiles(e)}),this.showPrompt(),this.emit("ready",{})}destroy(){this.dragDropCleanup&&(this.dragDropCleanup(),this.dragDropCleanup=null),this.chartManager&&(this.chartManager.destroy(),this.chartManager=null),this.sharingModal&&(this.sharingModal.destroy(),this.sharingModal=null),this.eventListeners.clear(),this.debouncedHighlight.cancel()}openSharingModal(){if(this.state==="executing")return;if(!this.sharingModal){const i=this.resolveContainer();this.sharingModal=new qt(i,{},{maxUrlLength:2e3,initialQueryCount:5,loadMoreCount:5})}const e=this.history.getAll().filter(i=>!i.trim().startsWith("."));this.sharingModal.show(e)}async handleDroppedFiles(t){const e=await Promise.allSettled(t.map(n=>this.loadFile(n))),i=e.filter(n=>n.status==="fulfilled"&&n.value).length,r=e.length-i;r>0&&i>0&&this.writeln(p(`Loaded ${i} of ${e.length} files (${r} failed)`)),this.showPrompt()}async loadFile(t){const e=Pt(t.name),i=ke(t);try{const r=await Pe(t);await this.database.registerFile(t.name,r),this.loadedFiles.set(t.name,i),this.emit("fileLoaded",{filename:t.name,size:t.size,type:e}),this.writeln(""),this.writeln(d(`Loaded: ${t.name}`,C)+` (${z(t.size)})`);const n=t.name.replace(/'/g,"''");if(e==="csv"){const o=t.name.replace(/\.[^.]+$/,"").replace(/[^a-zA-Z0-9_]/g,"_");this.writeln(p(`Hint: SELECT * FROM read_csv('${n}');`)),this.writeln(p(` or: CREATE TABLE ${o} AS SELECT * FROM read_csv('${n}');`))}else e==="parquet"?this.writeln(p(`Hint: SELECT * FROM read_parquet('${n}');`)):e==="json"&&this.writeln(p(`Hint: SELECT * FROM read_json('${n}');`));return!0}catch(r){const n=r instanceof Error?r.message:String(r);return this.writeln(d(`Error loading ${t.name}: ${n}`,y)),!1}}resolveContainer(){if(typeof this.config.container=="string"){const t=document.querySelector(this.config.container);if(!t)throw new Error(`Container not found: ${this.config.container}`);return t}return this.config.container}registerCommands(){this.commands.set(".help",{name:".help",description:"Show available commands",handler:()=>this.cmdHelp()}),this.commands.set(".clear",{name:".clear",description:"Clear the terminal",handler:()=>this.clear()}),this.commands.set(".tables",{name:".tables",description:"List all tables",handler:()=>this.cmdTables()}),this.commands.set(".schema",{name:".schema",description:"Show table schema",usage:".schema <table_name>",handler:t=>this.cmdSchema(t)}),this.commands.set(".timer",{name:".timer",description:"Toggle query timing",usage:".timer on|off",handler:t=>this.cmdTimer(t)}),this.commands.set(".mode",{name:".mode",description:"Set output mode",usage:".mode table|csv|tsv|json",handler:t=>this.cmdMode(t)}),this.commands.set(".theme",{name:".theme",description:"Set color theme (clears screen)",usage:".theme dark|light",handler:t=>this.cmdTheme(t)}),this.commands.set(".examples",{name:".examples",description:"Show example queries",handler:()=>this.cmdExamples()}),this.commands.set(".files",{name:".files",description:"Manage loaded files",usage:".files [list|add|remove <name|index>]",handler:t=>this.cmdFiles(t)}),this.commands.set(".open",{name:".open",description:"Open a file picker to load files",handler:()=>this.cmdOpen()}),this.commands.set(".copy",{name:".copy",description:"Copy last result to clipboard",handler:async()=>{await this.copyLastResult()}}),this.commands.set(".download",{name:".download",description:"Download last result as file",usage:".download [filename]",handler:t=>this.cmdDownload(t)}),this.commands.set(".highlight",{name:".highlight",description:"Toggle syntax highlighting",usage:".highlight on|off",handler:t=>this.cmdHighlight(t)}),this.commands.set(".links",{name:".links",description:"Toggle clickable URL detection",usage:".links on|off",handler:t=>this.cmdLinks(t)}),this.commands.set(".pagesize",{name:".pagesize",description:"Enable pagination for large results (default: off)",usage:".pagesize <number> (0 = disabled)",handler:t=>this.cmdPageSize(t)}),this.commands.set(".reset",{name:".reset",description:"Reset database and all settings to defaults",handler:()=>this.cmdReset()}),this.commands.set(".prompt",{name:".prompt",description:"Get or set the command prompt",usage:".prompt [primary [continuation]]",handler:t=>this.cmdPrompt(t)}),this.commands.set(".chart",{name:".chart",description:"Show chart of last query result",usage:".chart [type=line|bar|scatter|histogram] [x=col] [y=col,...]",handler:t=>this.cmdChart(t)}),this.commands.set(".clearhistory",{name:".clearhistory",description:"Clear command history",handler:()=>this.cmdClearHistory()}),this.commands.set(".share",{name:".share",description:"Open sharing modal to share queries",handler:()=>this.openSharingModal()}),this.commands.set(".ai",{name:".ai",description:"AI-powered natural language to SQL",usage:".ai query <question> | .ai provider list|set <name> | .ai endpoint get|set <url>",handler:t=>this.cmdAI(t)})}showPrompt(){const t=this.state==="collecting"?this.continuationPrompt:this.prompt;this.inputBuffer.setPromptLength(be(t)),this.write(d(t,C)),this.state!=="collecting"&&this.setState("idle")}handleResize(t){const e=this.inputBuffer.getTerminalWidth(),i=this.inputBuffer.getContent();if(t===e||i.length===0||this.state==="executing"){this.inputBuffer.setTerminalWidth(t);return}const r=this.inputBuffer.getCursorPosition(),n=this.inputBuffer.getEndPosition();this.inputBuffer.setTerminalWidth(t),this.redrawInputLine(r,n)}redrawInputLine(t,e){const i=this.inputBuffer.getContent(),r=this.inputBuffer.getCursorPosition(),n=this.inputBuffer.getEndPosition();let o="";o+=`\r
|
|
304
304
|
`;const a=this.state==="collecting"?this.continuationPrompt:this.prompt;o+=d(a,C),o+=i,n.row>r.row&&(o+=U(n.row-r.row)),o+=L(r.col+1),this.write(o)}handleInput(t){if(this.state!=="executing"){if(this.state==="paginating"){this.handlePaginationInput(t);return}if(t.startsWith("\x1B[")){this.handleEscapeSequence(t);return}for(const e of t)this.handleChar(e)}}async handlePaginationInput(t){const e=Math.ceil(this.totalRows/this.pageSize),i=t.toLowerCase();if(i==="n"||t==="\x1B[B"){this.currentPage<e-1?(this.currentPage++,await this.executePaginatedQuery()):this.writeln(p("Already on last page"));return}if(i==="p"||t==="\x1B[A"){this.currentPage>0?(this.currentPage--,await this.executePaginatedQuery()):this.writeln(p("Already on first page"));return}if(i==="q"||i==="\x1B"||i===""){this.writeln(""),this.exitPagination(),this.writeln(""),this.showPrompt();return}if(i==="\r"||i===`
|
|
305
305
|
`){const r=this.inputBuffer.getContent().trim();if(r){const n=parseInt(r,10);!isNaN(n)&&n>=1&&n<=e?(this.currentPage=n-1,this.inputBuffer.clear(),await this.executePaginatedQuery()):(this.writeln(d(`Invalid page number. Enter 1-${e}`,y)),this.inputBuffer.clear())}return}if(/^\d$/.test(i)){this.write(this.inputBuffer.insert(i));return}if(i===""||i==="\b"){this.write(this.inputBuffer.backspace());return}}handleChar(t){const e=t.charCodeAt(0);switch(t){case"\r":case`
|
|
306
|
-
`:this.handleEnter();return;case"":case"\b":this.write(this.inputBuffer.backspace());return;case"\x1B":return;case" ":this.handleTab();return;case"":this.handleCtrlC();return;case"":this.handlePaste();return;case"":this.write(this.inputBuffer.moveToStart());return;case"":this.write(this.inputBuffer.moveToEnd());return;case"\v":this.write(this.inputBuffer.clearToEnd());return;case"":this.write(this.inputBuffer.clearLine());return}t!=="\x1B"&&(e>=32&&e<127?(this.write(this.inputBuffer.insert(t)),this.isHighlightTrigger(t)&&this.debouncedHighlight()):e>=128&&this.write(this.inputBuffer.insert(t)))}isHighlightTrigger(t){return t===" "||t===";"||t==="("||t===")"||t===","}handleEscapeSequence(t){switch(t){case"\x1B[A":this.handleArrowUp();break;case"\x1B[B":this.handleArrowDown();break;case"\x1B[C":this.write(this.inputBuffer.moveRight());break;case"\x1B[D":this.write(this.inputBuffer.moveLeft());break;case"\x1B[H":this.write(this.inputBuffer.moveToStart());break;case"\x1B[F":this.write(this.inputBuffer.moveToEnd());break;case"\x1B[3~":this.write(this.inputBuffer.delete());break}}async handleEnter(){const t=this.inputBuffer.getContent();if(this.writeln(""),t.trim()===""&&this.state!=="collecting"){this.showPrompt();return}if(t.trim().startsWith(".")&&this.state!=="collecting"){this.writeln("")
|
|
306
|
+
`:this.handleEnter();return;case"":case"\b":this.write(this.inputBuffer.backspace());return;case"\x1B":return;case" ":this.handleTab();return;case"":this.handleCtrlC();return;case"":this.handlePaste();return;case"":this.write(this.inputBuffer.moveToStart());return;case"":this.write(this.inputBuffer.moveToEnd());return;case"\v":this.write(this.inputBuffer.clearToEnd());return;case"":this.write(this.inputBuffer.clearLine());return}t!=="\x1B"&&(e>=32&&e<127?(this.write(this.inputBuffer.insert(t)),this.isHighlightTrigger(t)&&this.debouncedHighlight()):e>=128&&this.write(this.inputBuffer.insert(t)))}isHighlightTrigger(t){return t===" "||t===";"||t==="("||t===")"||t===","}handleEscapeSequence(t){switch(t){case"\x1B[A":this.handleArrowUp();break;case"\x1B[B":this.handleArrowDown();break;case"\x1B[C":this.write(this.inputBuffer.moveRight());break;case"\x1B[D":this.write(this.inputBuffer.moveLeft());break;case"\x1B[H":this.write(this.inputBuffer.moveToStart());break;case"\x1B[F":this.write(this.inputBuffer.moveToEnd());break;case"\x1B[3~":this.write(this.inputBuffer.delete());break}}async handleEnter(){const t=this.inputBuffer.getContent();if(this.writeln(""),t.trim()===""&&this.state!=="collecting"){this.showPrompt();return}if(t.trim().startsWith(".")&&this.state!=="collecting"){this.writeln("");const r=this.history.add(t.trim());await this.executeCommand(t.trim()),await r,this.inputBuffer.clear(),this.writeln(""),this.showPrompt();return}this.collectedSQL.push(t);const e=this.collectedSQL.join(`
|
|
307
307
|
`).trim(),i=It(e);if(i){const r=e.replace(/\s*\n\s*/g," ").trim();if(await this.history.add(r),this.database.isPoachedLoaded()){const n=await this.database.validateSQL(e);if(n&&!n.isValid&&n.error?.exceptionMessage){this.writeln(""),this.writeln(d("Error: ",y)+n.error.exceptionMessage),this.collectedSQL=[],this.setState("idle"),this.inputBuffer.clear(),this.writeln(""),this.showPrompt();return}}this.writeln(""),await this.executeSQL(e),this.collectedSQL=[],this.state!=="paginating"&&this.setState("idle")}else this.setState("collecting");this.inputBuffer.clear(),this.state!=="paginating"&&(i&&this.writeln(""),this.showPrompt())}handleArrowUp(){const t=this.history.previous(this.inputBuffer.getContent());t!==null&&(this.write(this.inputBuffer.clearLine()),this.inputBuffer.setContent(t),this.write(t),this.syntaxHighlighting&&this.redrawLineHighlighted())}handleArrowDown(){const t=this.history.next();t!==null&&(this.write(this.inputBuffer.clearLine()),this.inputBuffer.setContent(t),this.write(t),this.syntaxHighlighting&&this.redrawLineHighlighted())}async handleTab(){const t=this.inputBuffer.getContent(),e=this.inputBuffer.getCursorPos(),i=await this.database.getCompletions(t,e);if(i.length!==0)if(i.length===1)this.write(this.inputBuffer.replaceWordBeforeCursor(i[0].value)),this.redrawLineHighlighted();else{this.writeln("");const r=i.map(l=>{const c=l.type==="keyword"?K:l.type==="table"?C:l.type==="function"?D:X;return d(l.value,c)}).join(" ");this.writeln(r);const n=this.findCommonPrefix(i.map(l=>l.value)),o=this.inputBuffer.getWordBeforeCursor();n.length>o.length&&this.write(this.inputBuffer.replaceWordBeforeCursor(n));const a=this.state==="collecting"?this.continuationPrompt:this.prompt;this.write(d(a,C)),this.write(this.inputBuffer.getContent()),this.syntaxHighlighting&&this.redrawLineHighlighted()}}findCommonPrefix(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=t[0];for(let i=1;i<t.length;i++)for(;!t[i].toLowerCase().startsWith(e.toLowerCase());)if(e=e.slice(0,-1),e==="")return"";return e}handleCtrlC(){this.writeln("^C"),this.inputBuffer.clear(),this.collectedSQL=[],this.setState("idle"),this.showPrompt()}async handlePaste(){const t=await kt();if(t)for(const e of t)e===`
|
|
308
308
|
`||e==="\r"||this.write(this.inputBuffer.insert(e))}async copyLastResult(){if(!this.lastQueryResult)return this.writeln(p("No query result to copy")),!1;let t;switch(this.outputMode){case"csv":t=Q(this.lastQueryResult.columns,this.lastQueryResult.rows);break;case"tsv":t=H(this.lastQueryResult.columns,this.lastQueryResult.rows);break;case"json":t=_(this.lastQueryResult.columns,this.lastQueryResult.rows);break;default:t=F(this.lastQueryResult.columns,this.lastQueryResult.rows)}const e=await Z(t);return e?this.writeln(d("Result copied to clipboard",C)):this.writeln(d("Failed to copy to clipboard",y)),e}cmdDownload(t){if(!this.lastQueryResult){this.writeln(p("No query result to download"));return}let e,i,r;switch(this.outputMode){case"csv":e=Q(this.lastQueryResult.columns,this.lastQueryResult.rows),i=".csv",r="text/csv";break;case"tsv":e=H(this.lastQueryResult.columns,this.lastQueryResult.rows),i=".tsv",r="text/tab-separated-values";break;case"json":e=_(this.lastQueryResult.columns,this.lastQueryResult.rows),i=".json",r="application/json";break;default:e=F(this.lastQueryResult.columns,this.lastQueryResult.rows),i=".txt",r="text/plain"}const n=this.generateDownloadFilename(t[0],i);Ie(e,n,r),this.writeln(d(`Downloaded: ${n}`,C))}generateDownloadFilename(t,e){if(t)return t.endsWith(e)?t:t+e;const i=new Date,r=i.getFullYear(),n=String(i.getMonth()+1).padStart(2,"0"),o=String(i.getDate()).padStart(2,"0"),a=String(i.getHours()).padStart(2,"0"),l=String(i.getMinutes()).padStart(2,"0"),c=String(i.getSeconds()).padStart(2,"0");return`duckdb-result-${r}-${n}-${o}-${a}${l}${c}${e}`}async executeCommand(t){const{command:e,args:i}=Be(t),r=this.commands.get(e);if(!r){this.writeln(d(`Unknown command: ${e}`,y)),this.writeln("Type .help for available commands"),this.emit("error",{message:`Unknown command: ${e}`,source:"command"});return}this.emit("commandExecute",{command:e,args:i});try{await r.handler(i,this)}catch(n){const o=n instanceof Error?n.message:String(n);this.writeln(d(`Error: ${o}`,y)),this.emit("error",{message:o,source:"command"})}}async executeSQL(t){const e=this.queryQueue.then(()=>this.executeSQLInternal(t));return this.queryQueue=e.catch(()=>null),e}async highlightSQL(t){if(this.database.isPoachedLoaded()){const e=await this.database.tokenizeSQL(t);if(e)return tt(t,e)}return t}async executeSQLInternal(t){this.setState("executing");const e=performance.now();this.emit("queryStart",{sql:t});try{const i=t.replace(/\s*\n\s*/g," ").trim();await this.history.add(i);const r=t.trim().replace(/;+$/,""),n=/^\s*SELECT\s/i.test(r),o=/\b(LIMIT|OFFSET)\b/i.test(r);if(this.pageSize>0&&n&&!o){const c=`SELECT COUNT(*) as cnt FROM (${r}) AS _count_subquery`,u=(await this.database.executeQuery(c)).rows[0]?.[0],g=typeof u=="bigint"?Number(u):u??0;if(g>this.pageSize)return this.paginationQuery=r,this.totalRows=g,this.currentPage=0,await this.executePaginatedQuery()}const a=await this.database.executeQuery(t),l=performance.now()-e;return this.lastQueryResult=a,a.columns.length>0&&this.displayResult(a),this.showTimer&&this.writeln(p(`Time: ${a.duration.toFixed(2)}ms`)),this.emit("queryEnd",{sql:t,result:a,duration:l}),a}catch(i){const r=i instanceof Error?i.message:String(i),n=performance.now()-e,o=r.split(`
|
|
309
309
|
|