#!/usr/bin/env node
import{a as q,b as w}from"./chunk-OOJCYVYF.js";import{c as b}from"./chunk-MO4RPBN2.js";import{b as j}from"./chunk-YU6OGPZR.js";import{a as E,b as g}from"./chunk-RLNOQILG.js";import{a as C,b as M}from"./chunk-GTNBSMZR.js";import{randomBytes as z}from"node:crypto";import{existsSync as T}from"node:fs";import{dirname as X,join as x}from"node:path";import{fileURLToPath as Y}from"node:url";import{Worker as G}from"node:worker_threads";import K from"sql.js";function A(e,t,r){switch(r.mode){case"list":return O(e,t,r);case"csv":return P(e,t,r);case"json":return N(e,t);case"line":return R(e,t,r);case"column":return F(e,t,r);case"table":return Q(e,t,r);case"markdown":return U(e,t,r);case"tabs":return W(e,t,r);case"box":return D(e,t,r);case"quote":return H(e,t,r);case"html":return J(e,t,r);case"ascii":return _(e,t,r)}}function f(e,t){return e==null?t: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 O(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.join(r.separator));for(let a of t)n.push(a.map(o=>f(o,r.nullValue)).join(r.separator));return n.length>0?`${n.join(r.newline)}${r.newline}`:""}function P(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.map(L).join(","));for(let a of t)n.push(a.map(o=>L(f(o,r.nullValue))).join(","));return n.length>0?`${n.join(`
`)}
`:""}function L(e){return e.includes(",")||e.includes('"')||e.includes("'")||e.includes(`
`)?`"${e.replace(/"/g,'""')}"`:e}function B(e){return e.toPrecision(17).replace(/\.?0+$/,"")}function I(e){return e===null?"null":typeof e=="number"?Number.isInteger(e)?String(e):B(e):JSON.stringify(e)}function N(e,t){return t.length===0?"":`[${t.map(n=>`{${e.map((o,i)=>`${JSON.stringify(o)}:${I(n[i])}`).join(",")}}`).join(`,
`)}]
`}function R(e,t,r){if(e.length===0||t.length===0)return"";let n=Math.max(5,...e.map(o=>o.length)),a=[];for(let o of t)for(let i=0;i<e.length;i++){let s=e[i].padStart(n);a.push(`${s} = ${f(o[i],r.nullValue)}`)}return`${a.join(`
`)}
`}function F(e,t,r){if(e.length===0)return"";let n=e.map(o=>o.length);for(let o of t)for(let i=0;i<o.length;i++){let s=f(o[i],r.nullValue).length;s>n[i]&&(n[i]=s)}let a=[];r.header&&(a.push(e.map((o,i)=>o.padEnd(n[i])).join("  ")),a.push(n.map(o=>"-".repeat(o)).join("  ")));for(let o of t)a.push(o.map((i,s)=>f(i,r.nullValue).padEnd(n[s])).join("  "));return a.length>0?`${a.join(`
`)}
`:""}function Q(e,t,r){if(e.length===0)return"";let n=e.map(i=>i.length);for(let i of t)for(let s=0;s<i.length;s++){let m=f(i[s],r.nullValue).length;m>n[s]&&(n[s]=m)}let a=[],o=`+${n.map(i=>"-".repeat(i+2)).join("+")}+`;a.push(o),r.header&&(a.push(`| ${e.map((i,s)=>i.padEnd(n[s])).join(" | ")} |`),a.push(o));for(let i of t)a.push(`| ${i.map((s,m)=>f(s,r.nullValue).padEnd(n[m])).join(" | ")} |`);return a.push(o),`${a.join(`
`)}
`}function U(e,t,r){if(e.length===0)return"";let n=[];r.header&&(n.push(`| ${e.join(" | ")} |`),n.push(`|${e.map(()=>"---").join("|")}|`));for(let a of t)n.push(`| ${a.map(o=>f(o,r.nullValue)).join(" | ")} |`);return n.length>0?`${n.join(`
`)}
`:""}function W(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.join("	"));for(let a of t)n.push(a.map(o=>f(o,r.nullValue)).join("	"));return n.length>0?`${n.join(r.newline)}${r.newline}`:""}function D(e,t,r){if(e.length===0)return"";let n=e.map(o=>o.length);for(let o of t)for(let i=0;i<o.length;i++){let s=f(o[i],r.nullValue).length;s>n[i]&&(n[i]=s)}let a=[];a.push(`\u250C${n.map(o=>"\u2500".repeat(o+2)).join("\u252C")}\u2510`),a.push(`\u2502 ${e.map((o,i)=>o.padEnd(n[i])).join(" \u2502 ")} \u2502`),a.push(`\u251C${n.map(o=>"\u2500".repeat(o+2)).join("\u253C")}\u2524`);for(let o of t)a.push(`\u2502 ${o.map((i,s)=>f(i,r.nullValue).padEnd(n[s])).join(" \u2502 ")} \u2502`);return a.push(`\u2514${n.map(o=>"\u2500".repeat(o+2)).join("\u2534")}\u2518`),`${a.join(`
`)}
`}function H(e,t,r){let n=[];r.header&&e.length>0&&n.push(e.map(a=>`'${a}'`).join(","));for(let a of t)n.push(a.map(o=>o==null?"NULL":typeof o=="number"?Number.isInteger(o)?String(o):B(o):`'${String(o)}'`).join(","));return n.length>0?`${n.join(r.newline)}${r.newline}`:""}function J(e,t,r){let n=[];r.header&&e.length>0&&(n.push(`<TR>${e.map(a=>`<TH>${V(a)}</TH>`).join("")}`),n.push("</TR>"));for(let a of t)n.push(`<TR>${a.map(o=>`<TD>${V(f(o,r.nullValue))}</TD>`).join("")}`),n.push("</TR>");return n.length>0?`${n.join(`
`)}
`:""}function V(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function _(e,t,r){let o=[];r.header&&e.length>0&&o.push(e.join(""));for(let i of t)o.push(i.map(s=>f(s,r.nullValue)).join(""));return o.length>0?o.join("")+"":""}var Z=5e3,v={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 ee(e){let t={mode:"list",header:!1,separator:"|",newline:`
`,nullValue:"",readonly:!1,bail:!1,echo:!1,cmd:null},r=null,n=null,a=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(o){r===null?r=s:n===null&&(n=s);continue}if(s==="--")o=!0;else if(s==="-version")a=!0;else if(s==="-list")t.mode="list";else if(s==="-csv")t.mode="csv";else if(s==="-json")t.mode="json";else if(s==="-line")t.mode="line";else if(s==="-column")t.mode="column";else if(s==="-table")t.mode="table";else if(s==="-markdown")t.mode="markdown";else if(s==="-tabs")t.mode="tabs";else if(s==="-box")t.mode="box";else if(s==="-quote")t.mode="quote";else if(s==="-html")t.mode="html";else if(s==="-ascii")t.mode="ascii";else if(s==="-header")t.header=!0;else if(s==="-noheader")t.header=!1;else if(s==="-readonly")t.readonly=!0;else if(s==="-bail")t.bail=!0;else if(s==="-echo")t.echo=!0;else if(s==="-separator"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -separator
`,exitCode:1};t.separator=e[++i]}else if(s==="-newline"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -newline
`,exitCode:1};t.newline=e[++i]}else if(s==="-nullvalue"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -nullvalue
`,exitCode:1};t.nullValue=e[++i]}else if(s==="-cmd"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
`,exitCode:1};t.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};r===null?r=s:n===null&&(n=s)}}return{options:t,database:r,sql:n,showVersion:a}}async function re(){let e=await j.runTrustedAsync(()=>K()),t=new e.Database;try{let r=t.exec("SELECT sqlite_version()");return r.length>0&&r[0].values.length>0?String(r[0].values[0][0]):"unknown"}finally{t.close()}}function te(){let e=X(Y(import.meta.url)),t=x(e,"../../commands/sqlite3/worker.js");if(T(t))return t;let r=x(e,"worker.js");if(T(r))return r;let n=x(e,"../../../dist/commands/sqlite3/worker.js");if(T(n))return n;throw new Error("sqlite3 worker not found. Run 'pnpm build' to compile the worker.")}var ne={createWorker(e,t){return new G(e,{workerData:t})}};function oe(){return z(16).toString("hex")}function se(e,t){if(!e||typeof e!="object")return{success:!1,error:"Malformed worker response"};let r=e;return typeof r.protocolToken!="string"||r.protocolToken!==t?{success:!1,error:"Malformed worker response: invalid protocol token"}: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 ie(e,t,r){try{let n=te();return await new Promise((a,o)=>{let i=j.runTrusted(()=>ne.createWorker(n,e)),s=b(r,"sqlite3","worker timeout callback",()=>{i.terminate(),a({success:!1,error:`Query timeout: execution exceeded ${t}ms limit`})}),c=q(()=>{try{s()}catch(u){let l=u instanceof Error?u.message:String(u);a({success:!1,error:g(l)})}},t),S=b(r,"sqlite3","worker message callback",u=>{w(c),a(se(u,e.protocolToken))}),$=b(r,"sqlite3","worker error callback",u=>{w(c),o(u)}),y=b(r,"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:g(d)})}},k=u=>{try{$(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);o(new Error(g(d)))}},h=u=>{try{y(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:g(d)})}};i.on("message",p),i.on("error",k),i.on("exit",h)})}catch(n){let a=g(n.message);throw new Error(`sqlite3 worker failed to load: ${a}`)}}var $e={name:"sqlite3",async execute(e,t){if(M(e)||e.includes("-help"))return C(v);let r=ee(e);if("exitCode"in r)return r;let{options:n,database:a,sql:o,showVersion:i}=r;if(i)return{stdout:`${await re()}
`,stderr:"",exitCode:0};if(!a)return{stdout:"",stderr:`sqlite3: missing database argument
`,exitCode:1};let s=o||t.stdin.trim();if(n.cmd&&(s=n.cmd+(s?`; ${s}`:"")),!s)return{stdout:"",stderr:`sqlite3: no SQL provided
`,exitCode:1};let m=a===":memory:",c="",S=null;try{m||(c=t.fs.resolvePath(t.cwd,a),await t.fs.exists(c)&&(S=await t.fs.readFileBuffer(c)))}catch(l){let d=E(l.message);return{stdout:"",stderr:`sqlite3: unable to open database "${a}": ${d}
`,exitCode:1}}let $=t.limits?.maxSqliteTimeoutMs??Z,y={protocolToken:oe(),dbBuffer:S,sql:s,options:{bail:n.bail,echo:n.echo}},p;try{p=await ie(y,$,t.requireDefenseContext)}catch(l){return{stdout:"",stderr:`sqlite3: worker error: ${g(l.message)}
`,exitCode:1}}if(!p.success)return{stdout:"",stderr:`sqlite3: ${g(p.error)}
`,exitCode:1};let k={mode:n.mode,header:n.header,separator:n.separator,newline:n.newline,nullValue:n.nullValue},h="";n.echo&&(h+=`${s}
`);let u=!1;for(let l of p.results)if(l.type==="error"){if(n.bail)return{stdout:h,stderr:`Error: ${l.error}
`,exitCode:1};h+=`Error: ${l.error}
`,u=!0}else l.columns&&l.rows&&(l.rows.length>0||n.header)&&(h+=A(l.columns,l.rows,k));if(p.hasModifications&&!n.readonly&&!m&&c&&p.dbBuffer)try{await t.fs.writeFile(c,p.dbBuffer)}catch(l){let d=E(l.message);return{stdout:h,stderr:`sqlite3: failed to write database: ${d}
`,exitCode:1}}return{stdout:h,stderr:"",exitCode:u&&n.bail?1:0}}},ye={name:"sqlite3",flags:[],needsArgs:!0};export{ne as a,$e as b,ye as c};
