bun-query-builder 0.3.7 → 0.3.9
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 +8 -8
- package/dist/{chunk-3htakbmy.js → chunk-284e3ka8.js} +7 -7
- package/dist/{chunk-bpwg9p8b.js → chunk-3hwsz4q7.js} +1 -1
- package/dist/{chunk-baxpnvev.js → chunk-56n17myf.js} +1 -1
- package/dist/chunk-8zpn75gg.js +2 -0
- package/dist/{chunk-7dxm19yj.js → chunk-9wck98bv.js} +2 -2
- package/dist/{chunk-vmptnnff.js → chunk-dj2eazhq.js} +2 -2
- package/dist/chunk-ygwkzhkh.js +3 -0
- package/dist/db.d.ts +1 -0
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-b5fh1hw4.js +0 -3
- package/dist/chunk-w84w1rrf.js +0 -2
|
@@ -61,7 +61,7 @@ export type ConfigOf = Config
|
|
|
61
61
|
`;return c}}function qo(i,o,c={}){return ps(i,o,c,new WeakMap)}function ps(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return ys(i,o,u,f);if(!re(o)||!re(i))return o;return Yo(i,o,c,f)}function ys(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return Ho(i,o);case"smart":return zo(i,o,f);default:return o}return o}function Ho(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>vr(u,f)))c.push(f);return c}function zo(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(re(o[0])&&re(i[0]))return Go(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function Go(i,o,c){let f=[...o];for(let u of i){if(!re(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((y)=>re(y)&&(d in y)&&y[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function Yo(i,o,c,f){let u=o;if(re(u)&&f.has(u))return f.get(u);let g={...i};if(re(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],p=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(re(d)&&re(p))g[h]=ps(p,d,c,f);else if(Array.isArray(d)||Array.isArray(p))g[h]=ys(p,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function ws(i,o,c="replace"){return qo(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function vr(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!vr(i[c],o[c]))return!1;return!0}if(re(i)&&re(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!vr(i[u],o[u]))return!1}return!0}return!1}function re(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class bs{extensions=Bn;async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let y=bt.getWithFileCheck("file",i);if(y){if(d)console.log(`Configuration loaded from cache: ${i}`);return y}}let p=async()=>{if(!gt(i))return null;try{let y=`?t=${Date.now()}`,w=await import(i+y),S=w.default||w,E="default"in w,v=Object.keys(w).length>0;if(!E&&!v)throw new Ot(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof S!=="object"||S===null||Array.isArray(S))throw new Ot(i,Error("Configuration must export a valid object"),"unknown");let A={config:ws(o,S,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)bt.setWithFileCheck("file",A,i,g);return A}catch(y){throw y instanceof Error?ye.configLoad(i,y):ye.configLoad(i,Error(String(y)))}};if(h)return Er.track("loadFromPath",p,{path:i});return p()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){return Ws({name:i,directory:o,alias:c})}generateNamePatterns(i,o){return jn({name:i,alias:o})}checkFileAccess(i){return Uo(async()=>gt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!gt(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=In(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=In(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((c)=>c.test(i))}async validateConfigFile(i){let o=[];try{if(!gt(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}var Zo=/^https?:\/\//;class Ss{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:p=!1}=c,y=async()=>{let w=[],S=[],E={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:p};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,E);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],E);else return this.validateWithJSONSchema(i,o,E)}catch(v){return w.push({path:"",message:`Validation failed: ${v}`,rule:"system"}),{isValid:!1,errors:w,warnings:S}}};if(d)return await Er.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,o,c){try{if(!Jo(o))throw new Pt(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new Pt(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,p]of Object.entries(o.properties))if(d in h){let y=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],p,y,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let p of Object.keys(h))if(!d.has(p))u.push({path:c?`${c}.${p}`:p,message:`Additional property '${p}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Zo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ie=new It("bunfig",{showTags:!0});function Xo(i){if(!i)return"";let o=Array.isArray(i)?i.filter(Boolean):[i];if(o.length===0)return"";if(o.length===1)return` or alias "${o[0]}"`;return` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`}class vs{fileLoader=new bs;envProcessor=new Or;validator=new Ss;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let p=this.checkCache(h.name||"",h);if(p)return p}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(p){if(h.configFile)throw p;let y=h.__strictErrorHandling;if(p instanceof Error&&p.name==="ConfigNotFoundError"){if(y)throw p;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(p instanceof Error&&p.name==="ConfigLoadError"){let w=p.message.includes("EACCES")||p.message.includes("EPERM")||p.message.includes("permission denied"),S=!w&&(p.message.includes("syntax")||p.message.includes("Expected")||p.message.includes("Unexpected")||p.message.includes("BuildMessage")||p.message.includes("errors building")),E=p.message.includes("Configuration must export a valid object")||p.message.includes("Configuration file is empty and exports nothing");if(y&&(E||w))throw p;if(S&&(!y||!E))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${p.message}`]};else throw p}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${p instanceof Error?p.message:String(p)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let p={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(p);if(f.slowThreshold&&p.duration>f.slowThreshold)ie.warn(`Slow configuration loading detected: ${p.duration}ms for ${h.name}`);d.metrics=p}return d}catch(d){if(d instanceof Error&&d.name==="ConfigNotFoundError")throw d;let p=Date.now()-o;throw ie.error(`Configuration loading failed after ${p}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,configFile:g,cwd:h,configDir:d,defaultConfig:p,checkEnv:y=!0,arrayStrategy:w="replace",verbose:S=!1}=i,E=h||Nt.cwd(),v=[];if(g){let K=ce(E,g);v.push(K);let ne=y?Ne(f,p,S):p,Z=await this.fileLoader.tryLoadFromPaths([K],ne,{arrayStrategy:w,verbose:S,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!Z)throw ye.configNotFound(f||g,v,u);if(S)ie.success(`Configuration loaded from explicit path: ${K}`);return this.finalizeResult(Z,v,y,f,S)}let x=await this.loadLocalConfiguration(f,u,E,d,p,w,S,y,c);if(x)return v.push(...this.getLocalSearchPaths(f,u,E,d)),this.finalizeResult(x,v,y,f,S);let C=await this.loadHomeConfiguration(f,u,p,w,S,y);if(C)return v.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(C,v,y,f,S);let A=await this.loadPackageJsonConfiguration(f,u,E,p,w,S,y);if(A)return v.push(ce(E,"package.json")),this.finalizeResult(A,v,y,f,S);if(v.push(...this.getAllSearchPaths(f,u,E,d)),o)throw ye.configNotFound(f,v,u);return{...await this.applyEnvironmentVariables(f,p,y,S),warnings:[`No configuration file found for "${f}"${Xo(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,p){let y=d?Ne(i,u,h):u,w=this.getLocalDirectories(c,f);for(let S of w){if(h)ie.info(`Searching for configuration in: ${S}`);let E=this.fileLoader.generateConfigPaths(i,S,o),v=await this.fileLoader.tryLoadFromPaths(E,y,{arrayStrategy:g,verbose:h,cacheTtl:p?.ttl,useCache:!p?.ttl||p.ttl>100});if(v){if(h)ie.success(`Configuration loaded from: ${v.source.path}`);return v}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?Ne(i,c,u):c,d=[ce(be(),".config",i),ce(be(),".config"),be()];for(let p of d){if(u)ie.info(`Checking home directory: ${p}`);let y=this.fileLoader.generateConfigPaths(i,p,o),w=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:u});if(w){if(u)ie.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?Ne(i,f,g):f;try{let p=ce(c,"package.json");if(!Us(p))return null;let y={};try{y=JSON.parse(qs(p,"utf8"))}catch(E){if(g)ie.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let w=y[i],S=i;if(!w&&o){let E=Array.isArray(o)?o:[o];for(let v of E){if(!v)continue;if(y[v]){w=y[v],S=v;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(g)ie.success(`Configuration loaded from package.json: ${S}`);return{config:ws(d,w,u),source:{type:"package.json",path:p,priority:30,timestamp:new Date}}}}catch(p){if(g)ie.warn("Failed to load package.json:",[p instanceof Error?p:Error(String(p))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ne(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw ye.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return bt.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);bt.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias){let f=Array.isArray(o.alias)?o.alias.join(","):o.alias;c.push(`alias:${f}`)}if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configFile)c.push(`configFile:${o.configFile}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Qs({cwd:i,configDir:o})}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(ce(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[ce(be(),".config",i),ce(be(),".config"),be()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}var lr=new vs;async function Es(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await lr.loadConfig(i);else f=await lr.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){if(i.configFile)throw f;let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ie.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await lr.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}function Ne(i,o,c=!1){let f=new Or,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let p={...h};for(let[y,w]of Object.entries(h)){let S=[...d,y],E=[`${u}_${S.join("_").toUpperCase()}`,`${u}_${S.map((C)=>C.toUpperCase()).join("")}`,`${u}_${S.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],v,x;for(let C of E)if(v=Nt.env[C],v!==void 0){x=C;break}if(v!==void 0&&x)if(typeof w==="boolean")p[y]=["true","1","yes"].includes(v.toLowerCase());else if(typeof w==="number"){let C=Number(v);if(!Number.isNaN(C))p[y]=C}else if(Array.isArray(w))try{p[y]=JSON.parse(v)}catch{p[y]=v.split(",").map((C)=>C.trim())}else p[y]=v;else if(w&&typeof w==="object"&&!Array.isArray(w))p[y]=g(w,S)}return p}return g(o)}var il=ce(Nt.cwd(),"config"),ol=ce(Nt.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var nt={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},Ts=new Set(["__proto__","constructor","prototype"]);function Cs(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function Pr(i,o,c=new Set){let f={...i};c.add(o);for(let u of Object.keys(o)){if(Ts.has(u))continue;let g=o[u];if(Cs(g)&&!c.has(g)){let h=f[u];f[u]=Pr(Cs(h)?h:{},g,c)}else f[u]=g}return c.delete(o),f}var ea=Symbol.for("bun-query-builder.config"),e=globalThis[ea]??=Pr({},nt),ta=Symbol.for("bun-query-builder.config-state"),_t=globalThis[ta]??={explicit:new Set,fileLoaded:!1};function P(i){if(i)return rt(i);let o=$s.env.DB_DIALECT||$s.env.DB_CONNECTION;if(o)return rt(o);return e.dialect||"postgres"}function rt(i){let o=i.trim().toLowerCase();if(o==="turso"||o==="libsql")return"sqlite";return o}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,o=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${o}`;for(let f=1;f<i;f++)c+=`, $${o+f}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function B(){if(!_t.fileLoaded){_t.fileLoaded=!0;let i=await Es({name:"query-builder",alias:"qb",defaultConfig:nt}),o={};for(let[c,f]of Object.entries(i??{}))if(!_t.explicit.has(c))o[c]=f;As(o)}return e}var Ue=null,xs=new Set;function As(i){let o=Pr(e,i),c=e;for(let f of Object.keys(o)){if(Ts.has(f))continue;c[f]=o[f]}}function _e(i){if(i.dialect&&Ue&&i.dialect!==Ue){let o=`${Ue}->${i.dialect}`;if(!xs.has(o))xs.add(o),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ue}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(i.dialect)Ue=i.dialect;for(let o of Object.keys(i))_t.explicit.add(o);As(i)}function dn(i){return i}function it(i){return typeof i==="string"&&/^(?:libsql|https?|wss?):\/\//i.test(i.trim())}function fn(i){let o;try{o=new URL(i.trim())}catch{throw new a("Invalid libSQL URL: expected libsql://, https://, http://, ws:// or wss://",{code:"LIBSQL_INVALID_URL"})}let c=o.protocol.replace(/:$/,"").toLowerCase(),f=o.searchParams.get("tls"),u=f==="0"||f==="false",g=o.searchParams.get("authToken")??void 0,h;switch(c){case"libsql":h=u?"http":"https";break;case"https":case"wss":h="https";break;case"http":case"ws":h="http";break;default:throw new a(`Unsupported libSQL URL scheme '${c}:'`,{code:"LIBSQL_INVALID_URL"})}if(o.username||o.password)throw new a("libSQL URLs must not embed credentials; pass the token as authToken",{code:"LIBSQL_INVALID_URL"});let d=o.pathname.replace(/\/+$/,"");return{baseUrl:`${h}://${o.host}${d}`,authToken:g||void 0}}var ra=[[/^UNIQUE constraint failed/i,"SQLITE_CONSTRAINT_UNIQUE",2067],[/^NOT NULL constraint failed/i,"SQLITE_CONSTRAINT_NOTNULL",1299],[/^FOREIGN KEY constraint failed/i,"SQLITE_CONSTRAINT_FOREIGNKEY",787],[/^CHECK constraint failed/i,"SQLITE_CONSTRAINT_CHECK",275]],Ls={SQLITE_ERROR:1,SQLITE_INTERNAL:2,SQLITE_PERM:3,SQLITE_ABORT:4,SQLITE_BUSY:5,SQLITE_LOCKED:6,SQLITE_NOMEM:7,SQLITE_READONLY:8,SQLITE_INTERRUPT:9,SQLITE_IOERR:10,SQLITE_CORRUPT:11,SQLITE_FULL:13,SQLITE_CANTOPEN:14,SQLITE_SCHEMA:17,SQLITE_TOOBIG:18,SQLITE_CONSTRAINT:19,SQLITE_MISMATCH:20,SQLITE_MISUSE:21,SQLITE_RANGE:25};class a extends Error{code;errno;libsqlCode;status;constructor(i,o){super(i,o.cause===void 0?void 0:{cause:o.cause});this.name="LibSQLError",this.code=o.code,this.errno=o.errno,this.libsqlCode=o.libsqlCode,this.status=o.status}}function Ie(i){let c=String(i.message??"libSQL statement failed").replace(/^SQLite error:\s*/i,""),f=i.code??void 0;for(let[u,g,h]of ra)if(u.test(c))return new a(c,{code:g,errno:h,libsqlCode:f});if(f&&f in Ls)return new a(c,{code:f,errno:Ls[f],libsqlCode:f});if(f==="SQL_PARSE_ERROR"||f==="SQL_INPUT_ERROR")return new a(c,{code:"SQLITE_ERROR",errno:1,libsqlCode:f});return new a(c,{code:f??"LIBSQL_ERROR",libsqlCode:f})}var na=-(2n**63n),sa=2n**63n-1n;function Nr(i){return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function jt(i){if(i===null||i===void 0)return{type:"null"};switch(typeof i){case"string":return{type:"text",value:i};case"boolean":return{type:"integer",value:i?"1":"0"};case"number":if(!Number.isFinite(i))throw RangeError(`Cannot bind ${i} to a libSQL statement: only finite numbers are allowed`);return Number.isSafeInteger(i)?{type:"integer",value:String(i===0?0:i)}:{type:"float",value:i};case"bigint":if(i<na||i>sa)throw RangeError(`Cannot bind ${i} to a libSQL statement: it does not fit in a 64-bit integer`);return{type:"integer",value:i.toString()}}if(i instanceof Date){if(Number.isNaN(i.getTime()))throw RangeError("Cannot bind an invalid Date to a libSQL statement");return{type:"text",value:i.toISOString()}}if(i instanceof Uint8Array)return{type:"blob",base64:Nr(i)};if(i instanceof ArrayBuffer)return{type:"blob",base64:Nr(new Uint8Array(i))};if(ArrayBuffer.isView(i))return{type:"blob",base64:Nr(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))};throw TypeError(`Cannot bind a value of type ${Object.prototype.toString.call(i).slice(8,-1)} to a libSQL statement; serialize it first (e.g. JSON.stringify)`)}function qt(i,o="bigint"){switch(i.type){case"null":return null;case"integer":{let c=Number(i.value);if(Number.isSafeInteger(c))return c;return o==="string"?i.value:BigInt(i.value)}case"float":return typeof i.value==="number"?i.value:Number(i.value);case"text":return i.value;case"blob":{let c=Buffer.from(i.base64??"","base64");return new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}default:throw new a(`Unknown libSQL value type '${i.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"})}}function mn(i,o="bigint"){let c=i.cols.map((d,p)=>d.name??String(p)),f=i.rows.map((d)=>{let p={};for(let y=0;y<c.length;y++)p[c[y]]=qt(d[y]??{type:"null"},o);return p}),u=Number(i.affected_row_count??0),g=i.last_insert_rowid==null?null:qt({type:"integer",value:i.last_insert_rowid},o),h=(d)=>({value:d,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperties(f,{changes:h(u),count:h(u>0?u:f.length),lastInsertRowid:h(g),columns:h(c)}),f}function Le(i,o=[]){if(!Array.isArray(o)){let f=Object.entries(o).map(([u,g])=>({name:/^[:@$]/.test(u)?u:`:${u}`,value:jt(g)}));return{sql:i,named_args:f,want_rows:!0}}let c=Mt(i,[...o]);return{sql:c.sql,args:c.params.map(jt),want_rows:!0}}var ia=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i,oa=/^\s*PRAGMA\s+(?:main\.)?foreign_keys\s*(?:=\s*|\(\s*)['"]?(\w+)['"]?\s*\)?\s*;?\s*$/i;function aa(i){let o=oa.exec(i);return o?o[1].toUpperCase():null}class Os{baseUrl;authToken;timeoutMs;fetchImpl;constructor(i){let o=fn(i.url);this.baseUrl=o.baseUrl,this.authToken=i.authToken||o.authToken,this.timeoutMs=i.timeoutMs,this.fetchImpl=i.fetch??fetch}async pipeline(i,o,c){let f={"content-type":"application/json"};if(this.authToken)f.authorization=`Bearer ${this.authToken}`;let u;try{u=await this.fetchImpl(`${i}/v3/pipeline`,{method:"POST",headers:f,body:JSON.stringify({baton:o,requests:c}),signal:this.timeoutMs?AbortSignal.timeout(this.timeoutMs):void 0})}catch(h){let d=h instanceof Error?h.message:String(h);throw new a(`Could not reach the libSQL server at ${this.baseUrl}: ${d}`,{code:"LIBSQL_CONNECTION_FAILED",cause:h})}if(!u.ok){let h=await ca(u),d=h?` (${h})`:"";if(u.status===401||u.status===403)throw new a(`The libSQL server at ${this.baseUrl} rejected the request: HTTP ${u.status}${d}. `+(this.authToken?"The auth token was refused - check that it belongs to this database and has not expired.":"No auth token was sent - set one (TURSO_AUTH_TOKEN in Stacks)."),{code:"LIBSQL_UNAUTHORIZED",status:u.status});if(u.status===404)throw new a(`The libSQL server at ${this.baseUrl} has no Hrana v3 pipeline endpoint (HTTP 404). Check the URL, and that the server is sqld 0.21+ or Turso.`,{code:"LIBSQL_NOT_FOUND",status:404});throw new a(`The libSQL server at ${this.baseUrl} answered HTTP ${u.status}${d}`,{code:"LIBSQL_HTTP_ERROR",status:u.status})}let g=await u.json();if(!g||!Array.isArray(g.results))throw new a(`The libSQL server at ${this.baseUrl} sent a reply that is not a Hrana pipeline response`,{code:"LIBSQL_PROTOCOL_ERROR"});return g}}async function ca(i){try{let o=(await i.text()).trim();if(!o)return"";try{let c=JSON.parse(o),f=c.error??c.message;if(typeof f==="string")return f}catch{}return o.slice(0,300)}catch{return""}}class Ps{http;prelude;baton=null;baseUrl;tail=Promise.resolve();opened=!1;closed=!1;constructor(i,o){this.http=i;this.prelude=o;this.baseUrl=i.baseUrl}send(i,o={}){let c=async()=>{if(this.closed)throw new a("This libSQL stream is closed",{code:"LIBSQL_STREAM_CLOSED"});let u=this.opened?[]:this.prelude();this.opened=!0;let g=[...u,...i];if(o.close)g.push({type:"close"});let h;try{h=await this.http.pipeline(this.baseUrl,this.baton,g)}catch(d){throw this.closed=!0,d}if(this.baton=h.baton,h.base_url)this.baseUrl=h.base_url.replace(/\/+$/,"");if(o.close||h.baton===null)this.closed=!0;for(let d=0;d<u.length;d++){let p=h.results[d];if(p?.type==="error")throw Ie(p.error)}return h.results.slice(u.length,u.length+i.length)},f=this.tail.then(c,c);return this.tail=f.catch(()=>{}),f}async close(){if(this.closed)return;if(!this.opened){this.closed=!0;return}await this.send([],{close:!0})}}function He(i){if(!i)throw new a("The libSQL server sent fewer results than requests",{code:"LIBSQL_PROTOCOL_ERROR"});if(i.type==="error")throw Ie(i.error);if(i.response.type!=="execute")throw new a(`Expected an execute result, got '${i.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});return i.response.result}function ks(i){if(i?.type==="ok"&&i.response.type==="get_autocommit")return i.response.is_autocommit;return!1}class Ns{http;largeIntegers;foreignKeys=null;pinned=null;closed=!1;constructor(i){this.http=new Os(i),this.largeIntegers=i.largeIntegers??"bigint"}prelude=()=>this.foreignKeys?[{type:"execute",stmt:{sql:`PRAGMA foreign_keys = ${this.foreignKeys}`,want_rows:!1}}]:[];openStream(){return this.assertOpen(),new Ps(this.http,this.prelude)}assertOpen(){if(this.closed)throw new a("Cannot use a closed libSQL connection",{code:"LIBSQL_CLOSED"})}rows(i){return mn(i,this.largeIntegers)}notePragma(i){let o=aa(i);if(o)this.foreignKeys=o==="OFF"||o==="0"||o==="FALSE"||o==="NO"?"OFF":"ON"}async execute(i){this.assertOpen();let o=ia.test(i.sql);if(this.pinned){let g=this.pinned,h=[{type:"execute",stmt:i}];if(o)h.push({type:"get_autocommit"});let d;try{d=await g.send(h)}catch(y){if(this.pinned===g)this.pinned=null;throw y}if(o&&ks(d[1])){if(this.pinned===g)this.pinned=null;await g.close().catch(()=>{})}let p=this.rows(He(d[0]));return this.notePragma(i.sql),p}if(o){let g=this.openStream(),h;try{h=await g.send([{type:"execute",stmt:i},{type:"get_autocommit"}])}catch(p){throw await g.close().catch(()=>{}),p}if(h[0]?.type!=="error"&&!ks(h[1]))this.pinned=g;else await g.close().catch(()=>{});return this.rows(He(h[0]))}let c=this.openStream(),[f]=await c.send([{type:"execute",stmt:i}],{close:!0}),u=this.rows(He(f));return this.notePragma(i.sql),u}async close(){this.closed=!0;let i=this.pinned;this.pinned=null,await i?.close().catch(()=>{})}}function Fs(i,o){return{async execute(c){let[f]=await o.send([{type:"execute",stmt:c}]),u=i.rows(He(f));return i.notePragma(c.sql),u},async sequence(c){let f=[];for(let u of c)f.push(await this.execute(u));return f}}}function la(i){return{execute:(o)=>i.execute(o),async sequence(o){if(i.pinned){let f=[];for(let u of o)f.push(await i.execute(u));return f}let c=i.openStream();try{let f=[];for(let u of o)f.push(await Fs(i,c).execute(u));return f}finally{await c.close().catch(()=>{})}}}}function Rs(i){return{__raw:!0,value:i,toString:()=>i}}function fa(i,o){let c=i[0],f=[];for(let u=0;u<o.length;u++){let g=o[u],h=Ir(g);if(h&&typeof h.sql==="string"&&Array.isArray(h.values))c+=h.sql+(i[u+1]||""),f.push(...h.values);else if(h&&(h.__raw||h.raw)){let d=h.raw,p=h.__raw?h.value:typeof d==="string"?d:d();c+=p+(i[u+1]||"")}else if(Array.isArray(g))c+=g.map(()=>"?").join(", ")+(i[u+1]||""),f.push(...g);else c+=`?${i[u+1]||""}`,f.push(g)}return{sql:c,params:f}}function Fr(i,o,c,f){let u=()=>{try{return i.target.execute(Le(o,c))}catch(h){return Promise.reject(h)}},g={sql:o,values:c,execute:u,raw:()=>o,toString:()=>o,cancel:()=>{}};if(f)g.then=(h,d)=>u().then(h,d);return g}function Dr(i){function o(c,...f){if(Array.isArray(c)&&"raw"in c){let{sql:u,params:g}=fa(c,f);return Fr(i,u,g,!1)}if(typeof c==="string")return Rs(c);return Fr(i,"",[],!1)}return o.raw=(c)=>Rs(c),o.unsafe=(c,f=[])=>Fr(i,c,f??[],!0),o.query=(c,f)=>{try{return i.target.execute(Le(c,f??[]))}catch(u){return Promise.reject(u)}},o.file=async(c)=>{let{readFileSync:f}=await import("fs"),u=_r(f(c,"utf-8")).map((g)=>g.trim()).filter((g)=>g&&!g.startsWith("--"));return await i.target.sequence(u.map((g)=>Le(g))),[]},o.batch=async(c)=>{if(i.session.assertOpen(),c.length===0)return[];let f=i.stream!==null,u=c.map((E)=>Le(E.sql,E.args??[])),g=[];if(!f)g.push({stmt:{sql:"BEGIN"}});for(let E of u)g.push({stmt:E,condition:g.length?{type:"ok",step:g.length-1}:null});if(!f){let E=g.length-1;g.push({stmt:{sql:"COMMIT"},condition:{type:"ok",step:E}}),g.push({stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:E+1}}})}let h=i.stream??i.session.openStream(),d;try{d=await h.send([{type:"batch",batch:{steps:g}}],{close:!f})}finally{if(!f)await h.close().catch(()=>{})}let p=d[0];if(!p)throw new a("The libSQL server sent no batch result",{code:"LIBSQL_PROTOCOL_ERROR"});if(p.type==="error")throw Ie(p.error);if(p.response.type!=="batch")throw new a(`Expected a batch result, got '${p.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});let{step_results:y,step_errors:w}=p.response.result,S=f?0:1;for(let E=0;E<w.length;E++){let v=w[E];if(v)throw Ie(v)}return u.map((E,v)=>{let x=y[v+S];if(!x)throw new a(`Batch statement ${v+1} did not run`,{code:"LIBSQL_BATCH_SKIPPED"});return i.session.rows(x)})},o.begin=async(c,f)=>{let u=typeof c==="function"?c:f;if(typeof u!=="function")throw TypeError("[query-builder] libsql begin(): a transaction callback is required");if(i.session.assertOpen(),i.stream){let w=`qb_sp_${i.depth}`,S=i.target;await S.execute({sql:`SAVEPOINT ${w}`});let E=Dr({...i,depth:i.depth+1});try{let v=await u(E);return await S.execute({sql:`RELEASE SAVEPOINT ${w}`}),v}catch(v){try{await S.execute({sql:`ROLLBACK TO SAVEPOINT ${w}`}),await S.execute({sql:`RELEASE SAVEPOINT ${w}`})}catch{}throw v}}let g=i.session.openStream(),h=Fs(i.session,g);try{await h.execute({sql:"BEGIN"})}catch(w){throw await g.close().catch(()=>{}),w}let d=Dr({session:i.session,target:h,stream:g,depth:1}),p;try{p=await u(d)}catch(w){try{await g.send([{type:"execute",stmt:{sql:"ROLLBACK"}}],{close:!0})}catch{await g.close().catch(()=>{})}throw w}let[y]=await g.send([{type:"execute",stmt:{sql:"COMMIT"}}],{close:!0});return He(y),p},o.savepoint=o.begin,o.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on libSQL. Use begin()/transaction().")},o.close=async()=>{if(i.stream)return;await i.session.close()},o.libsql={url:i.session.http.baseUrl,transaction:i.stream!==null},o}function Wt(i){let o=new Ns(i);return Dr({session:o,target:la(o),stream:null,depth:0})}function Wn(i){return(typeof i==="function"||typeof i==="object"&&i!==null)&&typeof i.libsql==="object"&&i.libsql!==null}var Ut=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Vt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:Ut}function k(i){for(let o of Vt())try{i.run(o)}catch{}}function ze(i){return`"${i.replaceAll('"','""')}"`}class Mr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,o)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(o),f=c.map((h)=>{let d=o[h];if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength).slice();return d??null}),u=JSON.stringify([i,c]),g=512+u.length*2+f.reduce((h,d)=>h+(typeof d==="string"?d.length*2:ArrayBuffer.isView(d)?d.byteLength:16),0);if(this.hasPending&&(this.pending.length>=32||this.bytes+g>262144))this.flush();return new Promise((h,d)=>{let p={table:i,columns:c,values:f,shape:u,uncached:g>262144,resolve:h,reject:d};if(this.database.inTransaction||g>262144){this.writeOne(p);return}this.pending.push(p),this.bytes+=g,this.timer??=setImmediate(()=>this.flush())})};flush(){if(this.timer!==void 0)clearImmediate(this.timer),this.timer=void 0;let i=this.pending;this.pending=[],this.bytes=0;for(let o=0;o<i.length;){if(this.failure){for(let u of i.slice(o))u.reject(this.failure);return}let c=o+1;while(c<i.length&&i[c].shape===i[o].shape)c++;let f=i.slice(o,c);if(o=c,f.length===1||!f[0].columns.length||this.database.inTransaction){for(let u of f)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=f[0],g=`(${u.columns.map(()=>"?").join(",")})`,h=`INSERT INTO ${ze(u.table)} (${u.columns.map(ze).join(",")}) VALUES ${f.map(()=>g).join(",")}`;this.database.query(h).run(...f.flatMap((d)=>d.values))})();for(let u of f)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let g of[...f,...i.slice(o)])g.reject(u);return}for(let g of f)this.writeOne(g)}}}writeOne(i){let o=!1;try{this.assertUsable(),o=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${ze(i.table)} (${i.columns.map(ze).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${ze(i.table)} DEFAULT VALUES`,f=()=>{if(!i.uncached)return this.database.query(c).run(...i.values);let u=this.database.prepare(c);try{return u.run(...i.values)}finally{u.finalize()}};if(o)f();else this.database.transaction(f)();i.resolve()}catch(c){if(!this.failure&&!o&&this.database.inTransaction)this.invalidate(c);i.reject(c)}}assertUsable(){if(this.failure)throw this.failure}invalidate(i){this.failure=Error("SQLite connection is unusable after deferred insert rollback failed",{cause:i});try{this.database.close()}catch{}}close(){this.closed=!0,this.flush()}}function Br(i){return i}function Ir(i){return i!==null&&typeof i==="object"?i:null}function Mt(i,o){if(o.length===0||!/\$\d/.test(i))return{sql:i,params:o};let c=[],f="",u=0;for(let g=0;g<i.length;g++){let h=i[g];if(h==="'"||h==='"'||h==="`"){let d=da(i,g,h);f+=i.slice(g,d),g=d-1;continue}if(h==="-"&&i[g+1]==="-"){let d=i.indexOf(`
|
|
62
62
|
`,g),p=d===-1?i.length:d;f+=i.slice(g,p),g=p-1;continue}if(h==="/"&&i[g+1]==="*"){let d=i.indexOf("*/",g+2),p=d===-1?i.length:d+2;f+=i.slice(g,p),g=p-1;continue}if(h==="$"){let d=/^\d+/.exec(i.slice(g+1))?.[0];if(d){let p=Number(d);if(u=Math.max(u,p),p>=1&&p<=o.length){c.push(o[p-1]),f+="?",g+=d.length;continue}}}f+=h}if(u>o.length)throw Error(`SQL references $${u} but only ${o.length} value${o.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:o};return{sql:f,params:c}}function da(i,o,c){for(let f=o+1;f<i.length;f++){if(i[f]!==c)continue;if(i[f+1]===c){f++;continue}return f+1}return i.length}var jr=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class Bs{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let o=ga(i);if(o&&o!==".")ha(o,{recursive:!0})}this.db=new ua(i),k(this.db)}deferInsert=(i,o)=>{if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));if(!this.deferredInserts){let c=this.deferredInserts=new Mr(this.db),f=this.query.bind(this),u=this.run.bind(this),g=(h)=>{if(c.hasPending&&!jr.test(h))c.flush();c.assertUsable()};this.query=(h,d)=>(g(h),f(h,d)),this.run=(h,d)=>(g(h),u(h,d))}return this.deferredInserts.append(i,o)};flushDeferredInserts(){this.deferredInserts?.flush()}query(i,o=[]){let c=Mt(i,o),f=c.params.length>0||jr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).all(...c.params)}run(i,o=[]){let c=Mt(i,o),f=c.params.length>0||jr.test(c.sql),u=f?this.db.query(c.sql):this.db.prepare(c.sql);return(f&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).run(...c.params)}close(){this.closed=!0,this.deferredInserts?.close(),this.db.close()}get database(){return this.db}}function Is(i){return{__raw:!0,value:i,toString:()=>i}}function _s(i){let o=i.trimStart();for(;;)if(o.startsWith("--")){let c=o.indexOf(`
|
|
63
63
|
`);o=c===-1?"":o.slice(c+1).trimStart()}else if(o.startsWith("/*")){let c=o.indexOf("*/");o=c===-1?"":o.slice(c+2).trimStart()}else return o}function _r(i){let o=[],c="",f=!1,u=!1,g=!1,h=!1;for(let p=0;p<i.length;p++){let y=i[p],w=i[p+1];if(!f&&!u&&!h&&y==="-"&&w==="-"){g=!0,c+=y;continue}if(g&&(y===`
|
|
64
|
-
`||y==="\r")){g=!1,c+=y;continue}if(!f&&!u&&!g&&y==="/"&&w==="*"){h=!0,c+=y;continue}if(h&&y==="*"&&w==="/"){h=!1,c+=y+w,p++;continue}if(g||h){c+=y;continue}if(y==="'"&&!u){if(f&&w==="'"){c+=y+w,p++;continue}f=!f,c+=y;continue}if(y==='"'&&!f){u=!u,c+=y;continue}if(y===";"&&!f&&!u){let S=_s(c.trim());if(S)o.push(S);c="";continue}c+=y}let d=_s(c.trim());if(d)o.push(d);return o}function Ms(i){let o=new Bs(i);function c(h,d){let p=h.trim().toUpperCase();if(p.startsWith("SELECT")||p.startsWith("PRAGMA")||/\bRETURNING\b/.test(p))return o.query(h,Br(d));return o.run(h,Br(d))}function f(h,...d){let p=h[0],y=[];for(let S=0;S<d.length;S++){let E=d[S],v=Ir(E);if(v&&typeof v.sql==="string"&&Array.isArray(v.values))p+=v.sql+(h[S+1]||""),y.push(...v.values);else if(v&&(v.__raw||v.raw)){let x=v.raw,C=v.__raw?v.value:typeof x==="string"?x:x();p+=C+(h[S+1]||"")}else if(Array.isArray(E)){let x=E.map(()=>"?").join(", ");p+=x+(h[S+1]||""),y.push(...E)}else p+=`?${h[S+1]||""}`,y.push(E)}let w=()=>c(p,y);return{sql:p,values:y,executeSync:w,execute:()=>{try{return Promise.resolve(w())}catch(S){return Promise.reject(S)}},raw:()=>p,toString:()=>p,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Is(h);return f([""])}u.raw=(h)=>Is(h),u.unsafe=(h,d=[])=>{let p=()=>c(h,d),y=()=>{try{return Promise.resolve(p())}catch(w){return Promise.reject(w)}};return{sql:h,values:d,execute:y,executeSync:p,then:(w,S)=>y().then(w,S),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let p=o.query(h,Br(d||[]));return Promise.resolve(p)}catch(p){return Promise.reject(p)}},u.file=async(h,d)=>{try{let{readFileSync:p}=await import("fs"),y=p(h,"utf-8"),w=_r(y);for(let S of w){let E=S.trim();if(!E||E.startsWith("--"))continue;let v=E.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))o.query(S);else o.run(S)}return Promise.resolve([])}catch(p){return Promise.reject(p)}};let g=0;return u.begin=async(h,d)=>{let p=typeof h==="function"?h:d;if(typeof p!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let y=g>0,w=`qb_sp_${g}`;if(y)o.run(`SAVEPOINT ${w}`);else o.run("BEGIN");g++;try{let S=await p(u);if(g--,y)o.run(`RELEASE SAVEPOINT ${w}`);else o.run("COMMIT");return S}catch(S){g--;try{if(y)o.run(`ROLLBACK TO SAVEPOINT ${w}`),o.run(`RELEASE SAVEPOINT ${w}`);else o.run("ROLLBACK")}catch{}throw S}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=o,u}function ma(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function Ke(i=e.database){let o=Ge.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function pa(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ge.env.DB_CONNECTION===i){let y=Ge.env,w=(y.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),S=y.DB_USERNAME||o.username,E=y.DB_PASSWORD??o.password??"",v=y.DB_HOST||o.host||"localhost",x=y.DB_PORT||o.port,C=i==="postgres"?"postgres":"mysql",A=y.DB_SSL==="true"||y.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${C}://${S}:${E}@${v}${x?`:${x}`:""}/${w}${A}`}if(o.url)return i==="sqlite"?ma(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,p=d||Ge.env.DB_SSL==="true"||Ge.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function js(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);return o}function _(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=it(i.url)?i.url:it(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function ya(){let i=e.dialect,o=_(e.database,i);if(o)return Wt(o);let c=pa(i,e.database);try{if(i==="sqlite")return Ms(c);let f=js(e.database.pool);return Object.keys(f).length>0?new Ds(c,f):new Ds(c)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return Ms(":memory:");throw f}}var Pe=null,Kr=null;function wa(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,authToken:i.authToken,pool:js(i.pool)})}function b(i=!1){let o=wa();if(i||Pe!==null&&Kr!==o||!Pe)Ks(),Pe=ya(),Kr=o;return Pe}function Ks(){let i=Pe;return i?.flushDeferredInserts?.(),Pe=null,Kr=null,i}async function ba(i){if(!i||typeof i.close!=="function")return;await i.close()}function hn(){ba(Ks()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function st(i){try{return await i(b())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=b(!0);return await i(c)}throw o}}function Sa(){return new Proxy(function(){},{get(i,o){let c=b(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return b()(...c)}})}var r=Sa();function Fe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function T(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Fe(String(i?.name??""))}function gn(i){return i.endsWith("s")?i.slice(0,-1):i}function pn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return pn;return gn}var Ht="1 = 0";function D(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function at(i,o){if(o!=="postgres")return i;return je(i,(c)=>`$${c}`).text}function X(i){return je(i,()=>{return}).count}function je(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=va(i,g,h);else if(h==="-"&&i[g+1]==="-"){let p=i.indexOf(`
|
|
64
|
+
`||y==="\r")){g=!1,c+=y;continue}if(!f&&!u&&!g&&y==="/"&&w==="*"){h=!0,c+=y;continue}if(h&&y==="*"&&w==="/"){h=!1,c+=y+w,p++;continue}if(g||h){c+=y;continue}if(y==="'"&&!u){if(f&&w==="'"){c+=y+w,p++;continue}f=!f,c+=y;continue}if(y==='"'&&!f){u=!u,c+=y;continue}if(y===";"&&!f&&!u){let S=_s(c.trim());if(S)o.push(S);c="";continue}c+=y}let d=_s(c.trim());if(d)o.push(d);return o}function Ms(i){let o=new Bs(i);function c(h,d){let p=h.trim().toUpperCase();if(p.startsWith("SELECT")||p.startsWith("PRAGMA")||/\bRETURNING\b/.test(p))return o.query(h,Br(d));return o.run(h,Br(d))}function f(h,...d){let p=h[0],y=[];for(let S=0;S<d.length;S++){let E=d[S],v=Ir(E);if(v&&typeof v.sql==="string"&&Array.isArray(v.values))p+=v.sql+(h[S+1]||""),y.push(...v.values);else if(v&&(v.__raw||v.raw)){let x=v.raw,C=v.__raw?v.value:typeof x==="string"?x:x();p+=C+(h[S+1]||"")}else if(Array.isArray(E)){let x=E.map(()=>"?").join(", ");p+=x+(h[S+1]||""),y.push(...E)}else p+=`?${h[S+1]||""}`,y.push(E)}let w=()=>c(p,y);return{sql:p,values:y,executeSync:w,execute:()=>{try{return Promise.resolve(w())}catch(S){return Promise.reject(S)}},raw:()=>p,toString:()=>p,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Is(h);return f([""])}u.raw=(h)=>Is(h),u.unsafe=(h,d=[])=>{let p=()=>c(h,d),y=()=>{try{return Promise.resolve(p())}catch(w){return Promise.reject(w)}};return{sql:h,values:d,execute:y,executeSync:p,then:(w,S)=>y().then(w,S),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let p=o.query(h,Br(d||[]));return Promise.resolve(p)}catch(p){return Promise.reject(p)}},u.file=async(h,d)=>{try{let{readFileSync:p}=await import("fs"),y=p(h,"utf-8"),w=_r(y);for(let S of w){let E=S.trim();if(!E||E.startsWith("--"))continue;let v=E.toUpperCase();if(v.startsWith("SELECT")||v.startsWith("PRAGMA"))o.query(S);else o.run(S)}return Promise.resolve([])}catch(p){return Promise.reject(p)}};let g=0;return u.begin=async(h,d)=>{let p=typeof h==="function"?h:d;if(typeof p!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let y=g>0,w=`qb_sp_${g}`;if(y)o.run(`SAVEPOINT ${w}`);else o.run("BEGIN");g++;try{let S=await p(u);if(g--,y)o.run(`RELEASE SAVEPOINT ${w}`);else o.run("COMMIT");return S}catch(S){g--;try{if(y)o.run(`ROLLBACK TO SAVEPOINT ${w}`),o.run(`RELEASE SAVEPOINT ${w}`);else o.run("ROLLBACK")}catch{}throw S}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=o,u}function ma(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function Ke(i=e.database){let o=Ge.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function pa(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ge.env.DB_CONNECTION===i){let y=Ge.env,w=(y.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),S=y.DB_USERNAME||o.username,E=y.DB_PASSWORD??o.password??"",v=y.DB_HOST||o.host||"localhost",x=y.DB_PORT||o.port,C=i==="postgres"?"postgres":"mysql",A=y.DB_SSL==="true"||y.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${C}://${S}:${E}@${v}${x?`:${x}`:""}/${w}${A}`}if(o.url)return i==="sqlite"?ma(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,p=d||Ge.env.DB_SSL==="true"||Ge.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${p}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function js(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);if(typeof i.preparedStatements==="boolean")o.prepare=i.preparedStatements;return o}function _(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=it(i.url)?i.url:it(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function ya(){let i=e.dialect,o=_(e.database,i);if(o)return Wt(o);let c=pa(i,e.database);try{if(i==="sqlite")return Ms(c);let f=js(e.database.pool);return Object.keys(f).length>0?new Ds(c,f):new Ds(c)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return Ms(":memory:");throw f}}var Pe=null,Kr=null;function wa(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,authToken:i.authToken,pool:js(i.pool)})}function b(i=!1){let o=wa();if(i||Pe!==null&&Kr!==o||!Pe)Ks(),Pe=ya(),Kr=o;return Pe}function Ks(){let i=Pe;return i?.flushDeferredInserts?.(),Pe=null,Kr=null,i}async function ba(i){if(!i||typeof i.close!=="function")return;await i.close()}function hn(){ba(Ks()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function st(i){try{return await i(b())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=b(!0);return await i(c)}throw o}}function Sa(){return new Proxy(function(){},{get(i,o){let c=b(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return b()(...c)}})}var r=Sa();function Fe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function T(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Fe(String(i?.name??""))}function gn(i){return i.endsWith("s")?i.slice(0,-1):i}function pn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return pn;return gn}var Ht="1 = 0";function D(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function at(i,o){if(o!=="postgres")return i;return je(i,(c)=>`$${c}`).text}function X(i){return je(i,()=>{return}).count}function je(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=va(i,g,h);else if(h==="-"&&i[g+1]==="-"){let p=i.indexOf(`
|
|
65
65
|
`,g+2);d=p===-1?i.length:p}else if(h==="/"&&i[g+1]==="*"){let p=1;d=g+2;while(d<i.length&&p>0)if(i[d]==="/"&&i[d+1]==="*")p++,d+=2;else if(i[d]==="*"&&i[d+1]==="/")p--,d+=2;else d++}else if(h==="$"){let p=i.slice(g).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(p){let y=i.indexOf(p,g+p.length);d=y===-1?i.length:y+p.length}}if(d!==-1){g=d;continue}if(h==="?"){f++;let p=o(f);if(p!==void 0)c+=i.slice(u,g)+p,u=g+1}g++}return{text:u===0?i:c+i.slice(u),count:f}}function va(i,o,c){let f=o+1;while(f<i.length){if(i[f]===c){if(i[f+1]===c){f+=2;continue}return f+1}f++}return i.length}function qe(i,o,c=Number.POSITIVE_INFINITY){let f=[],u=0,g=(h)=>h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||h===95;for(let h=0;h<i.length;h++){let d=i.charCodeAt(h);if(d===45&&i.charCodeAt(h+1)===45){let y=i.indexOf(`
|
|
66
66
|
`,h+2);if(y===-1)return f;h=y;continue}if(d===47&&i.charCodeAt(h+1)===42){let y=1,w=h+2;while(w<i.length&&y>0)if(i[w]==="/"&&i[w+1]==="*")y++,w+=2;else if(i[w]==="*"&&i[w+1]==="/")y--,w+=2;else w++;h=w-1;continue}if(d===39||d===34||d===96){let y=h+1;while(y<i.length){if(i.charCodeAt(y)===d){if(i.charCodeAt(y+1)===d){y+=2;continue}break}y++}h=y;continue}if(d===36){let y=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(h));if(y){let w=i.indexOf(y[0],h+y[0].length);h=w===-1?i.length:w+y[0].length-1;continue}}if(d===40){u++;continue}if(d===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(h===0)continue;let p=d&-33;if(p<65||p>90)continue;if(g(i.charCodeAt(h-1)))continue;for(let{key:y,pattern:w}of o){w.lastIndex=h;let S=w.exec(i);if(!S)continue;if(f.push({key:y,start:h,length:S[0].length}),f.length>=c)return f;h+=S[0].length-1;break}}return f}
|
|
67
67
|
export{n,nt,e,P,rt,t,s,B,_e,dn,it,fn,a,Ie,jt,qt,mn,Le,Wt,Wn,Ut,Vt,k,Ke,_,b,hn,st,r,Fe,T,gn,pn,m,Ht,D,l,at,X,je,qe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rn,sn,an,on,ln,Ft,cn,un}from"./chunk-
|
|
2
|
+
import{rn,sn,an,on,ln,Ft,cn,un}from"./chunk-dj2eazhq.js";import"./chunk-3hwsz4q7.js";import"./chunk-93ny6tvm.js";export{ln as clearModelRegistry,cn as defineModel,sn as getAllModels,rn as getModel,an as getModelRegistry,on as hasModel,un as registerBrowserModels,Ft as registerModel};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ht,w,R,Qe,A}from"./chunk-284e3ka8.js";import"./chunk-ygwkzhkh.js";import"./chunk-9wck98bv.js";import"./chunk-dj2eazhq.js";import"./chunk-3hwsz4q7.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};
|
|
@@ -3,5 +3,5 @@ class At{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityM
|
|
|
3
3
|
`)+`
|
|
4
4
|
`,A=g.map((T)=>T.toLowerCase()).join(";"),k=await w(n),M=[t,y,d,D,A,k].join(`
|
|
5
5
|
`),K=await w(M),P="AWS4-HMAC-SHA256",_=`${c}/${a}/${s}/aws4_request`,L=[P,l,_,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=`${P} Credential=${r.accessKeyId}/${_}, 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 x(t){return new z(t)}var p={region:process.env.AWS_REGION??"us-east-1"},B=null,N=null;function Nt(t){p={...p,...t},B=null,N=null}function h(){if(!B)B=x({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return B}function b(){if(!N)N=u({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return N}class Ye{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 R(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}`,k=`:val${m}`;y[A]=g,d[k]=n.marshall({v:D}).v,c.push(`${A} = ${k}`),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 R{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 v(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 Ne(t){let e=Xe(t);return Ze(e)}function Xe(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 Ze(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 Me(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:v(e)}}function Mt(t,e){return v(t)===v(e)}var f="_qb_migrations",E="MIGRATION",C="VERSION";class Y{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=`${E}#${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=`${E}#${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=`${E}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:v(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(`${E}#`,"");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=`${E}#${t}`;for(let n of e){let r=`${C}#${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 Oe{client;tracker;config;constructor(t){this.config=t,this.client=x({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new Y(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=Ne(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=Me(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 et(t){return new Oe(t)}async function Ot(t,e){return et(e).migrateModels(t)}class tt{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 I{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 tt(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 tn=new I;function nn(){return new I}
|
|
7
|
-
export{At,u,z,x,
|
|
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=`${P} Credential=${r.accessKeyId}/${_}, 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 x(t){return new z(t)}var p={region:process.env.AWS_REGION??"us-east-1"},B=null,N=null;function Mt(t){p={...p,...t},B=null,N=null}function h(){if(!B)B=x({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return B}function b(){if(!N)N=u({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return N}class Ye{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 R(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}`,k=`:val${m}`;y[A]=g,d[k]=n.marshall({v:D}).v,c.push(`${A} = ${k}`),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 R{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 v(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 Me(t){let e=Xe(t);return Ze(e)}function Xe(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 Ze(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 Ne(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:v(e)}}function Nt(t,e){return v(t)===v(e)}var f="_qb_migrations",E="MIGRATION",C="VERSION";class Y{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=`${E}#${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=`${E}#${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=`${E}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:v(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(`${E}#`,"");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=`${E}#${t}`;for(let n of e){let r=`${C}#${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 Oe{client;tracker;config;constructor(t){this.config=t,this.client=x({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new Y(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=Me(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=Ne(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 et(t){return new Oe(t)}async function Ot(t,e){return et(e).migrateModels(t)}class tt{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 I{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 tt(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 tn=new I;function nn(){return new I}
|
|
7
|
+
export{At,u,z,x,Mt,Ye,v,Me,Xe,Ze,Ne,Nt,f,Y,Oe,et,Ot,tt,tn,nn};
|