import{a as x,b as w}from"./chunk-ZK6J6F7O.js";import{c as b}from"./chunk-T2EHE3CV.js";import{b as E}from"./chunk-3RCXHB4E.js";import{a as m}from"./chunk-CCNMISUL.js";import{a as T,b as C}from"./chunk-74CEPOFO.js";import{existsSync as k}from"node:fs";import{dirname as _,join as q}from"node:path";import{fileURLToPath as z}from"node:url";import{Worker as X}from"node:worker_threads";import Y from"sql.js";function V(e,r,n){switch(n.mode){case"list":return B(e,r,n);case"csv":return O(e,r,n);case"json":return N(e,r);case"line":return P(e,r,n);case"column":return R(e,r,n);case"table":return F(e,r,n);case"markdown":return Q(e,r,n);case"tabs":return U(e,r,n);case"box":return D(e,r,n);case"quote":return W(e,r,n);case"html":return H(e,r,n);case"ascii":return J(e,r,n)}}function f(e,r){return e==null?r:e instanceof Uint8Array||Buffer.isBuffer(e)?Buffer.from(e).toString("utf8"):typeof e=="number"&&!Number.isInteger(e)?e.toPrecision(17).replace(/\.?0+$/,""):String(e)}function B(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.join(n.separator));for(let a of r)t.push(a.map(o=>f(o,n.nullValue)).join(n.separator));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function O(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.map(L).join(","));for(let a of r)t.push(a.map(o=>L(f(o,n.nullValue))).join(","));return t.length>0?`${t.join(`
`)}
`:""}function L(e){return e.includes(",")||e.includes('"')||e.includes("'")||e.includes(`
`)?`"${e.replace(/"/g,'""')}"`:e}function A(e){return e.toPrecision(17).replace(/\.?0+$/,"")}function I(e){return e===null?"null":typeof e=="number"?Number.isInteger(e)?String(e):A(e):JSON.stringify(e)}function N(e,r){return r.length===0?"":`[${r.map(t=>`{${e.map((o,i)=>`${JSON.stringify(o)}:${I(t[i])}`).join(",")}}`).join(`,
`)}]
`}function P(e,r,n){if(e.length===0||r.length===0)return"";let t=Math.max(5,...e.map(o=>o.length)),a=[];for(let o of r)for(let i=0;i<e.length;i++){let s=e[i].padStart(t);a.push(`${s} = ${f(o[i],n.nullValue)}`)}return`${a.join(`
`)}
`}function R(e,r,n){if(e.length===0)return"";let t=e.map(o=>o.length);for(let o of r)for(let i=0;i<o.length;i++){let s=f(o[i],n.nullValue).length;s>t[i]&&(t[i]=s)}let a=[];n.header&&(a.push(e.map((o,i)=>o.padEnd(t[i])).join("  ")),a.push(t.map(o=>"-".repeat(o)).join("  ")));for(let o of r)a.push(o.map((i,s)=>f(i,n.nullValue).padEnd(t[s])).join("  "));return a.length>0?`${a.join(`
`)}
`:""}function F(e,r,n){if(e.length===0)return"";let t=e.map(i=>i.length);for(let i of r)for(let s=0;s<i.length;s++){let h=f(i[s],n.nullValue).length;h>t[s]&&(t[s]=h)}let a=[],o=`+${t.map(i=>"-".repeat(i+2)).join("+")}+`;a.push(o),n.header&&(a.push(`| ${e.map((i,s)=>i.padEnd(t[s])).join(" | ")} |`),a.push(o));for(let i of r)a.push(`| ${i.map((s,h)=>f(s,n.nullValue).padEnd(t[h])).join(" | ")} |`);return a.push(o),`${a.join(`
`)}
`}function Q(e,r,n){if(e.length===0)return"";let t=[];n.header&&(t.push(`| ${e.join(" | ")} |`),t.push(`|${e.map(()=>"---").join("|")}|`));for(let a of r)t.push(`| ${a.map(o=>f(o,n.nullValue)).join(" | ")} |`);return t.length>0?`${t.join(`
`)}
`:""}function U(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.join("	"));for(let a of r)t.push(a.map(o=>f(o,n.nullValue)).join("	"));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function D(e,r,n){if(e.length===0)return"";let t=e.map(o=>o.length);for(let o of r)for(let i=0;i<o.length;i++){let s=f(o[i],n.nullValue).length;s>t[i]&&(t[i]=s)}let a=[];a.push(`\u250C${t.map(o=>"\u2500".repeat(o+2)).join("\u252C")}\u2510`),a.push(`\u2502 ${e.map((o,i)=>o.padEnd(t[i])).join(" \u2502 ")} \u2502`),a.push(`\u251C${t.map(o=>"\u2500".repeat(o+2)).join("\u253C")}\u2524`);for(let o of r)a.push(`\u2502 ${o.map((i,s)=>f(i,n.nullValue).padEnd(t[s])).join(" \u2502 ")} \u2502`);return a.push(`\u2514${t.map(o=>"\u2500".repeat(o+2)).join("\u2534")}\u2518`),`${a.join(`
`)}
`}function W(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.map(a=>`'${a}'`).join(","));for(let a of r)t.push(a.map(o=>o==null?"NULL":typeof o=="number"?Number.isInteger(o)?String(o):A(o):`'${String(o)}'`).join(","));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function H(e,r,n){let t=[];n.header&&e.length>0&&(t.push(`<TR>${e.map(a=>`<TH>${M(a)}</TH>`).join("")}`),t.push("</TR>"));for(let a of r)t.push(`<TR>${a.map(o=>`<TD>${M(f(o,n.nullValue))}</TD>`).join("")}`),t.push("</TR>");return t.length>0?`${t.join(`
`)}
`:""}function M(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function J(e,r,n){let o=[];n.header&&e.length>0&&o.push(e.join(""));for(let i of r)o.push(i.map(s=>f(s,n.nullValue)).join(""));return o.length>0?o.join("")+"":""}var G=5e3,K={name:"sqlite3",summary:"SQLite database CLI",usage:"sqlite3 [OPTIONS] DATABASE [SQL]",options:["-list           output in list mode (default)","-csv            output in CSV mode","-json           output in JSON mode","-line           output in line mode","-column         output in column mode","-table          output as ASCII table","-markdown       output as markdown table","-tabs           output in tab-separated mode","-box            output in Unicode box mode","-quote          output in SQL quote mode","-html           output as HTML table","-ascii          output in ASCII mode (control chars)","-header         show column headers","-noheader       hide column headers","-separator SEP  field separator for list mode (default: |)","-newline SEP    row separator (default: \\n)","-nullvalue TEXT text for NULL values (default: empty)","-readonly       open database read-only (no writeback)","-bail           stop on first error","-echo           print SQL before execution","-cmd COMMAND    run SQL command before main SQL","-version        show SQLite version","--              end of options","--help          show this help"],examples:['sqlite3 :memory: "CREATE TABLE t(x); INSERT INTO t VALUES(1); SELECT * FROM t"','sqlite3 -json data.db "SELECT * FROM users"','sqlite3 -csv -header data.db "SELECT id, name FROM products"','sqlite3 -box data.db "SELECT * FROM users"']};function Z(e){let r={mode:"list",header:!1,separator:"|",newline:`
`,nullValue:"",readonly:!1,bail:!1,echo:!1,cmd:null},n=null,t=null,a=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(o){n===null?n=s:t===null&&(t=s);continue}if(s==="--")o=!0;else if(s==="-version")a=!0;else if(s==="-list")r.mode="list";else if(s==="-csv")r.mode="csv";else if(s==="-json")r.mode="json";else if(s==="-line")r.mode="line";else if(s==="-column")r.mode="column";else if(s==="-table")r.mode="table";else if(s==="-markdown")r.mode="markdown";else if(s==="-tabs")r.mode="tabs";else if(s==="-box")r.mode="box";else if(s==="-quote")r.mode="quote";else if(s==="-html")r.mode="html";else if(s==="-ascii")r.mode="ascii";else if(s==="-header")r.header=!0;else if(s==="-noheader")r.header=!1;else if(s==="-readonly")r.readonly=!0;else if(s==="-bail")r.bail=!0;else if(s==="-echo")r.echo=!0;else if(s==="-separator"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -separator
`,exitCode:1};r.separator=e[++i]}else if(s==="-newline"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -newline
`,exitCode:1};r.newline=e[++i]}else if(s==="-nullvalue"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -nullvalue
`,exitCode:1};r.nullValue=e[++i]}else if(s==="-cmd"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
`,exitCode:1};r.cmd=e[++i]}else{if(s.startsWith("-"))return{stdout:"",stderr:`sqlite3: Error: unknown option: ${s.startsWith("--")?s.slice(1):s}
Use -help for a list of options.
`,exitCode:1};n===null?n=s:t===null&&(t=s)}}return{options:r,database:n,sql:t,showVersion:a}}async function v(){let e=await E.runTrustedAsync(()=>Y()),r=new e.Database;try{let n=r.exec("SELECT sqlite_version()");return n.length>0&&n[0].values.length>0?String(n[0].values[0][0]):"unknown"}finally{r.close()}}function ee(){let e=_(z(import.meta.url)),r=q(e,"../../commands/sqlite3/worker.js");if(k(r))return r;let n=q(e,"worker.js");if(k(n))return n;let t=q(e,"../../../dist/commands/sqlite3/worker.js");if(k(t))return t;throw new Error("sqlite3 worker not found. Run 'pnpm build' to compile the worker.")}var re={createWorker(e,r){return new X(e,{workerData:r})}};function te(e){if(!e||typeof e!="object")return{success:!1,error:"Malformed worker response"};let r=e;return r.type==="security-violation"?{success:!1,error:`Security violation: ${typeof r.violation?.type=="string"?r.violation.type:"unknown"}`}:typeof r.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:r.success?Array.isArray(r.results)?typeof r.hasModifications!="boolean"?{success:!1,error:"Malformed worker response: missing hasModifications flag"}:r.dbBuffer!==null&&r.dbBuffer!==void 0&&!(r.dbBuffer instanceof Uint8Array)?{success:!1,error:"Malformed worker response: invalid dbBuffer"}:{success:!0,results:r.results,hasModifications:r.hasModifications,dbBuffer:r.dbBuffer===void 0?null:r.dbBuffer,defenseStats:r.defenseStats}:{success:!1,error:"Malformed worker response: missing results array"}:{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}async function ne(e,r,n){try{let t=ee();return await new Promise((a,o)=>{let i=E.runTrusted(()=>re.createWorker(t,e)),s=b(n,"sqlite3","worker timeout callback",()=>{i.terminate(),a({success:!1,error:`Query timeout: execution exceeded ${r}ms limit`})}),c=x(()=>{try{s()}catch(u){let l=u instanceof Error?u.message:String(u);a({success:!1,error:m(l)})}},r),S=b(n,"sqlite3","worker message callback",u=>{w(c),a(te(u))}),$=b(n,"sqlite3","worker error callback",u=>{w(c),o(u)}),j=b(n,"sqlite3","worker exit callback",u=>{w(c),u!==0&&a({success:!1,error:`Worker exited with code ${u}`})}),p=u=>{try{S(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:m(d)})}},y=u=>{try{$(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);o(new Error(m(d)))}},g=u=>{try{j(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:m(d)})}};i.on("message",p),i.on("error",y),i.on("exit",g)})}catch(t){let a=m(t.message);throw new Error(`sqlite3 worker failed to load: ${a}`)}}var ge={name:"sqlite3",async execute(e,r){if(C(e)||e.includes("-help"))return T(K);let n=Z(e);if("exitCode"in n)return n;let{options:t,database:a,sql:o,showVersion:i}=n;if(i)return{stdout:`${await v()}
`,stderr:"",exitCode:0};if(!a)return{stdout:"",stderr:`sqlite3: missing database argument
`,exitCode:1};let s=o||r.stdin.trim();if(t.cmd&&(s=t.cmd+(s?`; ${s}`:"")),!s)return{stdout:"",stderr:`sqlite3: no SQL provided
`,exitCode:1};let h=a===":memory:",c="",S=null;try{h||(c=r.fs.resolvePath(r.cwd,a),await r.fs.exists(c)&&(S=await r.fs.readFileBuffer(c)))}catch(l){let d=m(l.message);return{stdout:"",stderr:`sqlite3: unable to open database "${a}": ${d}
`,exitCode:1}}let $=r.limits?.maxSqliteTimeoutMs??G,j={dbBuffer:S,sql:s,options:{bail:t.bail,echo:t.echo}},p;try{p=await ne(j,$,r.requireDefenseContext)}catch(l){return{stdout:"",stderr:`sqlite3: worker error: ${m(l.message)}
`,exitCode:1}}if(!p.success)return{stdout:"",stderr:`sqlite3: ${m(p.error)}
`,exitCode:1};let y={mode:t.mode,header:t.header,separator:t.separator,newline:t.newline,nullValue:t.nullValue},g="";t.echo&&(g+=`${s}
`);let u=!1;for(let l of p.results)if(l.type==="error"){if(t.bail)return{stdout:g,stderr:`Error: ${l.error}
`,exitCode:1};g+=`Error: ${l.error}
`,u=!0}else l.columns&&l.rows&&(l.rows.length>0||t.header)&&(g+=V(l.columns,l.rows,y));if(p.hasModifications&&!t.readonly&&!h&&c&&p.dbBuffer)try{await r.fs.writeFile(c,p.dbBuffer)}catch(l){let d=m(l.message);return{stdout:g,stderr:`sqlite3: failed to write database: ${d}
`,exitCode:1}}return{stdout:g,stderr:"",exitCode:u&&t.bail?1:0}}},we={name:"sqlite3",flags:[],needsArgs:!0};export{re as a,ge as b,we as c};
