bun-query-builder 0.2.63 → 0.2.65

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/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import"../chunk-2jmgdx61.js";import"../chunk-7xvyccgk.js";import{J,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,_,ae,oe,v,le,b,k,C,me,he,I,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De}from"../chunk-0h7e47md.js";import"../chunk-55jccfgb.js";import{existsSync as Le}from"fs";import Q from"fs/promises";import Ie from"os";import ce from"path";import E from"process";import{EventEmitter as Ne}from"events";import x from"process";import Ee from"process";import fe from"process";import G from"process";import V from"process";import Me from"tty";import kt,{stdin as Xt,stdout as Zt}from"process";class Be{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Ie.homedir(),t=ce.join(e,".config","clapp");this.configPath=ce.join(t,"telemetry.json")}async isEnabled(){if(E.env.DO_NOT_TRACK==="1"||E.env.DO_NOT_TRACK==="true")return!1;if(E.env.NO_TELEMETRY==="1"||E.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Ie.platform(),nodeVersion:E.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:E.env.DO_NOT_TRACK==="1"||E.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Le(this.configPath)){let e=await Q.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=ce.dirname(this.configPath);await Q.mkdir(t,{recursive:!0}),await Q.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Nt=new Be;function de(e){return e.replace(/[<[].+/,"").trim()}function Pe(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],r=(l)=>{let n=!1,a=l[1];if(a.startsWith("..."))a=a.slice(3),n=!0;return{required:l[0].startsWith("<"),value:a,variadic:n}},o;while(o=t.exec(e))s.push(r(o));let d;while(d=i.exec(e))s.push(r(d));return s}function We(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,d)=>d!==i&&o.names.some((l)=>s.names.includes(l))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function ke(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function ue(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function U(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function Fe(e,t,i){let s=0,r=t.length,o=e,d;for(;s<r;++s)d=o[t[s]],o=o[t[s]]=s===r-1?i:d!=null?d:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function ze(e,t){for(let i of Object.keys(t)){let s=t[i];if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function Ue(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function A(e){return e.split(".").map((t,i)=>i===0?U(t):t).join(".")}class D extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
3
+ import"../chunk-2phsm8dt.js";import"../chunk-7xvyccgk.js";import{J,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,_,ae,oe,v,le,b,k,C,me,he,I,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De}from"../chunk-2ezrq7dm.js";import"../chunk-55jccfgb.js";import{existsSync as Le}from"fs";import Q from"fs/promises";import Ie from"os";import ce from"path";import E from"process";import{EventEmitter as Ne}from"events";import x from"process";import Ee from"process";import fe from"process";import G from"process";import V from"process";import Me from"tty";import kt,{stdin as Xt,stdout as Zt}from"process";class Be{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Ie.homedir(),t=ce.join(e,".config","clapp");this.configPath=ce.join(t,"telemetry.json")}async isEnabled(){if(E.env.DO_NOT_TRACK==="1"||E.env.DO_NOT_TRACK==="true")return!1;if(E.env.NO_TELEMETRY==="1"||E.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let s={event:e,...t,timestamp:Date.now(),platform:Ie.platform(),nodeVersion:E.version};if(this.events.push(s),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:E.env.DO_NOT_TRACK==="1"||E.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Le(this.configPath)){let e=await Q.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=ce.dirname(this.configPath);await Q.mkdir(t,{recursive:!0}),await Q.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var Nt=new Be;function de(e){return e.replace(/[<[].+/,"").trim()}function Pe(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],r=(l)=>{let n=!1,a=l[1];if(a.startsWith("..."))a=a.slice(3),n=!0;return{required:l[0].startsWith("<"),value:a,variadic:n}},o;while(o=t.exec(e))s.push(r(o));let d;while(d=i.exec(e))s.push(r(d));return s}function We(e){let t={alias:{},boolean:[]};for(let[i,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((o,d)=>d!==i&&o.names.some((l)=>s.names.includes(l))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function ke(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function ue(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function U(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function Fe(e,t,i){let s=0,r=t.length,o=e,d;for(;s<r;++s)d=o[t[s]],o=o[t[s]]=s===r-1?i:d!=null?d:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function ze(e,t){for(let i of Object.keys(t)){let s=t[i];if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function Ue(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function A(e){return e.split(".").map((t,i)=>i===0?U(t):t).join(".")}class D extends Error{exitCode=2;isUsageError=!0;usage;constructor(e,t){super(e);if(this.name=this.constructor.name,t!==void 0)this.usage=t;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
4
4
 
5
5
  Stack trace:
6
6
  ${this.stack}`;return this.message}}function Ge(e){if(e instanceof D)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function He(){let{env:e}=Ee,{TERM:t,TERM_PROGRAM:i}=e;if(Ee.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||i==="Terminus-Sublime"||i==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var H="\x1B",g=`${H}[`;var _e={to(e,t){if(!t)return`${g}${e+1}G`;return`${g}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${g}${-e}D`;else if(e>0)i+=`${g}${e}C`;if(t<0)i+=`${g}${-t}A`;else if(t>0)i+=`${g}${t}B`;return i},up:(e=1)=>`${g}${e}A`,down:(e=1)=>`${g}${e}B`,forward:(e=1)=>`${g}${e}C`,backward:(e=1)=>`${g}${e}D`,nextLine:(e=1)=>`${g}E`.repeat(e),prevLine:(e=1)=>`${g}F`.repeat(e),left:`${g}G`,hide:`${g}?25l`,show:`${g}?25h`,save:`${H}7`,restore:`${H}8`};var Ft={screen:`${g}2J`,up:(e=1)=>`${g}1J`.repeat(e),down:(e=1)=>`${g}J`.repeat(e),line:`${g}2K`,lineEnd:`${g}K`,lineStart:`${g}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?_e.up():"");if(e)t+=_e.left;return t}},zt={screen:`${H}c`};function Ke(e,t){let i=[];for(let s=0;s<=t.length;s++)i[s]=[s];for(let s=0;s<=e.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let r=1;r<=e.length;r++)if(t.charAt(s-1)===e.charAt(r-1))i[s][r]=i[s-1][r-1];else i[s][r]=Math.min(i[s-1][r-1]+1,i[s][r-1]+1,i[s-1][r]+1);return i[t.length][e.length]}function je(e,t,i=2,s=3){return t.map((r)=>({cmd:r,distance:Ke(e,r)})).filter(({distance:r})=>r<=i).sort((r,o)=>r.distance-o.distance).slice(0,s).map(({cmd:r})=>r)}function Ye(e,t={}){let i={_:[]},s=t.alias||{},r=new Set(t.boolean||[]),o={};for(let l of Object.keys(s))for(let n of s[l])o[n]=l;for(let l of r)if(s[l])for(let n of s[l])r.add(n);function d(l,n){let a=o[l]||l;if(i[a]=n,s[a])for(let c of s[a])i[c]=n;if(o[l]&&s[o[l]])for(let c of s[o[l]])i[c]=n;i[l]=n}for(let l=0;l<e.length;l++){let n=e[l];if(n==="--"){i._.push(...e.slice(l+1));break}if(n.startsWith("--")){let a=n.indexOf("=");if(a!==-1){let c=U(n.slice(2,a)),m=n.slice(a+1);d(c,m)}else{let c=n.slice(2);if(c.startsWith("no-")){let w=U(c.slice(3));d(w,!1);continue}let m=U(c),h=o[m]||m;if(r.has(h)||r.has(m))d(m,!0);else{let w=e[l+1];if(w!==void 0&&!w.startsWith("-"))d(m,w),l++;else d(m,!0)}}}else if(n.startsWith("-")&&n.length>1){let a=n.slice(1);for(let c=0;c<a.length;c++){let m=a[c],h=o[m]||m;if(c===a.length-1&&!r.has(h)&&!r.has(m)){let w=e[l+1];if(w!==void 0&&!w.startsWith("-"))d(m,w),l++;else d(m,!0)}else d(m,!0)}}else i._.push(n)}return i}class Re{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=de(e).split(",").map((s)=>{let r=s.trim().replace(/^-{1,2}/,"");if(r.startsWith("no-"))this.negated=!0,r=r.replace(/^no-/,"");return A(r)}).sort((s,r)=>s.length>r.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var Gt=fe.argv,Qe=`${fe.platform}-${fe.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,qe=G.argv,Je=`${G.platform}-${G.arch} node-${G.version}`;class $e{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,i,s){this.rawName=e,this.description=t,this.config=i,this.cli=s,this.options=[],this.aliasNames=[],this.name=de(e);let r=de(e),o=r.indexOf(":");if(o>0)this.namespace=r.substring(0,o),this.name=r.substring(o+1);if(this.args=Pe(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!i)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,i){let s=new Re(e,t,i);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof ve}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=A(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>A(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:r}=this.cli.globalCommand,o=[{body:`${e}${i?`/${i}`:""}`}];if(o.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let a=ke(t.map((y)=>y.rawName)),c=new Map,m=[];for(let y of t)if(y.namespace){if(!c.has(y.namespace))c.set(y.namespace,[]);c.get(y.namespace).push(y)}else m.push(y);let h="";if(m.sort((y,W)=>y.rawName<W.rawName?-1:y.rawName>W.rawName?1:0),m.length>0)h+=m.map((y)=>` ${ue(y.rawName,a.length)} ${y.description}`).join(`
@@ -29,7 +29,7 @@ Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error du
29
29
  `)),this.enableDidYouMean){let t=[];for(let s of this.commands){if(s.displayName)t.push(s.displayName);if(s.aliasNames)t.push(...s.aliasNames)}let i=je(e,t);if(i.length>0)console.log(T.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${T.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(T.dim("Run"),`${this.name} --help`,T.dim("to see all available commands")),x.exit(1)}async parse(e=qe,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(n){throw this.handleUsageError(n),n}if(this.rawArgs=e,!this.name)this.name=e[1]?Ue(e[1]):"cli";let r=!0,o=e.slice(2),d=o[0];if(d&&!d.startsWith("-")){for(let n of this.commands)if(n.isMatched(d)){let a=this.mri(o,n);r=!1;let c={...a,args:a.args.slice(1)};this.setParsedInfo(c,n,d),this.emit(`command:${d}`,n);break}if(r){let n=o[1];if(n&&!n.startsWith("-")){let a=`${d}:${n}`;for(let c of this.commands)if(c.isMatched(a)){let m=this.mri(o,c);r=!1;let h={...m,args:m.args.slice(2)};this.setParsedInfo(h,c,a),this.emit(`command:${a}`,c);break}}}}if(r){for(let n of this.commands)if(n.name===""){r=!1;let a=this.mri(o,n);this.setParsedInfo(a,n),this.emit("command:!",n);break}}if(r){let n=this.mri(e.slice(2));this.setParsedInfo(n)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),i=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),i=!1,this.unsetMatchedCommand();let l={args:this.args,options:this.options};if(i)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return l}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=We(i),r=[],o=e.indexOf("--");if(o>-1)r=e.slice(o+1),e=e.slice(0,o);let d=Ye(e,s),l={_:d._};for(let h of Object.keys(d))if(h!=="_")l[A(h)]=d[h];let n=l._,a={"--":r},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,m=Object.create(null);for(let h of i){if(!c&&h.config.default!==void 0)for(let w of h.names)a[w]=h.config.default;if(Array.isArray(h.config.type)){if(m[h.name]===void 0)m[h.name]={shouldTransform:!0,transformFunction:h.config.type[0]}}}for(let h of Object.keys(l))if(h!=="_"){let w=h.split(".");Fe(a,w,l[h]),ze(a,m)}return{args:n,options:a}}async run(e=qe){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ge(e)||e.isUsageError===!1)return;let t=e.message||"command-line error",i=this.name?`${this.name}: `:"",s=/--help/.test(t)?"":e.usage?`
30
30
  Usage: ${e.usage}`:`
31
31
  Run \`${this.name??"cli"} --help\` for usage.`;x.stderr.write(`${i}${t}${s}
32
- `),x.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((l,n)=>{if(l.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let r={command:i,args:s,options:t};for(let l of i.beforeHooks)await l(r);let o,d=async()=>{let l=i.commandAction.apply(this,s);if(l instanceof Promise)o=await l;else o=l;return o};if(i.middleware.length>0){let l=0,n=async()=>{if(l<i.middleware.length){let a=i.middleware[l++];await a({...r,next:n})}else await d()};await n()}else await d();for(let l of i.afterHooks)await l(r);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return x.removeAllListeners("SIGINT"),x.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Ve{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Kt=new Ve;function tt(){if("FORCE_COLOR"in V.env)return V.env.FORCE_COLOR!=="0";if("NO_COLOR"in V.env||V.env.TERM==="dumb")return!1;if(V.platform==="win32")return!0;return Me.isatty(1)&&Me.isatty(2)}var Ae=tt();function f(e,t){if(!Ae)return(i)=>i;return(i)=>e+i+t}var it=f("\x1B[0m","\x1B[0m"),st=f("\x1B[31m","\x1B[39m"),rt=f("\x1B[32m","\x1B[39m"),nt=f("\x1B[33m","\x1B[39m"),at=f("\x1B[34m","\x1B[39m"),ot=f("\x1B[35m","\x1B[39m"),lt=f("\x1B[36m","\x1B[39m"),ct=f("\x1B[37m","\x1B[39m"),ut=f("\x1B[90m","\x1B[39m"),dt=f("\x1B[1m","\x1B[22m"),mt=f("\x1B[3m","\x1B[23m"),ht=f("\x1B[4m","\x1B[24m"),pt=f("\x1B[2m","\x1B[22m"),ft=f("\x1B[7m","\x1B[27m"),gt=f("\x1B[8m","\x1B[28m"),bt=f("\x1B[9m","\x1B[29m"),yt=f("\x1B[41m","\x1B[49m"),$t=f("\x1B[42m","\x1B[49m"),wt=f("\x1B[43m","\x1B[49m"),vt=f("\x1B[44m","\x1B[49m"),xt=f("\x1B[45m","\x1B[49m"),Ct=f("\x1B[46m","\x1B[49m"),St=f("\x1B[47m","\x1B[49m"),Ot=Ae,It={reset:it,red:st,green:rt,yellow:nt,blue:at,magenta:ot,cyan:lt,white:ct,gray:ut,bold:dt,italic:mt,underline:ht,dim:pt,inverse:ft,hidden:gt,strikethrough:bt,bgRed:yt,bgGreen:$t,bgYellow:wt,bgBlue:vt,bgMagenta:xt,bgCyan:Ct,bgWhite:St,isColorSupported:Ot},Et=It,_t=["up","down","left","right","space","enter","cancel"],ei={actions:new Set(_t),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var ti=kt.platform.startsWith("win"),ii=Symbol("clapp:cancel");var qt=He();var p=(e,t)=>qt?e:t,si=p("\u25C6","*"),ri=p("\u25A0","x"),ni=p("\u25B2","x"),ai=p("\u25C7","o"),oi=p("\u250C","T"),Mt=p("\u2502","|"),li=p("\u2514","\u2014"),ci=p("\u25CF",">"),ui=p("\u25CB"," "),di=p("\u25FB","[\u2022]"),mi=p("\u25FC","[+]"),hi=p("\u25FB","[ ]"),pi=p("\u25AA","\u2022"),fi=p("\u2500","-"),gi=p("\u256E","+"),bi=p("\u251C","+"),yi=p("\u256F","+"),$i=p("\u25CF","\u2022"),wi=p("\u25C6","*"),vi=p("\u25B2","!"),xi=p("\u25A0","x");var Ci={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Bt(){return`${Et.gray(Mt)} `}var Si=Bt();var Ce="0.2.63";var u=new xe("query-builder");u.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(e,t)=>{await oe(e,t)});u.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(e)=>{let t=e?.table,i=t?Array.isArray(t)?t:[t]:void 0,s=await v({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
32
+ `),x.exit(e.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:i}=this;if(!i||!i.commandAction)return;i.checkUnknownOptions(),i.checkOptionValue(),i.checkRequiredArgs();let s=[];i.args.forEach((l,n)=>{if(l.variadic)s.push(e.slice(n));else s.push(e[n])}),s.push(t);let r={command:i,args:s,options:t};for(let l of i.beforeHooks)await l(r);let o,d=async()=>{let l=i.commandAction.apply(this,s);if(l instanceof Promise)o=await l;else o=l;return o};if(i.middleware.length>0){let l=0,n=async()=>{if(l<i.middleware.length){let a=i.middleware[l++];await a({...r,next:n})}else await d()};await n()}else await d();for(let l of i.afterHooks)await l(r);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return x.removeAllListeners("SIGINT"),x.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Ve{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,i=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:i})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())if(e-i.timestamp>i.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var Kt=new Ve;function tt(){if("FORCE_COLOR"in V.env)return V.env.FORCE_COLOR!=="0";if("NO_COLOR"in V.env||V.env.TERM==="dumb")return!1;if(V.platform==="win32")return!0;return Me.isatty(1)&&Me.isatty(2)}var Ae=tt();function f(e,t){if(!Ae)return(i)=>i;return(i)=>e+i+t}var it=f("\x1B[0m","\x1B[0m"),st=f("\x1B[31m","\x1B[39m"),rt=f("\x1B[32m","\x1B[39m"),nt=f("\x1B[33m","\x1B[39m"),at=f("\x1B[34m","\x1B[39m"),ot=f("\x1B[35m","\x1B[39m"),lt=f("\x1B[36m","\x1B[39m"),ct=f("\x1B[37m","\x1B[39m"),ut=f("\x1B[90m","\x1B[39m"),dt=f("\x1B[1m","\x1B[22m"),mt=f("\x1B[3m","\x1B[23m"),ht=f("\x1B[4m","\x1B[24m"),pt=f("\x1B[2m","\x1B[22m"),ft=f("\x1B[7m","\x1B[27m"),gt=f("\x1B[8m","\x1B[28m"),bt=f("\x1B[9m","\x1B[29m"),yt=f("\x1B[41m","\x1B[49m"),$t=f("\x1B[42m","\x1B[49m"),wt=f("\x1B[43m","\x1B[49m"),vt=f("\x1B[44m","\x1B[49m"),xt=f("\x1B[45m","\x1B[49m"),Ct=f("\x1B[46m","\x1B[49m"),St=f("\x1B[47m","\x1B[49m"),Ot=Ae,It={reset:it,red:st,green:rt,yellow:nt,blue:at,magenta:ot,cyan:lt,white:ct,gray:ut,bold:dt,italic:mt,underline:ht,dim:pt,inverse:ft,hidden:gt,strikethrough:bt,bgRed:yt,bgGreen:$t,bgYellow:wt,bgBlue:vt,bgMagenta:xt,bgCyan:Ct,bgWhite:St,isColorSupported:Ot},Et=It,_t=["up","down","left","right","space","enter","cancel"],ei={actions:new Set(_t),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var ti=kt.platform.startsWith("win"),ii=Symbol("clapp:cancel");var qt=He();var p=(e,t)=>qt?e:t,si=p("\u25C6","*"),ri=p("\u25A0","x"),ni=p("\u25B2","x"),ai=p("\u25C7","o"),oi=p("\u250C","T"),Mt=p("\u2502","|"),li=p("\u2514","\u2014"),ci=p("\u25CF",">"),ui=p("\u25CB"," "),di=p("\u25FB","[\u2022]"),mi=p("\u25FC","[+]"),hi=p("\u25FB","[ ]"),pi=p("\u25AA","\u2022"),fi=p("\u2500","-"),gi=p("\u256E","+"),bi=p("\u251C","+"),yi=p("\u256F","+"),$i=p("\u25CF","\u2022"),wi=p("\u25C6","*"),vi=p("\u25B2","!"),xi=p("\u25A0","x");var Ci={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Bt(){return`${Et.gray(Mt)} `}var Si=Bt();var Ce="0.2.65";var u=new xe("query-builder");u.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(e,t)=>{await oe(e,t)});u.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(e)=>{let t=e?.table,i=t?Array.isArray(t)?t:[t]:void 0,s=await v({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
33
33
 
34
34
  ${s.map((r)=>r.source).join(`
35
35
  `)}`)});u.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(e,t,i)=>{await Te(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await pe()});u.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(e)=>{try{await De(e)}catch{let t=await import("process");t.default.exitCode=1}});u.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(e,t)=>{await we(e,t)});u.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(e,t)=>{await se(e,t)});u.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate ./app/Models --dialect postgres").action(async(e,t)=>{try{await b(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full}),await k()}catch(i){console.error("-- Migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(e)=>{await ie(e)});u.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(e,t)=>{try{await K(e,{verbose:t.verbose,json:t.json})}catch(i){console.error("-- Explain all failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(e)=>{try{await F({dir:e.dir,format:e.format,output:e.output,verbose:e.verbose})}catch(t){console.error("-- Diagram generation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(e,t)=>{try{console.log("-- Resetting database..."),await C(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await b(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await k()}catch(i){console.error("-- Migrate fresh failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(e,t)=>{try{await C(e,{dialect:t.dialect,state:t.state})}catch(i){console.error("-- Reset failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(e)=>{try{if(e.class)await j(e.class,{verbose:e.verbose});else await R({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(e)=>{try{if(e.class)await j(e.class,{verbose:e.verbose});else await R({seedersDir:e.dir,verbose:e.verbose})}catch(t){console.error("-- Seeding failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(e)=>{try{await ye(e)}catch(t){console.error("-- Failed to create seeder:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(e)=>{try{await be({modelsDir:e.models,seedersDir:e.seeders,verbose:e.verbose})}catch(t){console.error("-- Database fresh failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(e,t)=>{try{await le(e,{table:t.table,dir:t.dir,timestamps:t.timestamps})}catch(i){console.error("-- Failed to create model:",i);let s=await import("process");s.default.exitCode=1}});u.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(e,t)=>{try{await L(e,{dir:t.dir,json:t.json,verbose:t.verbose})}catch(i){console.error("-- Failed to show model:",i);let s=await import("process");s.default.exitCode=1}});u.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await I()}catch(e){console.error("-- Failed to get migration status:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await ge()}catch(e){console.error("-- Failed to list migrations:",e);let t=await import("process");t.default.exitCode=1}});u.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(e)=>{try{await he({steps:Number(e.steps),reverseSchema:e.reverseSchema,deleteFiles:Boolean(e.deleteFiles)})}catch(t){console.error("-- Rollback failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(e,t)=>{try{await me(e,{dialect:t?.dialect,state:t?.state,apply:t?.apply,full:t?.full})}catch(i){console.error("-- Generate migration failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await B()}catch(e){console.error("-- Failed to get database info:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await re()}catch(e){console.error("-- Failed to get database stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(e)=>{try{await O({dialect:e.dialect,force:e.force,verbose:e.verbose})}catch(t){console.error("-- Wipe failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(e)=>{try{await P({dialect:e.dialect,aggressive:e.aggressive,tables:e.tables?e.tables.split(","):void 0,verbose:e.verbose})}catch(t){console.error("-- Optimize failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await N()}catch(e){console.error("-- Console failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await Z()}catch(e){console.error("-- Tinker failed:",e);let t=await import("process");t.default.exitCode=1}});u.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(e,t)=>{try{await _(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to inspect table:",i);let s=await import("process");s.default.exitCode=1}});u.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(e,t)=>{try{await ae(e,{verbose:t.verbose})}catch(i){console.error("-- Failed to get table info:",i);let s=await import("process");s.default.exitCode=1}});u.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await z()}catch(e){console.error("-- Failed to clear cache:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await Y()}catch(e){console.error("-- Failed to get cache stats:",e);let t=await import("process");t.default.exitCode=1}});u.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(e)=>{try{await X({size:e.size})}catch(t){console.error("-- Failed to configure cache:",t);let i=await import("process");i.default.exitCode=1}});u.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(e)=>{try{await J({operations:e.operations,iterations:e.iterations?Number(e.iterations):void 0})}catch(t){console.error("-- Benchmark failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(e)=>{try{await q(e)}catch(t){console.error("-- Validation failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(e)=>{try{await Se(e)}catch(t){console.error("-- Check failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(e,t)=>{try{await ee(e,{format:t.format,output:t.output,limit:t.limit?Number(t.limit):void 0})}catch(i){console.error("-- Export failed:",i);let s=await import("process");s.default.exitCode=1}});u.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(e,t,i)=>{try{await te(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let r=await import("process");r.default.exitCode=1}});u.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(e)=>{try{await ne({tables:e.tables,output:e.output})}catch(t){console.error("-- Dump failed:",t);let i=await import("process");i.default.exitCode=1}});u.command("version","Show the version of the CLI").action(()=>{console.log(Ce)});u.version(Ce);u.help();u.parse();
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{r,e,H,t,s,Q,qe,Ce,w,We,n,p,y,Tt,x,o,Re,A,Ae,Me,M}from"./chunk-2jmgdx61.js";import{c}from"./chunk-55jccfgb.js";var ni=import.meta.require;import{existsSync as Xn,mkdirSync as qs,mkdtempSync as Ra,readdirSync as Ks,readFileSync as Rr,rmSync as Fs,unlinkSync as Xr,writeFileSync as Us}from"fs";import{tmpdir as xa}from"os";import{isAbsolute as Na,join as Kn}from"path";import Zr from"process";function ri(d){let h=2166136261;for(let D=0;D<d.length;D++)h^=d.charCodeAt(D),h=Math.imul(h,16777619)>>>0;return h.toString(36).padStart(7,"0").slice(-7)}function si(d,h=63){if(d.length<=h)return d;let D=`_${ri(d)}`;return d.slice(0,h-D.length)+D}function Jn(d,h){let D=`${d}_`,E=h.startsWith(D)?h:`${D}${h}`;return si(E)}class a{quoteIdentifier(d){return`\`${d.replace(/`/g,"``")}\``}getColumnType(d){switch(d.type){case"string":return`varchar(${d.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(d.enumValues&&d.enumValues.length>0)return`ENUM(${d.enumValues.map((D)=>`'${D.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(d){return this.getColumnType(d)}getAutoIncrementClause(d){if(d.isPrimaryKey&&(d.type==="integer"||d.type==="bigint"))return"auto_increment";return""}getDefaultValue(d){if(!d.hasDefault||d.defaultValue===void 0)return"";let h=d.defaultValue;if(typeof h==="string"){let D=h.toUpperCase();if(D==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(D))return`default ${D}`;let V=`'${h.replace(/'/g,"''")}'`;if(d.type==="text"||d.type==="json"||d.type==="enum"&&!d.enumValues?.length)return`default (${V})`;return`default ${V}`}else if(typeof h==="number"||typeof h==="bigint")return`default ${h}`;else if(typeof h==="boolean")return`default ${h?1:0}`;else if(h instanceof Date)return`default '${h.toISOString()}'`;return""}createEnumType(d,h){return""}foreignKeyClauses(d){return d.columns.filter((h)=>h.references).map((h)=>{let D=h.references,E=`${d.table}_${h.name}_fk`,V=`CONSTRAINT ${this.quoteIdentifier(E)} FOREIGN KEY (${this.quoteIdentifier(h.name)}) REFERENCES ${this.quoteIdentifier(D.table)}(${this.quoteIdentifier(D.column)})`;if(D.onDelete)V+=` ON DELETE ${D.onDelete.toUpperCase()}`;if(D.onUpdate)V+=` ON UPDATE ${D.onUpdate.toUpperCase()}`;return V})}createTable(d){let h=[...d.columns.map((D)=>this.renderColumn(D)),...this.foreignKeyClauses(d)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(d.table)} (
2
+ import{r,e,H,t,s,Q,qe,Ce,w,We,n,p,y,Tt,x,o,Re,A,Ae,Me,M}from"./chunk-2phsm8dt.js";import{c}from"./chunk-55jccfgb.js";var ni=import.meta.require;import{existsSync as Xn,mkdirSync as qs,mkdtempSync as Ra,readdirSync as Ks,readFileSync as Rr,rmSync as Fs,unlinkSync as Xr,writeFileSync as Us}from"fs";import{tmpdir as xa}from"os";import{isAbsolute as Na,join as Kn}from"path";import Zr from"process";function ri(d){let h=2166136261;for(let D=0;D<d.length;D++)h^=d.charCodeAt(D),h=Math.imul(h,16777619)>>>0;return h.toString(36).padStart(7,"0").slice(-7)}function si(d,h=63){if(d.length<=h)return d;let D=`_${ri(d)}`;return d.slice(0,h-D.length)+D}function Jn(d,h){let D=`${d}_`,E=h.startsWith(D)?h:`${D}${h}`;return si(E)}class a{quoteIdentifier(d){return`\`${d.replace(/`/g,"``")}\``}getColumnType(d){switch(d.type){case"string":return`varchar(${d.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(d.enumValues&&d.enumValues.length>0)return`ENUM(${d.enumValues.map((D)=>`'${D.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(d){return this.getColumnType(d)}getAutoIncrementClause(d){if(d.isPrimaryKey&&(d.type==="integer"||d.type==="bigint"))return"auto_increment";return""}getDefaultValue(d){if(!d.hasDefault||d.defaultValue===void 0)return"";let h=d.defaultValue;if(typeof h==="string"){let D=h.toUpperCase();if(D==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(D))return`default ${D}`;let V=`'${h.replace(/'/g,"''")}'`;if(d.type==="text"||d.type==="json"||d.type==="enum"&&!d.enumValues?.length)return`default (${V})`;return`default ${V}`}else if(typeof h==="number"||typeof h==="bigint")return`default ${h}`;else if(typeof h==="boolean")return`default ${h?1:0}`;else if(h instanceof Date)return`default '${h.toISOString()}'`;return""}createEnumType(d,h){return""}foreignKeyClauses(d){return d.columns.filter((h)=>h.references).map((h)=>{let D=h.references,E=`${d.table}_${h.name}_fk`,V=`CONSTRAINT ${this.quoteIdentifier(E)} FOREIGN KEY (${this.quoteIdentifier(h.name)}) REFERENCES ${this.quoteIdentifier(D.table)}(${this.quoteIdentifier(D.column)})`;if(D.onDelete)V+=` ON DELETE ${D.onDelete.toUpperCase()}`;if(D.onUpdate)V+=` ON UPDATE ${D.onUpdate.toUpperCase()}`;return V})}createTable(d){let h=[...d.columns.map((D)=>this.renderColumn(D)),...this.foreignKeyClauses(d)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(d.table)} (
3
3
  ${h.join(`,
4
4
  `)}
5
5
  ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(d){let h=this.getColumnType(d).toLowerCase();if(h.includes("text")||h.includes("blob")||h==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let D=h.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(D!==void 0)return{bytes:Number(D)*a.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(d,h,D){let E=h.columns.map((Ne)=>{let xe=D?.find((Ve)=>Ve.name===Ne),Fe=xe?this.keyPartWidth(xe):{bytes:0,indexableWhole:!0},Ie=!Fe.indexableWhole;return{name:Ne,prefixed:Ie,bytes:Ie?a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER:Fe.bytes,narrowable:!Fe.indexableWhole||Fe.bytes>a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}}),V=()=>E.reduce((Ne,xe)=>Ne+xe.bytes,0);while(V()>a.MAX_KEY_BYTES){let Ne=E.filter((xe)=>xe.narrowable&&!xe.prefixed).sort((xe,Fe)=>Fe.bytes-xe.bytes)[0];if(!Ne)throw Error(`[migrations] Index '${h.name}' on table '${d}' needs ${V()} bytes of key, over MySQL's ${a.MAX_KEY_BYTES}. Every column in it is already at its ${a.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);Ne.prefixed=!0,Ne.bytes=a.KEY_PREFIX_CHARACTERS*a.BYTES_PER_CHARACTER}return E.map((Ne)=>Ne.prefixed?`${this.quoteIdentifier(Ne.name)}(${a.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(Ne.name))}createIndex(d,h,D){if(h.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${h.name}' on table '${d}' uses WHERE clause: ${h.where}`);let E=h.type==="unique"?"UNIQUE ":"",V=Jn(d,h.name),Ne=this.keyParts(d,h,D).join(", ");return`CREATE ${E}INDEX ${this.quoteIdentifier(V)} ON ${this.quoteIdentifier(d)} (${Ne});`}addForeignKey(d,h,D,E,V,Ne,xe=[]){let Fe=`${d}_${h}_fk`,Ie=`ALTER TABLE ${this.quoteIdentifier(d)} ADD CONSTRAINT ${this.quoteIdentifier(Fe)} FOREIGN KEY (${this.quoteIdentifier(h)}) REFERENCES ${this.quoteIdentifier(D)}(${this.quoteIdentifier(E)})`;if(V)Ie+=` ON DELETE ${V.toUpperCase()}`;if(Ne)Ie+=` ON UPDATE ${Ne.toUpperCase()}`;let Ve=[...new Set(xe)].map((gt)=>`ALTER TABLE ${this.quoteIdentifier(d)} DROP FOREIGN KEY ${this.quoteIdentifier(gt)};`).join(`
@@ -340,7 +340,7 @@ export default class ${V} extends Seeder {
340
340
  return 100
341
341
  }
342
342
  }
343
- `;na(xe,Fe),console.log(`-- \u2713 Created seeder: ${xe}`)}async function be(d={}){let h=Pr(Dr.cwd()),D=d.modelsDir||rr(h,"app/Models"),E=d.seedersDir||rr(h,"database/seeders"),V=d.verbose??!0;try{let{resetDatabase:Ne,generateMigration:xe,executeMigration:Fe}=await import("./chunk-eczymkcb.js");if(V)console.log("-- Refreshing database...");if(await Ne(D),V)console.log("-- Running migrations...");if(await xe(D,{full:!0}),await Fe(),V)console.log("-- Running seeders...");if(await R({seedersDir:E,verbose:V}),V)console.log("-- \u2713 Database refreshed successfully")}catch(Ne){throw console.error("-- \u2717 Database refresh failed:",Ne),Ne}}function Te(d,h,D={}){let E=u({modelsDir:d}),V=$e(E);if(e.debug)e.debug.captureText=!0;let Ne=i({schema:V}),xe=Ne.selectFrom(h).limit(Number(D.limit||10)).toText?.()??"";return console.log(xe||"[query]"),{sql:xe,qb:Ne,schema:V}}async function we(d,h={}){let D=i(),E=h.params?JSON.parse(h.params):void 0,V=await D.unsafe(d,E);return console.log(JSON.stringify(V)),V}import{existsSync as ra}from"fs";import{dirname as ws,join as Ds}from"path";import Es from"process";function sa(d){let h=d;while(h!==ws(h)){if(ra(Ds(h,"package.json")))return h;h=ws(h)}return Es.cwd()}async function q(d){if(!d)d=Ds(sa(Es.cwd()),"app/Models");let h=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${d}`),console.log(`-- Dialect: ${h}`),console.log();let D=[];try{let E=await u({modelsDir:d}),V=W(E,{dialect:h}),Ne=i(),xe=[];if(h==="sqlite")xe=(await Ne.unsafe(`
343
+ `;na(xe,Fe),console.log(`-- \u2713 Created seeder: ${xe}`)}async function be(d={}){let h=Pr(Dr.cwd()),D=d.modelsDir||rr(h,"app/Models"),E=d.seedersDir||rr(h,"database/seeders"),V=d.verbose??!0;try{let{resetDatabase:Ne,generateMigration:xe,executeMigration:Fe}=await import("./chunk-hgkvabrq.js");if(V)console.log("-- Refreshing database...");if(await Ne(D),V)console.log("-- Running migrations...");if(await xe(D,{full:!0}),await Fe(),V)console.log("-- Running seeders...");if(await R({seedersDir:E,verbose:V}),V)console.log("-- \u2713 Database refreshed successfully")}catch(Ne){throw console.error("-- \u2717 Database refresh failed:",Ne),Ne}}function Te(d,h,D={}){let E=u({modelsDir:d}),V=$e(E);if(e.debug)e.debug.captureText=!0;let Ne=i({schema:V}),xe=Ne.selectFrom(h).limit(Number(D.limit||10)).toText?.()??"";return console.log(xe||"[query]"),{sql:xe,qb:Ne,schema:V}}async function we(d,h={}){let D=i(),E=h.params?JSON.parse(h.params):void 0,V=await D.unsafe(d,E);return console.log(JSON.stringify(V)),V}import{existsSync as ra}from"fs";import{dirname as ws,join as Ds}from"path";import Es from"process";function sa(d){let h=d;while(h!==ws(h)){if(ra(Ds(h,"package.json")))return h;h=ws(h)}return Es.cwd()}async function q(d){if(!d)d=Ds(sa(Es.cwd()),"app/Models");let h=e.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${d}`),console.log(`-- Dialect: ${h}`),console.log();let D=[];try{let E=await u({modelsDir:d}),V=W(E,{dialect:h}),Ne=i(),xe=[];if(h==="sqlite")xe=(await Ne.unsafe(`
344
344
  SELECT name FROM sqlite_master
345
345
  WHERE type = 'table'
346
346
  AND name NOT LIKE 'sqlite_%'