bun-query-builder 0.3.12 → 0.3.13
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 +7 -7
- package/dist/chunk-12t4k0mz.js +2 -0
- package/dist/chunk-2v1zv4hb.js +7 -0
- package/dist/chunk-bhm321nb.js +3 -0
- package/dist/{chunk-d2k7k2v6.js → chunk-ev6akmaa.js} +63 -63
- package/dist/{chunk-30mmrj6e.js → chunk-hk8j5d48.js} +1 -1
- package/dist/{chunk-hzrsdtv2.js → chunk-jypmc6m3.js} +23 -23
- package/dist/chunk-ztdtt4hj.js +3 -0
- package/dist/index.d.ts +1 -2
- package/dist/orm.d.ts +3 -37
- package/dist/relation-utils.d.ts +1 -0
- package/dist/schema.d.ts +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/type-inference.d.ts +2 -1
- package/package.json +1 -1
- package/dist/chunk-4yc8xkvc.js +0 -2
- package/dist/chunk-6s2dqhn3.js +0 -7
- package/dist/chunk-erek1wzq.js +0 -3
- package/dist/chunk-kt617w7c.js +0 -3
package/dist/bin/cli.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"../chunk-
|
|
3
|
+
import"../chunk-jypmc6m3.js";import"../chunk-wvae8521.js";import"../chunk-bhm321nb.js";import"../chunk-ztdtt4hj.js";import"../chunk-2v1zv4hb.js";import{ne,re,ie,se,F,ae,oe,le,ce,j,ue,q,W,de,fe,U,me,he,A,ge,S,N,M,we,Se,V,De,H,Ee,Q,G,P,J,$e,xe,ve,ke,z,Ce,Re}from"../chunk-ev6akmaa.js";import{EventEmitter as Le}from"events";import v from"process";import ye from"process";import X from"process";import T from"process";import I from"process";import qe from"tty";import kt,{stdin as Gt,stdout as Ht}from"process";import{existsSync as Bt}from"fs";import D from"fs/promises";import Me from"os";import K from"path";import x from"process";function Y(e){return e.replace(/[<[].+/,"").trim()}function Ne(e){let t=/<([^>]+)>/g,i=/\[([^\]]+)\]/g,s=[],n=(d)=>{let a=!1,r=d[1];if(r.startsWith("..."))r=r.slice(3),a=!0;else if(r.endsWith("..."))r=r.slice(0,-3),a=!0;return{required:d[0].startsWith("<"),value:r.trim(),variadic:a}},o;while(o=t.exec(e))s.push(n(o));let m;while(m=i.exec(e))s.push(n(m));return s}function Pe(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,m)=>m!==i&&o.names.some((d)=>s.names.includes(d))&&typeof o.required==="boolean"))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t}function Oe(e){return e.reduce((t,i)=>t.length>=i.length?t:i,"")}function L(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function B(e){return e.replace(/([a-z])-([a-z])/g,(t,i,s)=>i+s.toUpperCase())}function We(e,t,i){let s=0,n=t.length,o=e,m;for(;s<n;++s)m=o[t[s]],o=o[t[s]]=s===n-1?i:m!=null?m:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]}function Fe(e,t){for(let i of Object.keys(t)){let s=t[i];if(e[i]===void 0)continue;if(s.shouldTransform){if(e[i]=Array.prototype.concat.call([],e[i]),typeof s.transformFunction==="function")e[i]=e[i].map(s.transformFunction)}}}function ze(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function k(e){return e.split(".").map((t,i)=>i===0?B(t):t).join(".")}class E 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
|
-
${this.stack}`;return this.message}}function Ue(e){if(e instanceof E)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ge(){let{env:e}=ye,{TERM:t,TERM_PROGRAM:i}=e;if(ye.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
|
|
6
|
+
${this.stack}`;return this.message}}function Ue(e){if(e instanceof E)return!0;return!!e&&typeof e==="object"&&e.name==="ClappError"&&typeof e.message==="string"}function Ge(){let{env:e}=ye,{TERM:t,TERM_PROGRAM:i}=e;if(ye.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 R="\x1B",b=`${R}[`;var Ie={to(e,t){if(!t)return`${b}${e+1}G`;return`${b}${t+1};${e+1}H`},move(e,t){let i="";if(e<0)i+=`${b}${-e}D`;else if(e>0)i+=`${b}${e}C`;if(t<0)i+=`${b}${-t}A`;else if(t>0)i+=`${b}${t}B`;return i},up:(e=1)=>`${b}${e}A`,down:(e=1)=>`${b}${e}B`,forward:(e=1)=>`${b}${e}C`,backward:(e=1)=>`${b}${e}D`,nextLine:(e=1)=>`${b}E`.repeat(e),prevLine:(e=1)=>`${b}F`.repeat(e),left:`${b}G`,hide:`${b}?25l`,show:`${b}?25h`,save:`${R}7`,restore:`${R}8`};var Vt={screen:`${b}2J`,up:(e=1)=>`${b}1J`.repeat(e),down:(e=1)=>`${b}J`.repeat(e),line:`${b}2K`,lineEnd:`${b}K`,lineStart:`${b}1K`,lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?Ie.up():"");if(e)t+=Ie.left;return t}},Lt={screen:`${R}c`};function He(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 n=1;n<=e.length;n++)if(t.charAt(s-1)===e.charAt(n-1))i[s][n]=i[s-1][n-1];else i[s][n]=Math.min(i[s-1][n-1]+1,i[s][n-1]+1,i[s-1][n]+1);return i[t.length][e.length]}function Be(e,t,i=2,s=3){return t.map((n)=>({cmd:n,distance:He(e,n)})).filter(({distance:n})=>n<=i).sort((n,o)=>n.distance-o.distance).slice(0,s).map(({cmd:n})=>n)}function Ke(e,t={}){let i={_:[]},s=t.alias||{},n=new Set(t.boolean||[]),o={};for(let a of Object.keys(s))for(let r of s[a])o[r]=a;for(let a of n)if(s[a])for(let r of s[a])n.add(r);function m(a,r){if(a===void 0)return r;if(typeof r==="boolean")return r;return Array.isArray(a)?[...a,r]:[a,r]}function d(a,r){let c=o[a]||a,h=m(i[c],r);if(i[c]=h,s[c])for(let l of s[c])i[l]=h;if(o[a]&&s[o[a]])for(let l of s[o[a]])i[l]=h;i[a]=h}for(let a=0;a<e.length;a++){let r=e[a];if(r==="--"){i._.push(...e.slice(a+1));break}if(r.startsWith("--")){let c=r.indexOf("=");if(c!==-1){let h=B(r.slice(2,c)),l=r.slice(c+1);d(h,l)}else{let h=r.slice(2);if(h.startsWith("no-")){let f=B(h.slice(3));d(f,!1);continue}let l=B(h),y=o[l]||l;if(n.has(y)||n.has(l))d(l,!0);else{let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}}}else if(r.startsWith("-")&&r.length>1){let c=r.slice(1);for(let h=0;h<c.length;h++){let l=c[h],y=o[l]||l;if(h===c.length-1&&!n.has(y)&&!n.has(l)){let f=e[a+1];if(f!==void 0&&!f.startsWith("-"))d(l,f),a++;else d(l,!0)}else d(l,!0)}}else i._.push(r)}return i}class Te{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(e,t,i){if(this.rawName=e,this.description=t,this.config=Object.assign({},i),e=e.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(e),this.names=Y(e).split(",").map((s)=>{let n=s.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return k(n)}).sort((s,n)=>s.length>n.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 Dt=X.argv,Ye=`${X.platform}-${X.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,_e=T.argv,Qe=`${T.platform}-${T.arch} node-${T.version}`;class Z{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=Y(e);let n=Y(e),o=n.indexOf(":");if(o>0)this.namespace=n.substring(0,o),this.name=n.substring(o+1);if(this.args=Ne(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 Te(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 ee}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){let t=k(e.split(".")[0]);return!!this.options.find((i)=>i.names.some((s)=>k(s)===t))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:i,options:s,helpCallback:n}=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 r=Oe(t.map((f)=>f.rawName)),c=new Map,h=[];for(let f of t)if(f.namespace){if(!c.has(f.namespace))c.set(f.namespace,[]);c.get(f.namespace).push(f)}else h.push(f);let l="";if(h.sort((f,_)=>f.rawName<_.rawName?-1:f.rawName>_.rawName?1:0),h.length>0)l+=h.map((f)=>` ${L(f.rawName,r.length)} ${f.description}`).join(`
|
|
7
7
|
`);let y=Array.from(c.keys()).sort();for(let f of y){let _=c.get(f);if(l.length>0)l+=`
|
|
8
8
|
|
|
9
9
|
`;l+=` ${f}:
|
|
10
|
-
`,l+=_.map((be)=>` ${
|
|
11
|
-
`)}o.push({title:"Commands",body:l}),o.push({body:`Run \`${e} <command> --help\` for command details.`})}let d=new Set(this.options.flatMap((r)=>r.names)),a=this.isGlobalCommand?s:[...this.options,...(s||[]).filter((r)=>!r.names.some((c)=>d.has(c)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)a=a.filter((r)=>r.name!=="version");if(a.length>0){let r=Oe(a.map((c)=>c.rawName));o.push({title:"Options",body:a.map((c)=>` ${
|
|
10
|
+
`,l+=_.map((be)=>` ${L(be.rawName,r.length-2)} ${be.description}`).join(`
|
|
11
|
+
`)}o.push({title:"Commands",body:l}),o.push({body:`Run \`${e} <command> --help\` for command details.`})}let d=new Set(this.options.flatMap((r)=>r.names)),a=this.isGlobalCommand?s:[...this.options,...(s||[]).filter((r)=>!r.names.some((c)=>d.has(c)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)a=a.filter((r)=>r.name!=="version");if(a.length>0){let r=Oe(a.map((c)=>c.rawName));o.push({title:"Options",body:a.map((c)=>` ${L(c.rawName,r.length)} ${c.description} ${c.config.default===void 0?"":`(default: ${c.config.default})`}`).join(`
|
|
12
12
|
`)})}if(this.examples.length>0)o.push({title:"Examples",body:this.examples.map((r)=>{if(typeof r==="function")return r(e);return r}).join(`
|
|
13
13
|
`)});if(n)o=n(o)||o;console.log(o.map((r)=>r.title?`${r.title}:
|
|
14
14
|
${r.body}`:r.body).join(`
|
|
@@ -22,14 +22,14 @@ Did you mean one of these?`,d.forEach((r)=>{let c=r.length>1?`--${r}`:`-${r}`;a+
|
|
|
22
22
|
|
|
23
23
|
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new E(a,this.usageLine)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,i=[...t.options,...this.options];for(let s of i){let n=e[s.name.split(".")[0]];if(s.required){let o=i.some((m)=>m.negated&&m.names.includes(s.name));if(n===!0||n===!1&&!o)throw new E(`Option \`${s.rawName}\` requires a value.
|
|
24
24
|
|
|
25
|
-
Example: ${this.cli.name} ${this.rawName} ${s.rawName} <value>`,this.usageLine)}}}}class ee extends Z{constructor(e){super("@@global@@","",{},e)}}var Je=Z,w={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var C={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Xe(){return!0}function Ze(){let e={};e.supportsColor=Xe();function t(s,n=[]){let o=s===""?[]:[...n,s],m=function(a){if(!e.supportsColor)return a;let r="",c="";for(let h of o)if(h in C&&C[h]in w){let l=C[h];r+=w[l][0],c=w[l][1]+c}else if(h in w)r+=w[h][0],c=w[h][1]+c;return r+a+c},d=[...Object.keys(w),...Object.keys(C)];for(let a of d)if(!(a in m))Object.defineProperty(m,a,{get(){return t(a,o)}});return m}let i=[...Object.keys(w),...Object.keys(C)];for(let s of i)if(!(s in e))Object.defineProperty(e,s,{get(){return t(s)}});return e}var O=Ze();class
|
|
25
|
+
Example: ${this.cli.name} ${this.rawName} ${s.rawName} <value>`,this.usageLine)}}}}class ee extends Z{constructor(e){super("@@global@@","",{},e)}}var Je=Z,w={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var C={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Xe(){return!0}function Ze(){let e={};e.supportsColor=Xe();function t(s,n=[]){let o=s===""?[]:[...n,s],m=function(a){if(!e.supportsColor)return a;let r="",c="";for(let h of o)if(h in C&&C[h]in w){let l=C[h];r+=w[l][0],c=w[l][1]+c}else if(h in w)r+=w[h][0],c=w[h][1]+c;return r+a+c},d=[...Object.keys(w),...Object.keys(C)];for(let a of d)if(!(a in m))Object.defineProperty(m,a,{get(){return t(a,o)}});return m}let i=[...Object.keys(w),...Object.keys(C)];for(let s of i)if(!(s in e))Object.defineProperty(e,s,{get(){return t(s)}});return e}var O=Ze();class te extends Le{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ee(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(i)=>{if(console.log(`
|
|
26
26
|
|
|
27
27
|
Received ${i}, cleaning up...`),e)try{await e()}catch(s){console.error("Error during cleanup:",s)}v.exit(0)};return v.on("SIGINT",()=>t("SIGINT")),v.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,i){if(!i)i={};let s=new Je(e,t||"",i,this);return s.globalCommand=this.globalCommand,this.commands.push(s),s}option(e,t,i){return this.globalCommand.option(e,t,i),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},i,s){if(this.args=e,this.options=t,i)this.matchedCommand=i;if(s)this.matchedCommandName=s;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(O.red(`
|
|
28
28
|
\u2717 Command "${e}" not found.
|
|
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=Be(e,t);if(i.length>0)console.log(O.yellow("Did you mean one of these?")),i.forEach((s)=>console.log(` ${O.dim("\u2022")} ${this.name} ${s}`)),console.log("")}console.log(O.dim("Run"),`${this.name} --help`,O.dim("to see all available commands")),v.exit(1)}async parse(e=_e,t={}){let{run:i=!0,exitOnError:s=!1}=t;if(s)try{return await this.parse(e,{run:i})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?ze(e[1]):"cli";let n=!0,o=e.slice(2),m=o[0];if(m&&!m.startsWith("-")){for(let a of this.commands)if(a.isMatched(m)){let r=this.mri(o,a);n=!1;let c={...r,args:r.args.slice(1)};this.setParsedInfo(c,a,m),this.emit(`command:${m}`,a);break}if(n){let a=o[1];if(a&&!a.startsWith("-")){let r=`${m}:${a}`;for(let c of this.commands)if(c.isMatched(r)){let h=this.mri(o,c);n=!1;let l={...h,args:h.args.slice(2)};this.setParsedInfo(l,c,r),this.emit(`command:${r}`,c);break}}}}if(n){for(let a of this.commands)if(a.name===""){n=!1;let r=this.mri(o,a);this.setParsedInfo(r,a),this.emit("command:!",a);break}}if(n){let a=this.mri(e.slice(2));this.setParsedInfo(a)}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 d={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 d}mri(e,t){let i=[...this.globalCommand.options,...t?t.options:[]],s=Pe(i),n=[],o=e.indexOf("--");if(o>-1)n=e.slice(o+1),e=e.slice(0,o);let m=Ke(e,s),d={_:m._};for(let l of Object.keys(m))if(l!=="_")d[k(l)]=m[l];let a=d._,r={"--":n},c=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let l of i){if(!c&&l.config.default!==void 0)for(let y of l.names)r[y]=l.config.default;if(Array.isArray(l.config.type)){if(h[l.name]===void 0)h[l.name]={shouldTransform:!0,transformFunction:l.config.type[0]}}}for(let l of Object.keys(d))if(l!=="_"){let y=l.split(".");We(r,y,d[l]),Fe(r,h)}for(let l of i){if(!l.variadic)continue;for(let y of l.names){let f=r[y];if(f===void 0||Array.isArray(f))continue;if(l.config.default!==void 0&&f===l.config.default)continue;r[y]=[f]}}return{args:a,options:r}}async run(e=_e){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!Ue(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.`;v.stderr.write(`${i}${t}${s}
|
|
32
|
-
`),v.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((d,a)=>{if(d.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t);let n={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(n);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,a=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...n,next:a})}else await m()};await a()}else await m();for(let d of i.afterHooks)await d(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.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
|
|
32
|
+
`),v.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((d,a)=>{if(d.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t);let n={command:i,args:s,options:t};for(let d of i.beforeHooks)await d(n);let o,m=async()=>{let d=i.commandAction.apply(this,s);if(d instanceof Promise)o=await d;else o=d;return o};if(i.middleware.length>0){let d=0,a=async()=>{if(d<i.middleware.length){let r=i.middleware[d++];await r({...n,next:a})}else await m()};await a()}else await m();for(let d of i.afterHooks)await d(n);return o}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return v.removeAllListeners("SIGINT"),v.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 je{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 Wt=new je;function et(){if("FORCE_COLOR"in I.env)return I.env.FORCE_COLOR!=="0";if("NO_COLOR"in I.env||I.env.TERM==="dumb")return!1;if(I.platform==="win32")return!0;return qe.isatty(1)&&qe.isatty(2)}var Ae=et();function g(e,t){if(!Ae)return(i)=>i;return(i)=>e+i+t}var tt=g("\x1B[0m","\x1B[0m"),it=g("\x1B[31m","\x1B[39m"),st=g("\x1B[32m","\x1B[39m"),rt=g("\x1B[33m","\x1B[39m"),nt=g("\x1B[34m","\x1B[39m"),at=g("\x1B[35m","\x1B[39m"),ot=g("\x1B[36m","\x1B[39m"),lt=g("\x1B[37m","\x1B[39m"),ct=g("\x1B[90m","\x1B[39m"),ut=g("\x1B[1m","\x1B[22m"),dt=g("\x1B[3m","\x1B[23m"),mt=g("\x1B[4m","\x1B[24m"),ht=g("\x1B[2m","\x1B[22m"),ft=g("\x1B[7m","\x1B[27m"),pt=g("\x1B[8m","\x1B[28m"),gt=g("\x1B[9m","\x1B[29m"),bt=g("\x1B[41m","\x1B[49m"),yt=g("\x1B[42m","\x1B[49m"),$t=g("\x1B[43m","\x1B[49m"),vt=g("\x1B[44m","\x1B[49m"),wt=g("\x1B[45m","\x1B[49m"),xt=g("\x1B[46m","\x1B[49m"),Ct=g("\x1B[47m","\x1B[49m"),St=Ae,Ot={reset:tt,red:it,green:st,yellow:rt,blue:nt,magenta:at,cyan:ot,white:lt,gray:ct,bold:ut,italic:dt,underline:mt,dim:ht,inverse:ft,hidden:pt,strikethrough:gt,bgRed:bt,bgGreen:yt,bgYellow:$t,bgBlue:vt,bgMagenta:wt,bgCyan:xt,bgWhite:Ct,isColorSupported:St},It=Ot,Et=["up","down","left","right","space","enter","cancel"],Kt={actions:new Set(Et),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var Yt=kt.platform.startsWith("win"),Qt=Symbol("clapp:cancel");var _t=Ge();var p=(e,t)=>_t?e:t,Jt=p("\u25C6","*"),Xt=p("\u25A0","x"),Zt=p("\u25B2","x"),ei=p("\u25C7","o"),ti=p("\u250C","T"),qt=p("\u2502","|"),ii=p("\u2514","\u2014"),si=p("\u25CF",">"),ri=p("\u25CB"," "),ni=p("\u25FB","[\u2022]"),ai=p("\u25FC","[+]"),oi=p("\u25FB","[ ]"),li=p("\u25AA","\u2022"),ci=p("\u2500","-"),ui=p("\u256E","+"),di=p("\u251C","+"),mi=p("\u256F","+"),hi=p("\u25CF","\u2022"),fi=p("\u25C6","*"),pi=p("\u25B2","!"),gi=p("\u25A0","x");var bi={light:p("\u2500","-"),heavy:p("\u2501","="),block:p("\u2588","#")};function Mt(){return`${It.gray(qt)} `}var yi=Mt();class Ve{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Me.homedir(),t=K.join(e,".config","clapp");this.configPath=K.join(t,"telemetry.json")}async isEnabled(){if(x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true")return!1;if(x.env.NO_TELEMETRY==="1"||x.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:Me.platform(),nodeVersion:x.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:x.env.DO_NOT_TRACK==="1"||x.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Bt(this.configPath)){let e=await D.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=K.dirname(this.configPath);await D.mkdir(t,{recursive:!0}),await D.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 Si=new Ve;var pe="0.3.13";var u=new te("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 he(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 A({tables:i});console.log(`import { defineModel } from 'bun-query-builder'
|
|
33
33
|
|
|
34
34
|
${s.map((n)=>n.source).join(`
|
|
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 xe(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await De()});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 Ce(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 ve(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 de(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").option("--from-db","Diff the models against the live database instead of the model snapshot").option("--strict","Fail when the migrated schema does not match the models").example("query-builder migrate ./app/Models --dialect postgres").example("query-builder migrate ./app/Models --from-db --strict").action(async(e,t)=>{try{await S(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full,fromDb:t.fromDb}),await A(void 0,{strict:t.strict,auditDrift:t.strict?"always":!0})}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 ue(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 H(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 Q({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 N(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await S(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await A()}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 N(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 G(e.class,{verbose:e.verbose});else await M({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 G(e.class,{verbose:e.verbose});else await M({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 Ee(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 $e({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 he(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 V(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 U()}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 Se()}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 we({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 Te(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 F()}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 ce()}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 q({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 j({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 K()}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 se()}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 W(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 fe(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 ne()}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 re()}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 ie({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 te({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 J(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 ke(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 ae(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 oe(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let n=await import("process");n.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 le({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(ge)});u.version(ge);u.help();u.parse();
|
|
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 ve(e,t,i)});u.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await Ee()});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 Re(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 ke(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 fe(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").option("--from-db","Diff the models against the live database instead of the model snapshot").option("--strict","Fail when the migrated schema does not match the models").example("query-builder migrate ./app/Models --dialect postgres").example("query-builder migrate ./app/Models --from-db --strict").action(async(e,t)=>{try{await S(e,{dialect:t.dialect,state:t.state,apply:t.apply,full:t.full,fromDb:t.fromDb}),await N(void 0,{strict:t.strict,auditDrift:t.strict?"always":!0})}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 de(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 Q(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 G({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 M(e,{dialect:t.dialect,state:t.state}),console.log("-- Generating fresh migrations..."),await S(e,{dialect:t.dialect,state:t.state,full:t.full}),console.log("-- Executing migrations..."),await N()}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 M(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 P({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 P({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 $e(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 xe({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 ge(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 H(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 V()}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 De()}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 Se({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 we(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 j()}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 ue()}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 W({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 q({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 F()}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 ae()}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 U(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 me(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 re()}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 ie()}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 se({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 ne({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 z(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 Ce(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 oe(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 le(e,t,{format:i.format,truncate:i.truncate})}catch(s){console.error("-- Import failed:",s);let n=await import("process");n.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 ce({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(pe)});u.version(pe);u.help();u.parse();
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{pt,S,N,Je,M}from"./chunk-ev6akmaa.js";import"./chunk-bhm321nb.js";import"./chunk-2v1zv4hb.js";import"./chunk-ztdtt4hj.js";import"./chunk-jypmc6m3.js";import"./chunk-wvae8521.js";export{N as executeMigration,Je as executeMigrationWithReport,S as generateMigration,M as resetDatabase,pt as saveMigrationSnapshot};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
class Mt{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityMappings)for(let e of t.entityMappings)this.registerEntity(e)}createTable(t){return{...t,billingMode:t.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(t){return{tableName:t}}registerEntity(t){this.entityMappings.set(t.entityType,t)}getEntityMapping(t){return this.entityMappings.get(t)}buildPrimaryKey(t,e){let i=this.entityMappings.get(t);if(!i)throw Error(`No entity mapping found for type: ${t}`);let n=this.interpolatePattern(i.pkPattern,e),r=this.interpolatePattern(i.skPattern,e);return{pk:n,sk:r}}parseEntityFromItem(t){let e=t.pk||t.PK;if(!e)return null;for(let[i,n]of this.entityMappings){let r=n.pkPattern.split("${")[0];if(e.startsWith(r))return{entityType:i,data:this.unmarshall(t)}}return null}buildQueryParams(t){return{tableName:t.tableName??this.config.tableName??"",keyConditions:t.keyConditions??[],...t}}buildScanParams(t){return{tableName:t.tableName??this.config.tableName??"",...t}}buildGetItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildPutItemParams(t){return{tableName:t.tableName??this.config.tableName??"",item:t.item??{},...t}}buildUpdateItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},updateExpressions:t.updateExpressions??{},...t}}buildDeleteItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildBatchGetItemParams(t){return{requestItems:t.requestItems??{}}}buildBatchWriteItemParams(t){return{requestItems:t.requestItems??{}}}buildTransactWriteParams(t){return{transactItems:t.transactItems??[],...t}}buildKeyConditionExpression(t){return this.buildExpression(t,"AND")}buildFilterExpression(t){return this.buildExpression(t,"AND")}buildUpdateExpression(t){let e={},i={},n=[],r=0;if(t.set&&Object.keys(t.set).length>0){let a=[];for(let[s,o]of Object.entries(t.set)){let l=`#attr${r}`,c=`:val${r}`;e[l]=s,i[c]=this.marshallValue(o),a.push(`${l} = ${c}`),r++}n.push(`SET ${a.join(", ")}`)}if(t.remove&&t.remove.length>0){let a=[];for(let s of t.remove){let o=`#attr${r}`;e[o]=s,a.push(o),r++}n.push(`REMOVE ${a.join(", ")}`)}if(t.add&&Object.keys(t.add).length>0){let a=[];for(let[s,o]of Object.entries(t.add)){let l=`#attr${r}`,c=`:val${r}`;e[l]=s,i[c]=this.marshallValue(o),a.push(`${l} ${c}`),r++}n.push(`ADD ${a.join(", ")}`)}if(t.delete&&Object.keys(t.delete).length>0){let a=[];for(let[s,o]of Object.entries(t.delete)){let l=`#attr${r}`,c=`:val${r}`;e[l]=s,i[c]=this.marshallValue(o),a.push(`${l} ${c}`),r++}n.push(`DELETE ${a.join(", ")}`)}return{expression:n.join(" "),expressionAttributeNames:e,expressionAttributeValues:i}}buildProjectionExpression(t){let e={},i=[];return t.forEach((n,r)=>{let a=`#proj${r}`;e[a]=n,i.push(a)}),{expression:i.join(", "),expressionAttributeNames:e}}marshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return e}unmarshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.unmarshallValue(n);return e}interpolatePattern(t,e){return t.replace(/\$\{(\w+)\}/g,(i,n)=>{if(!(n in e))throw Error(`Missing value for pattern key: ${n}`);return String(e[n])})}buildExpression(t,e){let i={},n={},r=[];return t.forEach((a,s)=>{let o=`#attr${s}`;i[o]=a.attribute;let l;switch(a.operator){case"=":case"<":case"<=":case">":case">=":{let c=`:val${s}`;n[c]=this.marshallValue(a.value),l=`${o} ${a.operator} ${c}`;break}case"BETWEEN":{let c=`:val${s}a`,y=`:val${s}b`;n[c]=this.marshallValue(a.values?.[0]),n[y]=this.marshallValue(a.values?.[1]),l=`${o} BETWEEN ${c} AND ${y}`;break}case"begins_with":{let c=`:val${s}`;n[c]=this.marshallValue(a.value),l=`begins_with(${o}, ${c})`;break}case"contains":{let c=`:val${s}`;n[c]=this.marshallValue(a.value),l=`contains(${o}, ${c})`;break}case"attribute_exists":l=`attribute_exists(${o})`;break;case"attribute_not_exists":l=`attribute_not_exists(${o})`;break;case"attribute_type":{let c=`:val${s}`;n[c]={S:a.value},l=`attribute_type(${o}, ${c})`;break}case"IN":{let c=(a.values??[]).map((y,d)=>`:val${s}_${d}`);a.values?.forEach((y,d)=>{n[`:val${s}_${d}`]=this.marshallValue(y)}),l=`${o} IN (${c.join(", ")})`;break}default:throw Error(`Unknown operator: ${a.operator}`)}r.push(l)}),{expression:r.join(` ${e} `),expressionAttributeNames:i,expressionAttributeValues:n}}marshallValue(t){if(t===null||t===void 0)return{NULL:!0};if(typeof t==="string")return{S:t};if(typeof t==="number")return{N:String(t)};if(typeof t==="boolean")return{BOOL:t};if(t instanceof Uint8Array||Buffer.isBuffer(t))return{B:t};if(Array.isArray(t)){if(t.length===0)return{L:[]};let e=typeof t[0],i=t.every((r)=>typeof r==="string"),n=t.every((r)=>typeof r==="number");if(i)return{SS:t};if(n)return{NS:t.map(String)};return{L:t.map((r)=>this.marshallValue(r))}}if(typeof t==="object"){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return{M:e}}return{S:String(t)}}unmarshallValue(t){if(!t||typeof t!=="object")return t;if("S"in t)return t.S;if("N"in t)return Number(t.N);if("BOOL"in t)return t.BOOL;if("NULL"in t)return null;if("B"in t)return t.B;if("SS"in t)return t.SS;if("NS"in t)return t.NS.map(Number);if("BS"in t)return t.BS;if("L"in t)return t.L.map((e)=>this.unmarshallValue(e));if("M"in t){let e={};for(let[i,n]of Object.entries(t.M))e[i]=this.unmarshallValue(n);return e}return t}}function u(t){return new Mt(t)}async function S(t,e){let i=t instanceof ArrayBuffer?t:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",n,new TextEncoder().encode(e))}async function _(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(e)).map((i)=>i.toString(16).padStart(2,"0")).join("")}async function G(t,e,i,n){let r=await S(new TextEncoder().encode(`AWS4${t}`),e),a=await S(r,i),s=await S(a,n);return S(s,"aws4_request")}async function W(t,e,i,n,r,a,s){let l=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),c=l.slice(0,8),y=e.pathname,d=e.search.slice(1),m={...i,host:e.host,"x-amz-date":l};if(r.sessionToken)m["x-amz-security-token"]=r.sessionToken;let g=Object.keys(m).sort(),D=g.map((T)=>`${T.toLowerCase()}:${m[T].trim()}`).join(`
|
|
3
|
+
`)+`
|
|
4
|
+
`,A=g.map((T)=>T.toLowerCase()).join(";"),E=await _(n),M=[t,y,d,D,A,E].join(`
|
|
5
|
+
`),K=await _(M),I="AWS4-HMAC-SHA256",P=`${c}/${a}/${s}/aws4_request`,L=[I,l,P,K].join(`
|
|
6
|
+
`),O=await G(r.secretAccessKey,c,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${I} Credential=${r.accessKeyId}/${P}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class Z{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await W("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let c=JSON.parse(o);l=c.message??c.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function k(t){return new Z(t)}var p={region:process.env.AWS_REGION??"us-east-1"},B=null,v=null;function Pt(t){p={...p,...t},B=null,v=null}function h(){if(!B)B=k({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return B}function b(){if(!v)v=u({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return v}class Ze{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new w(this)}static async find(t){let e=this,i=h(),n=b(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=h(),n=b(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let c=new e(l);return c._exists=!0,c}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=h(),n=b(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let c=[],y={},d={},m=0;for(let[g,D]of Object.entries(l)){let A=`#attr${m}`,E=`:val${m}`;y[A]=g,d[E]=n.marshall({v:D}).v,c.push(`${A} = ${E}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:d});for(let[g,D]of Object.entries(l))this._attributes[g]=D,this[g]=D;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=h(),i=b(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class w{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=b(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let c=o.values.map((y,d)=>`:flt${r}_${d}`);o.values.forEach((y,d)=>{n[`:flt${r}_${d}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${c.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let c=`:flt${r}a`,y=`:flt${r}b`;n[c]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${c} AND ${y}`)}else if(o.operator==="begins_with"){let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${c})`)}else{let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${c}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=h(),e=b(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=h(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=b();if(e)this._startKey=e;this._limitValue=t;let n=h(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let c=i.unmarshall(l),y=new this.ModelClass(c);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function C(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function Oe(t){let e=et(t);return tt(e)}function et(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function tt(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Be(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),c=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!c.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,d=e.streamSpecification?.enabled;if(y!==d)if(d)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:C(e)}}function Ot(t,e){return C(t)===C(e)}var f="_qb_migrations",x="MIGRATION",R="VERSION";class ee{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(f),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${f}`),await this.client.createTable({TableName:f,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(f),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${x}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${x}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${x}#${t}`,s=`${R}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:C(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:f,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:f,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${x}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${x}#${t}`;for(let n of e){let r=`${R}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:f,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class _e{client;tracker;config;constructor(t){this.config=t,this.client=k({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new ee(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=Oe(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Be(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function nt(t){return new _e(t)}async function Bt(t,e){return nt(e).migrateModels(t)}class rt{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((c,y)=>`:flt${r}_${y}`);s.values.forEach((c,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:c}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class N{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=u(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new rt(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[c,y]of Object.entries(i.update.set)){let d=`#set${o}`,m=`:set${o}`;a[d]=c,s[m]=this.driver.marshall({v:y}).v,l.push(`${d} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[c,y]of Object.entries(i.update.add)){let d=`#add${o}`,m=`:add${o}`;a[d]=c,s[m]={N:String(y)},l.push(`${d} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let c of i.update.remove){let y=`#rem${o}`;a[y]=c,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var rn=new N;function sn(){return new N}
|
|
7
|
+
export{Mt,u,Z,k,Pt,Ze,C,Oe,et,tt,Be,Ot,f,ee,_e,nt,Bt,rt,rn,sn};
|