bun-query-builder 0.2.60 → 0.2.62

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.
@@ -1,22 +1,22 @@
1
1
  // @bun
2
- import{Tb as Ll,Wb as Kl}from"./chunk-mvk2rcqm.js";import{Yb as Zt}from"./chunk-mjedm810.js";import{pc as Xm,qc as lg,rc as ut,sc as ze}from"./chunk-fn0m2c0v.js";import{existsSync as Qi,statSync as Vi}from"fs";import{resolve as _n}from"path";import Fc from"process";import{existsSync as Wc,mkdirSync as sy,readdirSync as iy,readFileSync as Uc,writeFileSync as oy}from"fs";import{homedir as dn}from"os";import{dirname as cy,resolve as bt}from"path";import qr from"process";import{existsSync as Ji,statSync as Hi}from"fs";import{existsSync as Ks,mkdirSync as Qc,readdirSync as Vc,writeFileSync as Jc}from"fs";import{homedir as fn}from"os";import{dirname as zi,resolve as Ve}from"path";import Yt from"process";import{join as Hc,relative as zc,resolve as Gi}from"path";import Cr from"process";import{existsSync as Io,mkdirSync as Ty,readdirSync as wy,writeFileSync as Dy}from"fs";import{homedir as ws}from"os";import{dirname as Ey,resolve as Qe}from"path";import Ln from"process";import{join as Gc,relative as Yc,resolve as Yi}from"path";import vr from"process";import{existsSync as Lo,mkdirSync as vy,readdirSync as Ay,writeFileSync as Ny}from"fs";import{dirname as Oy,resolve as Ar}from"path";import Fs from"process";import{Buffer as _t}from"buffer";import{createCipheriv as Xc,createDecipheriv as Zc,randomBytes as Ds}from"crypto";import{closeSync as Ss,createReadStream as Xi,createWriteStream as eu,existsSync as $s,fsyncSync as Zi,openSync as eo,writeFileSync as tu}from"fs";import{access as nu,constants as to,mkdir as ru,readdir as cr,rename as no,stat as mn,unlink as ur,writeFile as Es}from"fs/promises";import{join as gn}from"path";import Fe from"process";import{pipeline as su}from"stream/promises";import{createGzip as ro}from"zlib";import yn from"process";import xt from"process";import{Buffer as $t}from"buffer";import{createCipheriv as iu,createDecipheriv as ou,randomBytes as xs}from"crypto";import{closeSync as Rs,createReadStream as so,createWriteStream as au,existsSync as dr,fsyncSync as io,openSync as oo,writeFileSync as lu}from"fs";import{access as cu,constants as ao,mkdir as uu,readdir as fr,rename as lo,stat as hn,unlink as mr,writeFile as ks}from"fs/promises";import{isAbsolute as du,join as pn,resolve as fu}from"path";import ge from"process";import{pipeline as mu}from"stream/promises";import{createGzip as co}from"zlib";import bn from"process";import Rt from"process";import gr from"process";import{existsSync as yr}from"fs";import{resolve as Cs}from"path";import{existsSync as gu}from"fs";import{existsSync as yu,readdirSync as hu}from"fs";import{extname as vs,resolve as uo}from"path";import pu from"process";import{join as bu,relative as Tu,resolve as fo}from"path";import Nr from"process";import{Buffer as Et}from"buffer";import{createCipheriv as wu,createDecipheriv as Du,randomBytes as As}from"crypto";import{closeSync as Ns,createReadStream as mo,createWriteStream as Su,existsSync as hr,fsyncSync as go,openSync as yo,writeFileSync as $u}from"fs";import{access as Eu,constants as ho,mkdir as xu,readdir as pr,rename as po,stat as Tn,unlink as br,writeFile as Ms}from"fs/promises";import{isAbsolute as Ru,join as wn,resolve as ku}from"path";import ye from"process";import{pipeline as Cu}from"stream/promises";import{createGzip as bo}from"zlib";import Dn from"process";import kt from"process";import wr from"process";import{existsSync as Dr}from"fs";import{resolve as Mo}from"path";import{existsSync as Hd}from"fs";class Oo{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${n}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(e[n][0])}set(e,t,n,r){if(!this.options.enabled)return;let s=this.generateKey(e,n),i=r??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(e,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!Qi(e))return!0;return Vi(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let n=this.get(e,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(e,t);return}return n.value}setWithFileCheck(e,t,n,r){try{let s=Qi(n)?Vi(n):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},n,r)}catch{this.set(e,t,n,r)}}delete(e,t){let n=this.generateKey(e,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,s)=>r+s.size,0),n=e.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let e={};for(let[t,n]of this.cache.entries())e[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return e}import(e){this.cache.clear();for(let[t,n]of Object.entries(e))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Bo{metrics=[];maxMetrics=1000;async track(e,t,n={}){let r=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-r;return this.recordMetric({operation:e,duration:o,timestamp:s,...n}),i}catch(i){let o=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...n}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((s)=>s.duration),r=n.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function _o(e={}){let{name:t="",alias:n}=e,r=["config",".config"];if(t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let i of s){if(!i)continue;if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return Array.from(new Set(r.filter(Boolean)))}function qc(e){return _o(e).flatMap((n)=>Po.map((r)=>_n(e.directory,`${n}${r}`)))}function jc(e={}){let t=_n(e.cwd||Fc.cwd());return Array.from(new Set([t,_n(t,"config"),_n(t,".config"),e.configDir?_n(t,e.configDir):void 0].filter((n)=>Boolean(n))))}function Nu(e,t){this[e]=Au.bind(null,t)}class Xs{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${n}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(e[n][0])}set(e,t,n,r){if(!this.options.enabled)return;let s=this.generateKey(e,n),i=r??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(e,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!Ji(e))return!0;return Hi(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let n=this.get(e,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(e,t);return}return n.value}setWithFileCheck(e,t,n,r){try{let s=Ji(n)?Hi(n):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},n,r)}catch{this.set(e,t,n,r)}}delete(e,t){let n=this.generateKey(e,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,s)=>r+s.size,0),n=e.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let e={};for(let[t,n]of this.cache.entries())e[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return e}import(e){this.cache.clear();for(let[t,n]of Object.entries(e))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Zs{metrics=[];maxMetrics=1000;async track(e,t,n={}){let r=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-r;return this.recordMetric({operation:e,duration:o,timestamp:s,...n}),i}catch(i){let o=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...n}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((s)=>s.duration),r=n.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Bu(e,t={}){let r=Object.keys(t).sort().map((s)=>`${s}:${t[s]}`).join("|");return r?`${e}:${r}`:e}function Pu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function _u(e){return e.getStats().size*2}function ei(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Re(t[0])&&"id"in t[0]&&t[0].id===3&&Re(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Re(t)&&Re(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Re(e)&&"arr"in e&&Array.isArray(e.arr)&&Re(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Re(t[0])&&Re(e[0])){let r=[...t];for(let s of e)if(Re(s)&&"name"in s){if(!r.find((o)=>Re(o)&&("name"in o)&&o.name===s.name))r.push(s)}else if(Re(s)&&"path"in s){if(!r.find((o)=>Re(o)&&("path"in o)&&o.path===s.path))r.push(s)}else if(!r.some((i)=>Mr(i,s)))r.push(s);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}if(!Re(t)||!Re(e))return t;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let s=t[r];if(s===null||s===void 0)continue;else if(Re(s)&&Re(n[r]))n[r]=ei(n[r],s);else if(Array.isArray(s)&&Array.isArray(n[r]))if(s.length>0&&n[r].length>0&&Re(s[0])&&Re(n[r][0])){let i=[...s];for(let o of n[r])if(Re(o)&&"name"in o){if(!i.find((a)=>Re(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(Re(o)&&"path"in o){if(!i.find((a)=>Re(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((l)=>Mr(l,o)))i.push(o);n[r]=i}else if(s.every((i)=>typeof i==="string")&&n[r].every((i)=>typeof i==="string")){let i=[...s];for(let o of n[r])if(!i.includes(o))i.push(o);n[r]=i}else n[r]=s;else n[r]=s}return n}function Mr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Mr(e[n],t[n]))return!1;return!0}if(Re(e)&&Re(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Mr(e[s],t[s]))return!1}return!0}return!1}function Re(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Iu(e,t){if(!Lo(e))return null;try{let n=await import(e),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ei(t,r)}catch{return null}}catch{return null}}async function Lu({name:e="",cwd:t,defaultConfig:n}){let r=t||Fs.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],i=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of i)for(let l of s){let a=Ar(r,`${o}${l}`),c=await Iu(a,n);if(c!==null)return c}try{let o=Ar(r,"package.json");if(Lo(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return ei(n,a)}catch{}}}catch{}return n}function Ku(e,t={}){let n=vr.cwd();while(n.includes("storage"))n=Yi(n,"..");let r=Yi(n,e||"");if(t?.relative)return Yc(vr.cwd(),r);return r}async function Fu(){try{let e=await Lu({name:"clarity",defaultConfig:$r,cwd:vr.cwd(),endpoint:"",headers:{}});return{...$r,...e}}catch{return $r}}function Ce(){if(xt.env.NODE_ENV==="test"||xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qu(){if(xt.env.NODE_ENV==="test"||xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof xt<"u"){let e=xt.type;if(e==="renderer"||e==="worker")return!1;return!!(xt.versions&&(xt.versions.node||xt.versions.bun))}return!1}class Fo{async format(e){let t=await qu(),n=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:n})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:yn.pid,hostname:t(),environment:yn.env.NODE_ENV||"development",platform:yn.platform,version:yn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:yn.env.NODE_ENV||yn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Or{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...js},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fo,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Fe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Er,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Er};return{...Er,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:js.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(e){let n=(async()=>{let s,i=0,o=3,l=1000;while(i<o)try{try{try{await nu(this.config.logDirectory,to.F_OK|to.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await ru(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:_t.from(e);try{if(!$s(this.currentLogFile))await Es(this.currentLogFile,"",{mode:420});if(s=eo(this.currentLogFile,"a",420),tu(s,a,{flag:"a"}),Zi(s),s!==void 0)Ss(s),s=void 0;if((await mn(this.currentLogFile)).size===0){if(await Es(this.currentLogFile,a,{flag:"w",mode:420}),(await mn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let u=c;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,m);let h=l*2**i;await new Promise((w)=>setTimeout(w,h)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{Ss(s)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let u=a,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),a}i++;let c=l*2**(i-1);await new Promise((u)=>setTimeout(u,c))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return gn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return gn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ce())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,a])=>a.createdAt.getTime()-l.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[l]of s.slice(o))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Ds(16).toString("hex")}generateKey(){return Ds(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),n=Ds(16),r=Xc("aes-256-gcm",t,n),s=_t.concat([r.update(e,"utf8"),r.final()]),i=r.getAuthTag();return{encrypted:_t.concat([n,s,i]),iv:n}}async compressData(e){return new Promise((t,n)=>{let r=ro(),s=[];r.on("data",(i)=>s.push(i)),r.on("end",()=>t(_t.from(_t.concat(s)))),r.on("error",n),r.write(e),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ce())return;let e=await mn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await cr(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,c)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${o}`;if(await mn(n).catch(()=>null))try{if(await no(n,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await ur(l)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${n}.1`;await Es(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=n.replace(/\.log$/,`-${s}.log`);if(await mn(n).catch(()=>null))await no(n,i)}if(this.currentLogFile=r,t.maxFiles){let i=(await cr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,l)=>l.localeCompare(o));for(let o of i.slice(t.maxFiles))await ur(gn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let n=Xi(e),r=eu(t),s=ro();await su(n,s,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),$s(this.currentLogFile))try{let e=eo(this.currentLogFile,"r+");Zi(e),Ss(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await cr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await ur(gn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:n="",tag:r="",message:s,level:i,showTimestamp:o=!0}=e,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(o)w.push(t);if(i==="warning")w.push("WARN");else if(i==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(s),w.join(" ")}let a=Fe.stdout.columns||120,c="";if(i==="warning"||i==="error")c=`${n} ${s}`;else if(i==="info"||i==="success")c=`${n} ${r} ${s}`;else c=`${n} ${r} ${Ee.cyan(s)}`;if(!o)return c.trim();let u=l(c).trim().length,m=l(t).length,h=Math.max(1,a-2-u-m);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):i});let n=/%([sdijfo%])/g,r=0,s=e.replace(n,(i,o)=>{if(o==="%")return"%";if(r>=t.length)return i;let l=t[r++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return i}});if(r<t.length)s+=` ${t.slice(r).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}async log(e,t,...n){let r=new Date,s=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,n);if(this.fancy&&!Ce()){let c=Go[e],u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",m;switch(e){case"debug":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:Ee.gray(o),level:e}),console.error(m);break;case"info":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:o,level:e}),console.error(m);break;case"success":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:Ee.green(o),level:e}),console.error(m);break;case"warning":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:o,level:e}),console.warn(m);break;case"error":if(m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:o,level:e}),console.error(m),l){let h=l.split(`
2
+ import{Ub as Kl,Xb as Fl}from"./chunk-3s6cme8m.js";import{Zb as Zt}from"./chunk-79cr4zy3.js";import{qc as Zm,rc as cg,sc as ut,tc as ze}from"./chunk-w49dhqgq.js";import{existsSync as Vi,statSync as Ji}from"fs";import{resolve as In}from"path";import qc from"process";import{existsSync as Uc,mkdirSync as iy,readdirSync as oy,readFileSync as Qc,writeFileSync as ay}from"fs";import{homedir as un}from"os";import{dirname as uy,resolve as bt}from"path";import qr from"process";import{existsSync as Hi,statSync as zi}from"fs";import{existsSync as js,mkdirSync as Vc,readdirSync as Jc,writeFileSync as Hc}from"fs";import{homedir as dn}from"os";import{dirname as Gi,resolve as Ve}from"path";import Xt from"process";import{join as zc,relative as Gc,resolve as Yi}from"path";import Cr from"process";import{existsSync as Lo,mkdirSync as wy,readdirSync as Dy,writeFileSync as Sy}from"fs";import{homedir as $s}from"os";import{dirname as xy,resolve as Qe}from"path";import Kn from"process";import{join as Yc,relative as Xc,resolve as Xi}from"path";import vr from"process";import{existsSync as Ko,mkdirSync as Ay,readdirSync as Ny,writeFileSync as My}from"fs";import{dirname as By,resolve as Ar}from"path";import Ws from"process";import{Buffer as It}from"buffer";import{createCipheriv as Zc,createDecipheriv as eu,randomBytes as Es}from"crypto";import{closeSync as xs,createReadStream as Zi,createWriteStream as tu,existsSync as Rs,fsyncSync as eo,openSync as to,writeFileSync as nu}from"fs";import{access as ru,constants as no,mkdir as su,readdir as cr,rename as ro,stat as fn,unlink as ur,writeFile as ks}from"fs/promises";import{join as mn}from"path";import Fe from"process";import{pipeline as iu}from"stream/promises";import{createGzip as so}from"zlib";import gn from"process";import Rt from"process";import{Buffer as Et}from"buffer";import{createCipheriv as ou,createDecipheriv as au,randomBytes as Cs}from"crypto";import{closeSync as vs,createReadStream as io,createWriteStream as lu,existsSync as dr,fsyncSync as oo,openSync as ao,writeFileSync as cu}from"fs";import{access as uu,constants as lo,mkdir as du,readdir as fr,rename as co,stat as yn,unlink as mr,writeFile as As}from"fs/promises";import{isAbsolute as fu,join as hn,resolve as mu}from"path";import ge from"process";import{pipeline as gu}from"stream/promises";import{createGzip as uo}from"zlib";import pn from"process";import kt from"process";import gr from"process";import{existsSync as yr}from"fs";import{resolve as Ns}from"path";import{existsSync as yu}from"fs";import{existsSync as hu,readdirSync as pu}from"fs";import{extname as Ms,resolve as fo}from"path";import bu from"process";import{join as Tu,relative as wu,resolve as mo}from"path";import Nr from"process";import{Buffer as xt}from"buffer";import{createCipheriv as Du,createDecipheriv as Su,randomBytes as Os}from"crypto";import{closeSync as Bs,createReadStream as go,createWriteStream as $u,existsSync as hr,fsyncSync as yo,openSync as ho,writeFileSync as Eu}from"fs";import{access as xu,constants as po,mkdir as Ru,readdir as pr,rename as bo,stat as bn,unlink as br,writeFile as Ps}from"fs/promises";import{isAbsolute as ku,join as Tn,resolve as Cu}from"path";import ye from"process";import{pipeline as vu}from"stream/promises";import{createGzip as To}from"zlib";import wn from"process";import Ct from"process";import wr from"process";import{existsSync as Dr}from"fs";import{resolve as Oo}from"path";import{existsSync as zd}from"fs";class Bo{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${n}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(e[n][0])}set(e,t,n,r){if(!this.options.enabled)return;let s=this.generateKey(e,n),i=r??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(e,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!Vi(e))return!0;return Ji(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let n=this.get(e,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(e,t);return}return n.value}setWithFileCheck(e,t,n,r){try{let s=Vi(n)?Ji(n):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},n,r)}catch{this.set(e,t,n,r)}}delete(e,t){let n=this.generateKey(e,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,s)=>r+s.size,0),n=e.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let e={};for(let[t,n]of this.cache.entries())e[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return e}import(e){this.cache.clear();for(let[t,n]of Object.entries(e))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Po{metrics=[];maxMetrics=1000;async track(e,t,n={}){let r=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-r;return this.recordMetric({operation:e,duration:o,timestamp:s,...n}),i}catch(i){let o=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...n}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((s)=>s.duration),r=n.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Io(e={}){let{name:t="",alias:n}=e,r=["config",".config"];if(t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let i of s){if(!i)continue;if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return Array.from(new Set(r.filter(Boolean)))}function jc(e){return Io(e).flatMap((n)=>_o.map((r)=>In(e.directory,`${n}${r}`)))}function Wc(e={}){let t=In(e.cwd||qc.cwd());return Array.from(new Set([t,In(t,"config"),In(t,".config"),e.configDir?In(t,e.configDir):void 0].filter((n)=>Boolean(n))))}function Mu(e,t){this[e]=Nu.bind(null,t)}class ti{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${n}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(e[n][0])}set(e,t,n,r){if(!this.options.enabled)return;let s=this.generateKey(e,n),i=r??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(e,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!Hi(e))return!0;return zi(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let n=this.get(e,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(e,t);return}return n.value}setWithFileCheck(e,t,n,r){try{let s=Hi(n)?zi(n):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},n,r)}catch{this.set(e,t,n,r)}}delete(e,t){let n=this.generateKey(e,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,s)=>r+s.size,0),n=e.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let e={};for(let[t,n]of this.cache.entries())e[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return e}import(e){this.cache.clear();for(let[t,n]of Object.entries(e))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class ni{metrics=[];maxMetrics=1000;async track(e,t,n={}){let r=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-r;return this.recordMetric({operation:e,duration:o,timestamp:s,...n}),i}catch(i){let o=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...n}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((s)=>s.duration),r=n.reduce((s,i)=>s+i,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Pu(e,t={}){let r=Object.keys(t).sort().map((s)=>`${s}:${t[s]}`).join("|");return r?`${e}:${r}`:e}function _u(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Iu(e){return e.getStats().size*2}function ri(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Re(t[0])&&"id"in t[0]&&t[0].id===3&&Re(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Re(t)&&Re(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Re(e)&&"arr"in e&&Array.isArray(e.arr)&&Re(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Re(t[0])&&Re(e[0])){let r=[...t];for(let s of e)if(Re(s)&&"name"in s){if(!r.find((o)=>Re(o)&&("name"in o)&&o.name===s.name))r.push(s)}else if(Re(s)&&"path"in s){if(!r.find((o)=>Re(o)&&("path"in o)&&o.path===s.path))r.push(s)}else if(!r.some((i)=>Mr(i,s)))r.push(s);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}if(!Re(t)||!Re(e))return t;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let s=t[r];if(s===null||s===void 0)continue;else if(Re(s)&&Re(n[r]))n[r]=ri(n[r],s);else if(Array.isArray(s)&&Array.isArray(n[r]))if(s.length>0&&n[r].length>0&&Re(s[0])&&Re(n[r][0])){let i=[...s];for(let o of n[r])if(Re(o)&&"name"in o){if(!i.find((a)=>Re(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(Re(o)&&"path"in o){if(!i.find((a)=>Re(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((l)=>Mr(l,o)))i.push(o);n[r]=i}else if(s.every((i)=>typeof i==="string")&&n[r].every((i)=>typeof i==="string")){let i=[...s];for(let o of n[r])if(!i.includes(o))i.push(o);n[r]=i}else n[r]=s;else n[r]=s}return n}function Mr(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Mr(e[n],t[n]))return!1;return!0}if(Re(e)&&Re(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Mr(e[s],t[s]))return!1}return!0}return!1}function Re(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Lu(e,t){if(!Ko(e))return null;try{let n=await import(e),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ri(t,r)}catch{return null}}catch{return null}}async function Ku({name:e="",cwd:t,defaultConfig:n}){let r=t||Ws.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],i=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of i)for(let l of s){let a=Ar(r,`${o}${l}`),c=await Lu(a,n);if(c!==null)return c}try{let o=Ar(r,"package.json");if(Ko(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return ri(n,a)}catch{}}}catch{}return n}function Fu(e,t={}){let n=vr.cwd();while(n.includes("storage"))n=Xi(n,"..");let r=Xi(n,e||"");if(t?.relative)return Xc(vr.cwd(),r);return r}async function qu(){try{let e=await Ku({name:"clarity",defaultConfig:$r,cwd:vr.cwd(),endpoint:"",headers:{}});return{...$r,...e}}catch{return $r}}function Ce(){if(Rt.env.NODE_ENV==="test"||Rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ju(){if(Rt.env.NODE_ENV==="test"||Rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Rt<"u"){let e=Rt.type;if(e==="renderer"||e==="worker")return!1;return!!(Rt.versions&&(Rt.versions.node||Rt.versions.bun))}return!1}class qo{async format(e){let t=await ju(),n=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:n})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:gn.pid,hostname:t(),environment:gn.env.NODE_ENV||"development",platform:gn.platform,version:gn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:gn.env.NODE_ENV||gn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Or{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Qs},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new qo,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Fe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Er,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Er};return{...Er,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Qs.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(e){let n=(async()=>{let s,i=0,o=3,l=1000;while(i<o)try{try{try{await ru(this.config.logDirectory,no.F_OK|no.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await su(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:It.from(e);try{if(!Rs(this.currentLogFile))await ks(this.currentLogFile,"",{mode:420});if(s=to(this.currentLogFile,"a",420),nu(s,a,{flag:"a"}),eo(s),s!==void 0)xs(s),s=void 0;if((await fn(this.currentLogFile)).size===0){if(await ks(this.currentLogFile,a,{flag:"w",mode:420}),(await fn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let u=c;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,m);let h=l*2**i;await new Promise((w)=>setTimeout(w,h)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{xs(s)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let u=a,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),a}i++;let c=l*2**(i-1);await new Promise((u)=>setTimeout(u,c))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return mn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return mn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return mn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ce())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,a])=>a.createdAt.getTime()-l.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[l]of s.slice(o))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Es(16).toString("hex")}generateKey(){return Es(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),n=Es(16),r=Zc("aes-256-gcm",t,n),s=It.concat([r.update(e,"utf8"),r.final()]),i=r.getAuthTag();return{encrypted:It.concat([n,s,i]),iv:n}}async compressData(e){return new Promise((t,n)=>{let r=so(),s=[];r.on("data",(i)=>s.push(i)),r.on("end",()=>t(It.from(It.concat(s)))),r.on("error",n),r.write(e),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ce())return;let e=await fn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await cr(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,c)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${o}`;if(await fn(n).catch(()=>null))try{if(await ro(n,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await ur(l)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${n}.1`;await ks(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=n.replace(/\.log$/,`-${s}.log`);if(await fn(n).catch(()=>null))await ro(n,i)}if(this.currentLogFile=r,t.maxFiles){let i=(await cr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,l)=>l.localeCompare(o));for(let o of i.slice(t.maxFiles))await ur(mn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let n=Zi(e),r=tu(t),s=so();await iu(n,s,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Rs(this.currentLogFile))try{let e=to(this.currentLogFile,"r+");eo(e),xs(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await cr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await ur(mn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:n="",tag:r="",message:s,level:i,showTimestamp:o=!0}=e,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(o)w.push(t);if(i==="warning")w.push("WARN");else if(i==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(s),w.join(" ")}let a=Fe.stdout.columns||120,c="";if(i==="warning"||i==="error")c=`${n} ${s}`;else if(i==="info"||i==="success")c=`${n} ${r} ${s}`;else c=`${n} ${r} ${Ee.cyan(s)}`;if(!o)return c.trim();let u=l(c).trim().length,m=l(t).length,h=Math.max(1,a-2-u-m);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):i});let n=/%([sdijfo%])/g,r=0,s=e.replace(n,(i,o)=>{if(o==="%")return"%";if(r>=t.length)return i;let l=t[r++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return i}});if(r<t.length)s+=` ${t.slice(r).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}async log(e,t,...n){let r=new Date,s=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,n);if(this.fancy&&!Ce()){let c=Yo[e],u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",m;switch(e){case"debug":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:Ee.gray(o),level:e}),console.error(m);break;case"info":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:o,level:e}),console.error(m);break;case"success":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:Ee.green(o),level:e}),console.error(m);break;case"warning":m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:o,level:e}),console.warn(m);break;case"error":if(m=this.formatConsoleMessage({timestamp:s,icon:c,tag:u,message:o,level:e}),console.error(m),l){let h=l.split(`
3
3
  `);for(let w of h)if(w.trim()&&!w.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:Ee.gray(` ${w}`),level:e,showTimestamp:!1}))}break}}else if(!Ce()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}if(!this.shouldLog(e))return;let a=`${i} ${this.environment}.${e.toUpperCase()}: ${o}
4
4
  `;if(l)a+=`${l}
5
5
  `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!Ce()){let n=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:Ee.blue("\u25D0"),tag:n,message:`${Ee.cyan(e)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),s=Math.round(r-t),i=`${e} completed in ${s}ms`,o=new Date,l=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(n)c+=` ${JSON.stringify(n)}`;if(c+=`
6
- `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Ce()){let u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:Ee.green("\u2713"),tag:u,message:`${i}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Ce())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,n=new Or(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(Ce())throw Error("createReadStream is not supported in browser environments");if(!$s(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xi(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=_t.isBuffer(e)?e:_t.from(e,"base64"),s=r.slice(0,16),i=r.slice(-16),o=r.slice(16,-16),l=Zc("aes-256-gcm",n,s);return l.setAuthTag(i),_t.concat([l.update(o),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ce()}isServerMode(){return!Ce()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!Ce()){let i=e.split(`
6
+ `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Ce()){let u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:Ee.green("\u2713"),tag:u,message:`${i}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Ce())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,n=new Or(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(Ce())throw Error("createReadStream is not supported in browser environments");if(!Rs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zi(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=It.isBuffer(e)?e:It.from(e,"base64"),s=r.slice(0,16),i=r.slice(-16),o=r.slice(16,-16),l=eu("aes-256-gcm",n,s);return l.setAuthTag(i),It.concat([l.update(o),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ce()}isServerMode(){return!Ce()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!Ce()){let i=e.split(`
7
7
  `),o=Math.max(...i.map((u)=>u.length))+2,l=`\u250C${"\u2500".repeat(o)}\u2510`,a=`\u2514${"\u2500".repeat(o)}\u2518`,c=i.map((u)=>{let m=" ".repeat(o-u.length-2);return`\u2502 ${u}${m} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:Ee.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:Ee.cyan(l)})),c.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:Ee.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:Ee.cyan(a),showTimestamp:!1}))}else if(!Ce())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let s=`${r} ${this.environment}.INFO: [BOX] ${e}
8
8
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}async prompt(e){if(Ce())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ee.cyan("?")} ${e} (y/n) `);let n=(r)=>{let s=r.toString().trim().toLowerCase();Fe.stdin.removeListener("data",n);try{if(typeof Fe.stdin.setRawMode==="function")Fe.stdin.setRawMode(!1)}catch{}Fe.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof Fe.stdin.setRawMode==="function")Fe.stdin.setRawMode(!0)}catch{}Fe.stdin.resume(),Fe.stdin.once("data",n)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let n=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,l=0;if(n=e.replace(o,(a,c)=>{if(c==="%")return"%";if(l>=t.length)return a;let u=t[l++];switch(c){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),l<t.length)n+=` ${t.slice(l).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!Ce()){let o=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",l=Ee.blue("\u25D0");console.error(`${l} ${o} ${Ee.cyan(n)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
9
9
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||Ce()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ce())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),l!==void 0)this.activeProgressBar.message=l;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ce())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ce())return;Fe.stdout.write(`${"\r".padEnd(Fe.stdout.columns||80)}\r`),this.log(l,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Ce()||!Fe.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*n/100),s=e.barLength-r,i=Ee.green("\u2501".repeat(r)),o=Ee.gray("\u2501".repeat(s)),l=`[${i}${o}]`,a=`${n}%`.padStart(4),c=e.message?` ${e.message}`:"",u=t||n===100?Ee.green("\u2713"):Ee.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${Ee.gray(this.formatTag(this.name))}`:"",h=`\r${u}${m} ${l} ${a}${c}`,w=Fe.stdout.columns||80,N=" ".repeat(Math.max(0,w-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${N}`,Fe.stdout.write(e.lastRenderedLine),t)Fe.stdout.write(`
10
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ce()||!Fe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cr(this.config.logDirectory),n=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let i=gn(this.config.logDirectory,r);if(e.before)try{if((await mn(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}n.push(i)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await ur(r),console.warn(`Deleted log file: ${r}`)}catch(s){console.error(`Failed to delete log file ${r}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Sr(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let r=[...t];for(let s of e)if(Te(s)&&"name"in s){if(!r.find((o)=>Te(o)&&("name"in o)&&o.name===s.name))r.push(s)}else if(Te(s)&&"path"in s){if(!r.find((o)=>Te(o)&&("path"in o)&&o.path===s.path))r.push(s)}else if(!r.some((i)=>Br(i,s)))r.push(s);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}if(!Te(t)||!Te(e))return t;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let s=t[r];if(s===null||s===void 0)continue;else if(Te(s)&&Te(n[r]))n[r]=Sr(n[r],s);else if(Array.isArray(s)&&Array.isArray(n[r]))if(s.length>0&&n[r].length>0&&Te(s[0])&&Te(n[r][0])){let i=[...s];for(let o of n[r])if(Te(o)&&"name"in o){if(!i.find((a)=>Te(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(Te(o)&&"path"in o){if(!i.find((a)=>Te(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((l)=>Br(l,o)))i.push(o);n[r]=i}else if(s.every((i)=>typeof i==="string")&&n[r].every((i)=>typeof i==="string")){let i=[...s];for(let o of n[r])if(!i.includes(o))i.push(o);n[r]=i}else n[r]=s;else n[r]=s}return n}function ti(e,t,n="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return n==="replace"?t:Sr(e,t);if(Array.isArray(e))return n==="replace"?t:Sr(e,t);if(!Te(t)||!Te(e))return t;let r={...e};for(let s of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let i=t[s],o=r[s];if(i===null||i===void 0)continue;if(Array.isArray(i)||Array.isArray(o))if(n==="replace")r[s]=i;else r[s]=Sr(o,i);else if(Te(i)&&Te(o))r[s]=ti(o,i,n);else r[s]=i}return r}function Br(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Br(e[n],t[n]))return!1;return!0}if(Te(e)&&Te(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Br(e[s],t[s]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Tr(e,t,n="replace"){if(!Io(e))return null;try{let r=await import(e),s=r.default||r;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return ti(t,s,n)}catch{return null}}catch{return null}}function ju(e,t,n=!1){if(!e)return t;let r=e.toUpperCase().replace(/-/g,"_"),s={...t};function i(o,l=[]){let a={...o};for(let[c,u]of Object.entries(o)){let m=[...l,c],h=(R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${r}_${m.map(h).join("_")}`,N=`${r}_${m.map((R)=>R.toUpperCase()).join("_")}`;if(n)je.info(`Checking environment variable ${w} for config ${e}.${m.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[c]=i(u,m);else{let R=Ln.env[w]||Ln.env[N];if(R!==void 0){if(n)je.info(`Using environment variable ${R?w:N} for config ${e}.${m.join(".")}`);if(typeof u==="number")a[c]=Number(R);else if(typeof u==="boolean")a[c]=R.toLowerCase()==="true";else if(Array.isArray(u))try{let y=JSON.parse(R);if(Array.isArray(y))a[c]=y;else a[c]=R.split(",").map((b)=>b.trim())}catch{a[c]=R.split(",").map((y)=>y.trim())}else a[c]=R}}}return a}return i(s)}async function Wu({name:e="",alias:t,cwd:n,configDir:r,defaultConfig:s,verbose:i=!1,checkEnv:o=!0,arrayStrategy:l="replace"}){let a=o&&typeof s==="object"&&s!==null&&!Array.isArray(s)?ju(e,s,i):s,c=n||Ln.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(i)je.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${c}`);let m=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),w=t?[t,`.${t}`]:[],N=t?[`${t}.config`,`.${t}.config`]:[],R=Array.from(new Set([c,Qe(c,"config"),Qe(c,".config"),r?Qe(c,r):void 0].filter(Boolean)));for(let y of R){if(i)je.info(`Searching for configuration in: ${y}`);let g=[Qe(c,"config"),Qe(c,".config")].concat(r?[Qe(c,r)]:[]).includes(y)?[...m,...h,...w,...N]:[...h,...m,...N,...w];for(let p of g)for(let E of u){let D=Qe(y,`${p}${E}`),J=await Tr(D,a,l);if(J!==null){if(i)je.success(`Configuration loaded from: ${D}`);return J}}}if(e){let y=Qe(ws(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(i)je.info(`Checking user config directory: ${y}`);for(let g of b)for(let p of u){let E=Qe(y,`${g}${p}`),D=await Tr(E,a,l);if(D!==null){if(i)je.success(`Configuration loaded from user config directory: ${E}`);return D}}}if(e){let y=Qe(ws(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(i)je.info(`Checking user config directory for dotfile configs: ${y}`);for(let g of b)for(let p of u){let E=Qe(y,`${g}${p}`),D=await Tr(E,a,l);if(D!==null){if(i)je.success(`Configuration loaded from user config directory dotfile: ${E}`);return D}}}if(e){let y=ws(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(i)je.info(`Checking user home directory for dotfile configs: ${y}`);for(let g of b)for(let p of u){let E=Qe(y,`${g}${p}`),D=await Tr(E,a,l);if(D!==null){if(i)je.success(`Configuration loaded from user home directory: ${E}`);return D}}}try{let y=Qe(c,"package.json");if(Io(y)){let b=await import(y),g=b[e];if(!g&&t){if(g=b[t],g&&i)je.success(`Using alias "${t}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(i)je.success(`Configuration loaded from package.json: ${g===b[e]?e:t}`);return ti(a,g,l)}catch(p){if(i)je.warn("Failed to merge package.json config:",p)}}}catch(y){if(i)je.warn("Failed to load package.json:",y)}if(i)je.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Uu(e,t={}){let n=Cr.cwd();while(n.includes("storage"))n=Gi(n,"..");let r=Gi(n,e||"");if(t?.relative)return zc(Cr.cwd(),r);return r}async function Qu(){try{let e=await Wu({name:"clarity",alias:"logging",defaultConfig:xr,cwd:Cr.cwd()});return{...xr,...e||{}}}catch{return xr}}function Be(){if(Rt.env.NODE_ENV==="test"||Rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Vu(){if(Rt.env.NODE_ENV==="test"||Rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Rt<"u"){let e=Rt.type;if(e==="renderer"||e==="worker")return!1;return!!(Rt.versions&&(Rt.versions.node||Rt.versions.bun))}return!1}class qo{async format(e){let t=await Vu(),n=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:n})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:bn.pid,hostname:t(),environment:bn.env.NODE_ENV||"development",platform:bn.platform,version:bn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:bn.env.NODE_ENV||bn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Pr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Ws},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new qo,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ge.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[n]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rr};return{...Rr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ws.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!Be()&&this.config.writeToFile===!0}async writeToFile(e){let n=(async()=>{let s,i=0,o=3,l=1000;while(i<o)try{try{try{await cu(this.config.logDirectory,ao.F_OK|ao.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await uu(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:$t.from(e);try{if(!dr(this.currentLogFile))await ks(this.currentLogFile,"",{mode:420});if(s=oo(this.currentLogFile,"a",420),lu(s,a,{flag:"a"}),io(s),s!==void 0)Rs(s),s=void 0;if((await hn(this.currentLogFile)).size===0){if(await ks(this.currentLogFile,a,{flag:"w",mode:420}),(await hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let u=c;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,m);let h=l*2**i;await new Promise((w)=>setTimeout(w,h)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{Rs(s)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let u=a,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),a}i++;let c=l*2**(i-1);await new Promise((u)=>setTimeout(u,c))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return pn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return pn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return pn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,a])=>a.createdAt.getTime()-l.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[l]of s.slice(o))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return xs(16).toString("hex")}generateKey(){return xs(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),n=xs(16),r=iu("aes-256-gcm",t,n),s=$t.isBuffer(e)?e:$t.from(e,"utf8"),i=r.update(s),o=r.final(),l=i.length+o.length,a=r.getAuthTag(),c=$t.allocUnsafe(16+l+16);return n.copy(c,0),i.copy(c,16),o.copy(c,16+i.length),a.copy(c,16+l),{encrypted:c,iv:n}}async compressData(e){return new Promise((t,n)=>{let r=co(),s=[];r.on("data",(i)=>s.push(i)),r.on("end",()=>t($t.from($t.concat(s)))),r.on("error",n),r.write(e),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Be())return;if(!this.shouldWriteToFile())return;let e=await hn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await fr(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,c)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${o}`;if(await hn(n).catch(()=>null))try{if(await lo(n,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await mr(l)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${n}.1`;await ks(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=n.replace(/\.log$/,`-${s}.log`);if(await hn(n).catch(()=>null))await lo(n,i)}if(this.currentLogFile=r,t.maxFiles){let i=(await fr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,l)=>l.localeCompare(o));for(let o of i.slice(t.maxFiles))await mr(pn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let n=so(e),r=au(t),s=co();await mu(n,s,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),dr(this.currentLogFile))try{let e=oo(this.currentLogFile,"r+");io(e),Rs(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await fr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await mr(pn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Be())return!1;let e=typeof ge.env.NO_COLOR<"u",t=ge.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ge.stderr<"u"&&ge.stderr.isTTY||typeof ge.stdout<"u"&&ge.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:n="",tag:r="",message:s,level:i,showTimestamp:o=!0}=e,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(o)w.push(t);if(i==="warning")w.push("WARN");else if(i==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(s),w.join(" ")}let a=ge.stdout.columns||120,c="";if(i==="warning"||i==="error")c=`${n} ${s}`;else if(i==="info"||i==="success")c=`${n} ${r} ${s}`;else c=`${n} ${r} ${pe.cyan(s)}`;if(!o)return c.trim();let u=l(c).trim().length,m=l(t).length,h=Math.max(1,a-2-u-m);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):i});let n=/%([sdijfo%])/g,r=0,s=e.replace(n,(i,o)=>{if(o==="%")return"%";if(r>=t.length)return i;let l=t[r++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return i}});if(r<t.length)s+=` ${t.slice(r).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,s)=>{let i=pe.underline(pe.blue(r)),o=this.toAbsoluteFilePath(s);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,a="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(n,r)=>pe.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>pe.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>pe.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>pe.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>pe.strikethrough(r)),t}supportsHyperlinks(){if(Be())return!1;let e=ge.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=ge.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(du(t)||t.startsWith("./")||t.startsWith("../"))t=fu(t);else return null;return dr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,n=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(e,t,...n){let r=new Date,s=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,n);let{consoleText:a,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Yo[e],h=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",w;switch(e){case"debug":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:pe.gray(a),level:e}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:pe.green(a),level:e}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.error(w),l){let N=l.split(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ce()||!Fe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cr(this.config.logDirectory),n=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let i=mn(this.config.logDirectory,r);if(e.before)try{if((await fn(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}n.push(i)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await ur(r),console.warn(`Deleted log file: ${r}`)}catch(s){console.error(`Failed to delete log file ${r}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Sr(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let r=[...t];for(let s of e)if(Te(s)&&"name"in s){if(!r.find((o)=>Te(o)&&("name"in o)&&o.name===s.name))r.push(s)}else if(Te(s)&&"path"in s){if(!r.find((o)=>Te(o)&&("path"in o)&&o.path===s.path))r.push(s)}else if(!r.some((i)=>Br(i,s)))r.push(s);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}if(!Te(t)||!Te(e))return t;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let s=t[r];if(s===null||s===void 0)continue;else if(Te(s)&&Te(n[r]))n[r]=Sr(n[r],s);else if(Array.isArray(s)&&Array.isArray(n[r]))if(s.length>0&&n[r].length>0&&Te(s[0])&&Te(n[r][0])){let i=[...s];for(let o of n[r])if(Te(o)&&"name"in o){if(!i.find((a)=>Te(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(Te(o)&&"path"in o){if(!i.find((a)=>Te(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((l)=>Br(l,o)))i.push(o);n[r]=i}else if(s.every((i)=>typeof i==="string")&&n[r].every((i)=>typeof i==="string")){let i=[...s];for(let o of n[r])if(!i.includes(o))i.push(o);n[r]=i}else n[r]=s;else n[r]=s}return n}function si(e,t,n="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return n==="replace"?t:Sr(e,t);if(Array.isArray(e))return n==="replace"?t:Sr(e,t);if(!Te(t)||!Te(e))return t;let r={...e};for(let s of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let i=t[s],o=r[s];if(i===null||i===void 0)continue;if(Array.isArray(i)||Array.isArray(o))if(n==="replace")r[s]=i;else r[s]=Sr(o,i);else if(Te(i)&&Te(o))r[s]=si(o,i,n);else r[s]=i}return r}function Br(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Br(e[n],t[n]))return!1;return!0}if(Te(e)&&Te(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Br(e[s],t[s]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Tr(e,t,n="replace"){if(!Lo(e))return null;try{let r=await import(e),s=r.default||r;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return si(t,s,n)}catch{return null}}catch{return null}}function Wu(e,t,n=!1){if(!e)return t;let r=e.toUpperCase().replace(/-/g,"_"),s={...t};function i(o,l=[]){let a={...o};for(let[c,u]of Object.entries(o)){let m=[...l,c],h=(R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${r}_${m.map(h).join("_")}`,N=`${r}_${m.map((R)=>R.toUpperCase()).join("_")}`;if(n)je.info(`Checking environment variable ${w} for config ${e}.${m.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[c]=i(u,m);else{let R=Kn.env[w]||Kn.env[N];if(R!==void 0){if(n)je.info(`Using environment variable ${R?w:N} for config ${e}.${m.join(".")}`);if(typeof u==="number")a[c]=Number(R);else if(typeof u==="boolean")a[c]=R.toLowerCase()==="true";else if(Array.isArray(u))try{let y=JSON.parse(R);if(Array.isArray(y))a[c]=y;else a[c]=R.split(",").map((b)=>b.trim())}catch{a[c]=R.split(",").map((y)=>y.trim())}else a[c]=R}}}return a}return i(s)}async function Uu({name:e="",alias:t,cwd:n,configDir:r,defaultConfig:s,verbose:i=!1,checkEnv:o=!0,arrayStrategy:l="replace"}){let a=o&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Wu(e,s,i):s,c=n||Kn.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(i)je.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${c}`);let m=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),w=t?[t,`.${t}`]:[],N=t?[`${t}.config`,`.${t}.config`]:[],R=Array.from(new Set([c,Qe(c,"config"),Qe(c,".config"),r?Qe(c,r):void 0].filter(Boolean)));for(let y of R){if(i)je.info(`Searching for configuration in: ${y}`);let g=[Qe(c,"config"),Qe(c,".config")].concat(r?[Qe(c,r)]:[]).includes(y)?[...m,...h,...w,...N]:[...h,...m,...N,...w];for(let p of g)for(let E of u){let D=Qe(y,`${p}${E}`),J=await Tr(D,a,l);if(J!==null){if(i)je.success(`Configuration loaded from: ${D}`);return J}}}if(e){let y=Qe($s(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(i)je.info(`Checking user config directory: ${y}`);for(let g of b)for(let p of u){let E=Qe(y,`${g}${p}`),D=await Tr(E,a,l);if(D!==null){if(i)je.success(`Configuration loaded from user config directory: ${E}`);return D}}}if(e){let y=Qe($s(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(i)je.info(`Checking user config directory for dotfile configs: ${y}`);for(let g of b)for(let p of u){let E=Qe(y,`${g}${p}`),D=await Tr(E,a,l);if(D!==null){if(i)je.success(`Configuration loaded from user config directory dotfile: ${E}`);return D}}}if(e){let y=$s(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(i)je.info(`Checking user home directory for dotfile configs: ${y}`);for(let g of b)for(let p of u){let E=Qe(y,`${g}${p}`),D=await Tr(E,a,l);if(D!==null){if(i)je.success(`Configuration loaded from user home directory: ${E}`);return D}}}try{let y=Qe(c,"package.json");if(Lo(y)){let b=await import(y),g=b[e];if(!g&&t){if(g=b[t],g&&i)je.success(`Using alias "${t}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(i)je.success(`Configuration loaded from package.json: ${g===b[e]?e:t}`);return si(a,g,l)}catch(p){if(i)je.warn("Failed to merge package.json config:",p)}}}catch(y){if(i)je.warn("Failed to load package.json:",y)}if(i)je.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Qu(e,t={}){let n=Cr.cwd();while(n.includes("storage"))n=Yi(n,"..");let r=Yi(n,e||"");if(t?.relative)return Gc(Cr.cwd(),r);return r}async function Vu(){try{let e=await Uu({name:"clarity",alias:"logging",defaultConfig:xr,cwd:Cr.cwd()});return{...xr,...e||{}}}catch{return xr}}function Be(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ju(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let e=kt.type;if(e==="renderer"||e==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class jo{async format(e){let t=await Ju(),n=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:n})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:pn.pid,hostname:t(),environment:pn.env.NODE_ENV||"development",platform:pn.platform,version:pn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pn.env.NODE_ENV||pn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Pr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Vs},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new jo,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ge.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[n]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rr};return{...Rr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Vs.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!Be()&&this.config.writeToFile===!0}async writeToFile(e){let n=(async()=>{let s,i=0,o=3,l=1000;while(i<o)try{try{try{await uu(this.config.logDirectory,lo.F_OK|lo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await du(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Et.from(e);try{if(!dr(this.currentLogFile))await As(this.currentLogFile,"",{mode:420});if(s=ao(this.currentLogFile,"a",420),cu(s,a,{flag:"a"}),oo(s),s!==void 0)vs(s),s=void 0;if((await yn(this.currentLogFile)).size===0){if(await As(this.currentLogFile,a,{flag:"w",mode:420}),(await yn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let u=c;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,m);let h=l*2**i;await new Promise((w)=>setTimeout(w,h)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{vs(s)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let u=a,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),a}i++;let c=l*2**(i-1);await new Promise((u)=>setTimeout(u,c))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return hn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return hn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return hn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,a])=>a.createdAt.getTime()-l.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[l]of s.slice(o))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Cs(16).toString("hex")}generateKey(){return Cs(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),n=Cs(16),r=ou("aes-256-gcm",t,n),s=Et.isBuffer(e)?e:Et.from(e,"utf8"),i=r.update(s),o=r.final(),l=i.length+o.length,a=r.getAuthTag(),c=Et.allocUnsafe(16+l+16);return n.copy(c,0),i.copy(c,16),o.copy(c,16+i.length),a.copy(c,16+l),{encrypted:c,iv:n}}async compressData(e){return new Promise((t,n)=>{let r=uo(),s=[];r.on("data",(i)=>s.push(i)),r.on("end",()=>t(Et.from(Et.concat(s)))),r.on("error",n),r.write(e),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Be())return;if(!this.shouldWriteToFile())return;let e=await yn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await fr(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,c)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${o}`;if(await yn(n).catch(()=>null))try{if(await co(n,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await mr(l)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${n}.1`;await As(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=n.replace(/\.log$/,`-${s}.log`);if(await yn(n).catch(()=>null))await co(n,i)}if(this.currentLogFile=r,t.maxFiles){let i=(await fr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,l)=>l.localeCompare(o));for(let o of i.slice(t.maxFiles))await mr(hn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let n=io(e),r=lu(t),s=uo();await gu(n,s,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),dr(this.currentLogFile))try{let e=ao(this.currentLogFile,"r+");oo(e),vs(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await fr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await mr(hn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Be())return!1;let e=typeof ge.env.NO_COLOR<"u",t=ge.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ge.stderr<"u"&&ge.stderr.isTTY||typeof ge.stdout<"u"&&ge.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:n="",tag:r="",message:s,level:i,showTimestamp:o=!0}=e,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(o)w.push(t);if(i==="warning")w.push("WARN");else if(i==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(s),w.join(" ")}let a=ge.stdout.columns||120,c="";if(i==="warning"||i==="error")c=`${n} ${s}`;else if(i==="info"||i==="success")c=`${n} ${r} ${s}`;else c=`${n} ${r} ${pe.cyan(s)}`;if(!o)return c.trim();let u=l(c).trim().length,m=l(t).length,h=Math.max(1,a-2-u-m);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):i});let n=/%([sdijfo%])/g,r=0,s=e.replace(n,(i,o)=>{if(o==="%")return"%";if(r>=t.length)return i;let l=t[r++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return i}});if(r<t.length)s+=` ${t.slice(r).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,s)=>{let i=pe.underline(pe.blue(r)),o=this.toAbsoluteFilePath(s);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,a="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(n,r)=>pe.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>pe.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>pe.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>pe.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>pe.strikethrough(r)),t}supportsHyperlinks(){if(Be())return!1;let e=ge.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=ge.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(fu(t)||t.startsWith("./")||t.startsWith("../"))t=mu(t);else return null;return dr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,n=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(e,t,...n){let r=new Date,s=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,n);let{consoleText:a,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Xo[e],h=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",w;switch(e){case"debug":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:pe.gray(a),level:e}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:pe.green(a),level:e}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.error(w),l){let N=l.split(`
11
11
  `);for(let R of N)if(R.trim()&&!R.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:pe.gray(` ${R}`),level:e,showTimestamp:!1}))}break}}else if(!Be()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}if(!this.shouldLog(e))return;let u=`${i} ${this.environment}.${e.toUpperCase()}: ${c}
12
12
  `;if(l)u+=`${l}
13
13
  `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let n={update:(l,a)=>{},finish:(l)=>{},interrupt:(l,a)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!Be()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Be()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,a="info")=>{if(!Be()&&ge.stdout.isTTY)ge.stdout.write(`
14
14
  `);if(this[a==="warning"?"warn":a](l),this.activeProgressBar&&this.shouldStyleConsole()&&!Be()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":pe.blue("\u25D0"),tag:n,message:`${pe.cyan(e)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),s=Math.round(r-t),i=`${e} completed in ${s}ms`,o=new Date,l=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(n)c+=` ${JSON.stringify(n)}`;if(c+=`
15
- `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":pe.green("\u2713"),tag:u,message:`${i}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Be())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,n=new Pr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(Be())throw Error("createReadStream is not supported in browser environments");if(!dr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return so(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=$t.isBuffer(e)?e:$t.from(e,"base64"),s=r.subarray(0,16),i=r.subarray(r.length-16),o=r.subarray(16,r.length-16),l=ou("aes-256-gcm",n,s);l.setAuthTag(i);let a=l.update(o),c=l.final(),u=a.length+c.length,m=$t.allocUnsafe(u);return a.copy(m,0),c.copy(m,a.length),m.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Be()}isServerMode(){return!Be()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:s,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
15
+ `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":pe.green("\u2713"),tag:u,message:`${i}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Be())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,n=new Pr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(Be())throw Error("createReadStream is not supported in browser environments");if(!dr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return io(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Et.isBuffer(e)?e:Et.from(e,"base64"),s=r.subarray(0,16),i=r.subarray(r.length-16),o=r.subarray(16,r.length-16),l=au("aes-256-gcm",n,s);l.setAuthTag(i);let a=l.update(o),c=l.final(),u=a.length+c.length,m=Et.allocUnsafe(u);return a.copy(m,0),c.copy(m,a.length),m.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Be()}isServerMode(){return!Be()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:s,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
16
16
  `),a=Math.max(...l.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(a)}\u2510`,u=`\u2514${"\u2500".repeat(a)}\u2518`,m=l.map((h)=>this.formatConsoleMessage({timestamp:n,message:pe.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:pe.cyan(c),showTimestamp:!1})),m.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:n,message:pe.cyan(u),showTimestamp:!1}))}else if(!Be())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let o=`${r} ${this.environment}.INFO: [BOX] ${i}
17
17
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${pe.cyan("?")} ${e} (y/n) `);let n=(r)=>{let s=r.toString().trim().toLowerCase();ge.stdin.removeListener("data",n);try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!1)}catch{}ge.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!0)}catch{}ge.stdin.resume(),ge.stdin.once("data",n)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let n=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,c=0;if(n=e.replace(a,(u,m)=>{if(m==="%")return"%";if(c>=t.length)return u;let h=t[c++];switch(m){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),c<t.length)n+=` ${t.slice(c).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${pe.blue("\u25D0")} `;console.error(`${c}${a} ${pe.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
18
18
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ge.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*n/100),s=e.barLength-r,i=pe.green("\u2501".repeat(r)),o=pe.gray("\u2501".repeat(s)),l=`[${i}${o}]`,a=`${n}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||n===100?pe.green("\u2713"):pe.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${pe.gray(this.formatTag(this.name))}`:"",h=`\r${u}${m} ${l} ${a}${c}`,w=ge.stdout.columns||80,N=" ".repeat(Math.max(0,w-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${N}`,ge.stdout.write(e.lastRenderedLine),t)ge.stdout.write(`
19
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Be()||!ge.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await fr(this.config.logDirectory),n=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let i=pn(this.config.logDirectory,r);if(e.before)try{if((await hn(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}n.push(i)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await mr(r),console.warn(`Deleted log file: ${r}`)}catch(s){console.error(`Failed to delete log file ${r}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function jo(e,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:s=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),l===n||!s(o))break;if(r>0)await new Promise((c)=>setTimeout(c,r))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Wo(e){return e instanceof Ze}function Ju(e){return e instanceof _r}function Hu(e){if(Wo(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>e.message.toLowerCase().includes(n.toLowerCase()))}class jr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,n={}){let{prefix:r,useCamelCase:s=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:l=!1,trackPerformance:a=!0}=n,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],u,{useCamelCase:s,useBackwardCompatibility:i,customParsers:o,verbose:l,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return qn.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=o.map((u)=>this.formatEnvKey(u,r.useCamelCase)),a=`${n}_${l.join("_")}`,c=r.useBackwardCompatibility?`${n}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,n,r);else{let u=gr.env[a]||(c?gr.env[c]:void 0);if(u!==void 0){if(r.verbose){let m=gr.env[a]?a:c}try{e[s]=this.parseEnvironmentValue(u,typeof i,a,r.customParsers,r.configName)}catch(m){if(m instanceof Ir)throw m;throw It.envVar(a,u,typeof i,r.configName)}}}}}parseEnvironmentValue(e,t,n,r,s){for(let[i,o]of Object.entries(r))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw It.envVar(n,e,`${t} (via ${i.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},n=e.toUpperCase();for(let[r,s]of Object.entries(gr.env))if(r.startsWith(n)&&s!==void 0)t[r]=s;return t}validateEnvironmentVariable(e,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(e,t,n,{})}catch(s){r.push(`Cannot parse value "${t}" as ${n}: ${s}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,n={}){let{prefix:r,format:s="text"}=n,i=r||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),s){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=`${n}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,n,r);else r.push({key:l,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let n=`Environment Variables for ${t}:
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Be()||!ge.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await fr(this.config.logDirectory),n=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let i=hn(this.config.logDirectory,r);if(e.before)try{if((await yn(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}n.push(i)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await mr(r),console.warn(`Deleted log file: ${r}`)}catch(s){console.error(`Failed to delete log file ${r}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Wo(e,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:s=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),l===n||!s(o))break;if(r>0)await new Promise((c)=>setTimeout(c,r))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Uo(e){return e instanceof Ze}function Hu(e){return e instanceof _r}function zu(e){if(Uo(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>e.message.toLowerCase().includes(n.toLowerCase()))}class jr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,n={}){let{prefix:r,useCamelCase:s=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:l=!1,trackPerformance:a=!0}=n,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],u,{useCamelCase:s,useBackwardCompatibility:i,customParsers:o,verbose:l,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return jn.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=o.map((u)=>this.formatEnvKey(u,r.useCamelCase)),a=`${n}_${l.join("_")}`,c=r.useBackwardCompatibility?`${n}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,n,r);else{let u=gr.env[a]||(c?gr.env[c]:void 0);if(u!==void 0){if(r.verbose){let m=gr.env[a]?a:c}try{e[s]=this.parseEnvironmentValue(u,typeof i,a,r.customParsers,r.configName)}catch(m){if(m instanceof Ir)throw m;throw Lt.envVar(a,u,typeof i,r.configName)}}}}}parseEnvironmentValue(e,t,n,r,s){for(let[i,o]of Object.entries(r))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw Lt.envVar(n,e,`${t} (via ${i.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},n=e.toUpperCase();for(let[r,s]of Object.entries(gr.env))if(r.startsWith(n)&&s!==void 0)t[r]=s;return t}validateEnvironmentVariable(e,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(e,t,n,{})}catch(s){r.push(`Cannot parse value "${t}" as ${n}: ${s}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,n={}){let{prefix:r,format:s="text"}=n,i=r||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),s){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=`${n}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,n,r);else r.push({key:l,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let n=`Environment Variables for ${t}:
20
20
 
21
21
  `;for(let r of e)n+=`${r.key}
22
22
  `,n+=` Type: ${r.type}
@@ -28,25 +28,25 @@ import{Tb as Ll,Wb as Kl}from"./chunk-mvk2rcqm.js";import{Yb as Zt}from"./chunk-
28
28
  `;n+=`| Variable | Type | Description | Example |
29
29
  `,n+=`|----------|------|-------------|----------|
30
30
  `;for(let r of e)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
31
- `;return n}}function zu(e,t){let n=Ho("process");if(typeof n>"u"||!n.env)return t;let r=n.env[e];return r!==void 0?r:t}function Uo(e,t,n={}){return Qo(e,t,n,new WeakMap)}function Qo(e,t,n,r){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=n;if(t===null||t===void 0)return i?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Vo(e,t,s,r);if(!rt(t)||!rt(e))return t;return Zu(e,t,n,r)}function Vo(e,t,n,r){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(n){case"replace":return t;case"concat":return Gu(e,t);case"smart":return Yu(e,t,r);default:return t}return t}function Gu(e,t){let n=[...t];for(let r of e)if(!n.some((s)=>qs(s,r)))n.push(r);return n}function Yu(e,t,n){if(t.length===0)return e;if(e.length===0)return t;if(rt(t[0])&&rt(e[0]))return Xu(e,t,n);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}function Xu(e,t,n){let r=[...t];for(let s of e){if(!rt(s)){r.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let l of i)if(l in s){if(r.find((c)=>rt(c)&&(l in c)&&c[l]===s[l])){o=!0;break}}if(!o)r.push(s)}return r}function Zu(e,t,n,r){let s=t;if(rt(s)&&r.has(s))return r.get(s);let i={...e};if(rt(s))r.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let l=s[o],a=i[o];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){i[o]=l;continue}if(rt(l)&&rt(a))i[o]=Qo(a,l,n,r);else if(Array.isArray(l)||Array.isArray(a))i[o]=Vo(a,l,n.arrayMergeMode||"smart",r);else i[o]=l}return i}function ni(e,t,n="replace"){return Uo(e,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function qs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!qs(e[n],t[n]))return!1;return!0}if(rt(e)&&rt(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!qs(e[s],t[s]))return!1}return!0}return!1}function rt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Wr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,n={}){let{arrayStrategy:r="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:l=!1}=n;if(s){let c=Sn.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let a=async()=>{if(!yr(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),m=u.default||u,h="default"in u,w=Object.keys(u).length>0;if(!h&&!w)throw new Kn(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new Kn(e,Error("Configuration must export a valid object"),"unknown");let y={config:ni(t,m,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)Sn.setWithFileCheck("file",y,e,i);return y}catch(c){throw c instanceof Error?It.configLoad(e,c):It.configLoad(e,Error(String(c)))}};if(o)return qn.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,n={}){for(let r of e)try{let s=await this.loadFromPath(r,t,n);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(n.verbose)console.warn(`Failed to load config from ${r}:`,s)}return null}generateConfigPaths(e,t,n){let r=this.generateNamePatterns(e,n),s=[];for(let i of r)for(let o of this.extensions)s.push(Cs(t,`${i}${o}`));return s}generateNamePatterns(e,t){let n=[];if(n.push("config",".config"),e)n.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)n.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(e){return jo(async()=>yr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,n){let r=[];if(!yr(e))return r;if(t||n){let s=this.generateNamePatterns(t||"",n);for(let i of s)for(let o of this.extensions){let l=Cs(e,`${i}${o}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let l=Cs(e,o);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(e){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((n)=>n.test(e))}async validateConfigFile(e){let t=[];try{if(!yr(e))return t.push("Configuration file does not exist"),t;let n=await import(e),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let n=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let s=await this.loadFromPath(r,{},t);if(s)n.set(r,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${r}:`,s)}})),n}}class ri{async validateConfiguration(e,t,n={}){let{stopOnFirstError:r=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:l=!0,verbose:a=!1}=n,c=async()=>{let u=[],m=[],h={stopOnFirstError:r,validateRequired:s,validateTypes:i,customRules:o,trackPerformance:l,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(w){return u.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:u,warnings:m}}};if(l)return await qn.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,n){try{if(!gu(t))throw new Fn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),s=r.default||r;if(Array.isArray(s))return this.validateWithRules(e,s,n);else return this.validateWithJSONSchema(e,s,n)}catch(r){throw new Fn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,n){let r=[],s=[];return this.validateObjectAgainstSchema(e,t,"",r,s,n),{isValid:r.length===0,errors:r,warnings:s}}validateObjectAgainstSchema(e,t,n,r,s,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=n?`${n}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,r,s,i),i.stopOnFirstError&&r.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[l,a]of Object.entries(t.properties))if(l in o){let c=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],a,c,r,s,i),i.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!l.has(a))s.push({path:n?`${n}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,n){let r=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),l=this.validateWithRule(o,i,i.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(o){r.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:s}}validateWithRule(e,t,n){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let s=t.validator(e);if(s)r.push({path:n,message:t.message||s,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let n=t.split("."),r=e;for(let s of n)if(r&&typeof r==="object"&&s in r)r=r[s];else return;return r}generateRulesFromInterface(e){let t=[],n=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,s,i,o]=r;t.push({path:s,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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}]}}}class si{fileLoader=new Wr;envProcessor=new jr;validator=new ri;async loadConfig(e){let t=Date.now(),{cache:n,performance:r,schema:s,validate:i,...o}=e;try{if(n?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let l;try{l=await this.loadConfigurationStrategies(o,!0,n)}catch(a){let c=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(c)throw a;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),m=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw a;if(m&&(!c||!h))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(s||i)await this.validateConfiguration(l.config,s,i,o.name);if(n?.enabled&&l)this.cacheResult(o.name||"",l,n,o);if(r?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(a);if(r.slowThreshold&&a.duration>r.slowThreshold)ct.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);l.metrics=a}return l}catch(l){let a=Date.now()-t;throw ct.error(`Configuration loading failed after ${a}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,n){let{name:r="",alias:s,cwd:i,configDir:o,defaultConfig:l,checkEnv:a=!0,arrayStrategy:c="replace",verbose:u=!1}=e,m=i||Yt.cwd(),h=[],w=await this.loadLocalConfiguration(r,s,m,o,l,c,u,a,n);if(w)return h.push(...this.getLocalSearchPaths(r,s,m,o)),this.finalizeResult(w,h,a,r,u);let N=await this.loadHomeConfiguration(r,s,l,c,u,a);if(N)return h.push(...this.getHomeSearchPaths(r,s)),this.finalizeResult(N,h,a,r,u);let R=await this.loadPackageJsonConfiguration(r,s,m,l,c,u,a);if(R)return h.push(Ve(m,"package.json")),this.finalizeResult(R,h,a,r,u);if(h.push(...this.getAllSearchPaths(r,s,m,o)),t)throw It.configNotFound(r,h,s);return{...await this.applyEnvironmentVariables(r,l,a,u),warnings:[`No configuration file found for "${r}"${s?` or alias "${s}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,n,r,s,i,o,l,a){let c=l?In(e,s,o):s,u=this.getLocalDirectories(n,r);for(let m of u){if(o)ct.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(e,m,t),w=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(w){if(o)ct.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(e,t,n,r,s,i){if(!e)return null;let o=i?In(e,n,s):n,l=[Ve(fn(),".config",e),Ve(fn(),".config"),fn()];for(let a of l){if(s)ct.info(`Checking home directory: ${a}`);let c=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(c,o,{arrayStrategy:r,verbose:s});if(u){if(s)ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,n,r,s,i,o){let l=o?In(e,r,i):r;try{let a=Ve(n,"package.json");if(!Ks(a))return null;let c=await import(a),u=c[e],m=e;if(!u&&t)u=c[t],m=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)ct.success(`Configuration loaded from package.json: ${m}`);return{config:ni(l,u,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)ct.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,n,r){if(!n||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:In(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,n,r,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,n,r){let s=[];if(n){let i=n(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw It.configValidation(r||"unknown",s,r)}checkCache(e,t){let n=this.generateCacheKey(e,t);return Sn.get(n)||null}cacheResult(e,t,n,r){let s=this.generateCacheKey(e,r);Sn.set(s,t,void 0,n.ttl)}generateCacheKey(e,t){let n=[e];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ve(e,"config"),Ve(e,".config"),t?Ve(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,n,r){let s=[];return s.push(...this.getLocalSearchPaths(e,t,n,r)),s.push(...this.getHomeSearchPaths(e,t)),s.push(Ve(n,"package.json")),s}getLocalSearchPaths(e,t,n,r){let s=this.getLocalDirectories(n,r),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let n=[Ve(fn(),".config",e),Ve(fn(),".config"),fn()],r=[];for(let s of n)r.push(...this.fileLoader.generateConfigPaths(e,s,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function To(e){let n=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return n||r}async function ed(e){return Ct.loadConfig({...e,__strictErrorHandling:!0})}async function Jo(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},n="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(n)r=await Ct.loadConfig(e);else r=await Ct.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let s=r instanceof Error?r.name:"UnknownError",i=r instanceof Error?r.message:String(r);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)ct.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ct.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function td(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Ct.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&To(n)))return(await Ct.applyEnvironmentVariables(e,{},!0,!1)).config;throw n}}try{return(await Ct.loadConfig({...e,cwd:e.cwd||Yt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&To(t)))return(await Ct.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function nd(e,t,n="replace"){let r=new Wr;try{let s=await r.loadFromPath(e,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return s?s.config:null}catch{return null}}function In(e,t,n=!1){let r=new jr,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,l=[]){let a={...o};for(let[c,u]of Object.entries(o)){let m=[...l,c],h=[`${s}_${m.join("_").toUpperCase()}`,`${s}_${m.map((R)=>R.toUpperCase()).join("")}`,`${s}_${m.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,N;for(let R of h)if(w=Yt.env[R],w!==void 0){N=R;break}if(w!==void 0&&N)if(typeof u==="boolean")a[c]=["true","1","yes"].includes(w.toLowerCase());else if(typeof u==="number"){let R=Number(w);if(!Number.isNaN(R))a[c]=R}else if(Array.isArray(u))try{a[c]=JSON.parse(w)}catch{a[c]=w.split(",").map((R)=>R.trim())}else a[c]=w;else if(u&&typeof u==="object"&&!Array.isArray(u))a[c]=i(u,m)}return a}return i(t)}function rd(e){let t=Ve(Yt.cwd(),e.configDir),n=Ve(Yt.cwd(),e.generatedDir),r=Ve(n,"config-types.ts");if(!Ks(zi(r)))Qc(zi(r),{recursive:!0,mode:511});let s=Ks(t)?Vc(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],i=`// Generated by bunfig v${Md}
31
+ `;return n}}function Gu(e,t){let n=zo("process");if(typeof n>"u"||!n.env)return t;let r=n.env[e];return r!==void 0?r:t}function Qo(e,t,n={}){return Vo(e,t,n,new WeakMap)}function Vo(e,t,n,r){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=n;if(t===null||t===void 0)return i?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Jo(e,t,s,r);if(!rt(t)||!rt(e))return t;return ed(e,t,n,r)}function Jo(e,t,n,r){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(n){case"replace":return t;case"concat":return Yu(e,t);case"smart":return Xu(e,t,r);default:return t}return t}function Yu(e,t){let n=[...t];for(let r of e)if(!n.some((s)=>Us(s,r)))n.push(r);return n}function Xu(e,t,n){if(t.length===0)return e;if(e.length===0)return t;if(rt(t[0])&&rt(e[0]))return Zu(e,t,n);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}function Zu(e,t,n){let r=[...t];for(let s of e){if(!rt(s)){r.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let l of i)if(l in s){if(r.find((c)=>rt(c)&&(l in c)&&c[l]===s[l])){o=!0;break}}if(!o)r.push(s)}return r}function ed(e,t,n,r){let s=t;if(rt(s)&&r.has(s))return r.get(s);let i={...e};if(rt(s))r.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let l=s[o],a=i[o];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){i[o]=l;continue}if(rt(l)&&rt(a))i[o]=Vo(a,l,n,r);else if(Array.isArray(l)||Array.isArray(a))i[o]=Jo(a,l,n.arrayMergeMode||"smart",r);else i[o]=l}return i}function ii(e,t,n="replace"){return Qo(e,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Us(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Us(e[n],t[n]))return!1;return!0}if(rt(e)&&rt(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Us(e[s],t[s]))return!1}return!0}return!1}function rt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Wr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,n={}){let{arrayStrategy:r="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:l=!1}=n;if(s){let c=Dn.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let a=async()=>{if(!yr(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),m=u.default||u,h="default"in u,w=Object.keys(u).length>0;if(!h&&!w)throw new Fn(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new Fn(e,Error("Configuration must export a valid object"),"unknown");let y={config:ii(t,m,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)Dn.setWithFileCheck("file",y,e,i);return y}catch(c){throw c instanceof Error?Lt.configLoad(e,c):Lt.configLoad(e,Error(String(c)))}};if(o)return jn.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,n={}){for(let r of e)try{let s=await this.loadFromPath(r,t,n);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(n.verbose)console.warn(`Failed to load config from ${r}:`,s)}return null}generateConfigPaths(e,t,n){let r=this.generateNamePatterns(e,n),s=[];for(let i of r)for(let o of this.extensions)s.push(Ns(t,`${i}${o}`));return s}generateNamePatterns(e,t){let n=[];if(n.push("config",".config"),e)n.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)n.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(e){return Wo(async()=>yr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,n){let r=[];if(!yr(e))return r;if(t||n){let s=this.generateNamePatterns(t||"",n);for(let i of s)for(let o of this.extensions){let l=Ns(e,`${i}${o}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let l=Ns(e,o);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(e){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((n)=>n.test(e))}async validateConfigFile(e){let t=[];try{if(!yr(e))return t.push("Configuration file does not exist"),t;let n=await import(e),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let n=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let s=await this.loadFromPath(r,{},t);if(s)n.set(r,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${r}:`,s)}})),n}}class oi{async validateConfiguration(e,t,n={}){let{stopOnFirstError:r=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:l=!0,verbose:a=!1}=n,c=async()=>{let u=[],m=[],h={stopOnFirstError:r,validateRequired:s,validateTypes:i,customRules:o,trackPerformance:l,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(w){return u.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:u,warnings:m}}};if(l)return await jn.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,n){try{if(!yu(t))throw new qn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),s=r.default||r;if(Array.isArray(s))return this.validateWithRules(e,s,n);else return this.validateWithJSONSchema(e,s,n)}catch(r){throw new qn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,n){let r=[],s=[];return this.validateObjectAgainstSchema(e,t,"",r,s,n),{isValid:r.length===0,errors:r,warnings:s}}validateObjectAgainstSchema(e,t,n,r,s,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=n?`${n}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,r,s,i),i.stopOnFirstError&&r.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[l,a]of Object.entries(t.properties))if(l in o){let c=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],a,c,r,s,i),i.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!l.has(a))s.push({path:n?`${n}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,n){let r=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),l=this.validateWithRule(o,i,i.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(o){r.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:s}}validateWithRule(e,t,n){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let s=t.validator(e);if(s)r.push({path:n,message:t.message||s,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let n=t.split("."),r=e;for(let s of n)if(r&&typeof r==="object"&&s in r)r=r[s];else return;return r}generateRulesFromInterface(e){let t=[],n=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,s,i,o]=r;t.push({path:s,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:ea},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ai{fileLoader=new Wr;envProcessor=new jr;validator=new oi;async loadConfig(e){let t=Date.now(),{cache:n,performance:r,schema:s,validate:i,...o}=e;try{if(n?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let l;try{l=await this.loadConfigurationStrategies(o,!0,n)}catch(a){let c=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(c)throw a;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),m=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw a;if(m&&(!c||!h))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(s||i)await this.validateConfiguration(l.config,s,i,o.name);if(n?.enabled&&l)this.cacheResult(o.name||"",l,n,o);if(r?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(a);if(r.slowThreshold&&a.duration>r.slowThreshold)ct.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);l.metrics=a}return l}catch(l){let a=Date.now()-t;throw ct.error(`Configuration loading failed after ${a}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,n){let{name:r="",alias:s,cwd:i,configDir:o,defaultConfig:l,checkEnv:a=!0,arrayStrategy:c="replace",verbose:u=!1}=e,m=i||Xt.cwd(),h=[],w=await this.loadLocalConfiguration(r,s,m,o,l,c,u,a,n);if(w)return h.push(...this.getLocalSearchPaths(r,s,m,o)),this.finalizeResult(w,h,a,r,u);let N=await this.loadHomeConfiguration(r,s,l,c,u,a);if(N)return h.push(...this.getHomeSearchPaths(r,s)),this.finalizeResult(N,h,a,r,u);let R=await this.loadPackageJsonConfiguration(r,s,m,l,c,u,a);if(R)return h.push(Ve(m,"package.json")),this.finalizeResult(R,h,a,r,u);if(h.push(...this.getAllSearchPaths(r,s,m,o)),t)throw Lt.configNotFound(r,h,s);return{...await this.applyEnvironmentVariables(r,l,a,u),warnings:[`No configuration file found for "${r}"${s?` or alias "${s}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,n,r,s,i,o,l,a){let c=l?Ln(e,s,o):s,u=this.getLocalDirectories(n,r);for(let m of u){if(o)ct.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(e,m,t),w=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(w){if(o)ct.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(e,t,n,r,s,i){if(!e)return null;let o=i?Ln(e,n,s):n,l=[Ve(dn(),".config",e),Ve(dn(),".config"),dn()];for(let a of l){if(s)ct.info(`Checking home directory: ${a}`);let c=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(c,o,{arrayStrategy:r,verbose:s});if(u){if(s)ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,n,r,s,i,o){let l=o?Ln(e,r,i):r;try{let a=Ve(n,"package.json");if(!js(a))return null;let c=await import(a),u=c[e],m=e;if(!u&&t)u=c[t],m=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)ct.success(`Configuration loaded from package.json: ${m}`);return{config:ii(l,u,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)ct.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,n,r){if(!n||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ln(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,n,r,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,n,r){let s=[];if(n){let i=n(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw Lt.configValidation(r||"unknown",s,r)}checkCache(e,t){let n=this.generateCacheKey(e,t);return Dn.get(n)||null}cacheResult(e,t,n,r){let s=this.generateCacheKey(e,r);Dn.set(s,t,void 0,n.ttl)}generateCacheKey(e,t){let n=[e];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ve(e,"config"),Ve(e,".config"),t?Ve(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,n,r){let s=[];return s.push(...this.getLocalSearchPaths(e,t,n,r)),s.push(...this.getHomeSearchPaths(e,t)),s.push(Ve(n,"package.json")),s}getLocalSearchPaths(e,t,n,r){let s=this.getLocalDirectories(n,r),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let n=[Ve(dn(),".config",e),Ve(dn(),".config"),dn()],r=[];for(let s of n)r.push(...this.fileLoader.generateConfigPaths(e,s,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function wo(e){let n=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return n||r}async function td(e){return vt.loadConfig({...e,__strictErrorHandling:!0})}async function Ho(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},n="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(n)r=await vt.loadConfig(e);else r=await vt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let s=r instanceof Error?r.name:"UnknownError",i=r instanceof Error?r.message:String(r);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)ct.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await vt.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function nd(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await vt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&wo(n)))return(await vt.applyEnvironmentVariables(e,{},!0,!1)).config;throw n}}try{return(await vt.loadConfig({...e,cwd:e.cwd||Xt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&wo(t)))return(await vt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function rd(e,t,n="replace"){let r=new Wr;try{let s=await r.loadFromPath(e,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return s?s.config:null}catch{return null}}function Ln(e,t,n=!1){let r=new jr,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,l=[]){let a={...o};for(let[c,u]of Object.entries(o)){let m=[...l,c],h=[`${s}_${m.join("_").toUpperCase()}`,`${s}_${m.map((R)=>R.toUpperCase()).join("")}`,`${s}_${m.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,N;for(let R of h)if(w=Xt.env[R],w!==void 0){N=R;break}if(w!==void 0&&N)if(typeof u==="boolean")a[c]=["true","1","yes"].includes(w.toLowerCase());else if(typeof u==="number"){let R=Number(w);if(!Number.isNaN(R))a[c]=R}else if(Array.isArray(u))try{a[c]=JSON.parse(w)}catch{a[c]=w.split(",").map((R)=>R.trim())}else a[c]=w;else if(u&&typeof u==="object"&&!Array.isArray(u))a[c]=i(u,m)}return a}return i(t)}function sd(e){let t=Ve(Xt.cwd(),e.configDir),n=Ve(Xt.cwd(),e.generatedDir),r=Ve(n,"config-types.ts");if(!js(Gi(r)))Vc(Gi(r),{recursive:!0,mode:511});let s=js(t)?Jc(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],i=`// Generated by bunfig v${Od}
32
32
  export type ConfigNames = ${s.length?`'${s.join("' | '")}'`:"string"}
33
- `;Jc(r,i,{mode:438})}function sd(e){let t=null,n=null,r=()=>{if(!n)n=Jo(e).then((i)=>(t=i,i),(i)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)ct.warn("Config loading failed, using defaults:",[i instanceof Error?i:Error(String(i))]);return o});return n},s="defaultConfig"in e?e.defaultConfig:{};return t=s,r(),new Proxy({},{get(i,o){if(t)return t[o];let l=s[o];return r(),l},has(i,o){return o in(t||s)},ownKeys(){return Object.keys(t||s)},getOwnPropertyDescriptor(i,o){return Object.getOwnPropertyDescriptor(t||s,o)},set(i,o,l){if(!t)t={...s};return t[o]=l,!0}})}function id(e){let t=uo(pu.cwd(),e?.configDir||"./config");function n(){if(!yu(t))return[];let s=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),i=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=hu(t).filter((a)=>s.has(vs(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),l=new Map;for(let{base:a,file:c}of o){let u=vs(c).toLowerCase(),m=l.get(a);if(!m){l.set(a,c);continue}let h=vs(m).toLowerCase();if(i.indexOf(u)<i.indexOf(h))l.set(a,c)}return Array.from(l.entries()).map(([a,c])=>({base:a,file:c})).sort((a,c)=>a.base.localeCompare(c.base))}function r(){let s=n(),i=s.map((c)=>c.base),o=i.length?i.map((c)=>`'${c}'`).join(" | "):"string",l=s.length?`{
34
- ${s.map((c)=>{let u=uo(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${u}').default`}).join(`,
33
+ `;Hc(r,i,{mode:438})}function id(e){let t=null,n=null,r=()=>{if(!n)n=Ho(e).then((i)=>(t=i,i),(i)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)ct.warn("Config loading failed, using defaults:",[i instanceof Error?i:Error(String(i))]);return o});return n},s="defaultConfig"in e?e.defaultConfig:{};return t=s,r(),new Proxy({},{get(i,o){if(t)return t[o];let l=s[o];return r(),l},has(i,o){return o in(t||s)},ownKeys(){return Object.keys(t||s)},getOwnPropertyDescriptor(i,o){return Object.getOwnPropertyDescriptor(t||s,o)},set(i,o,l){if(!t)t={...s};return t[o]=l,!0}})}function od(e){let t=fo(bu.cwd(),e?.configDir||"./config");function n(){if(!hu(t))return[];let s=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),i=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=pu(t).filter((a)=>s.has(Ms(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),l=new Map;for(let{base:a,file:c}of o){let u=Ms(c).toLowerCase(),m=l.get(a);if(!m){l.set(a,c);continue}let h=Ms(m).toLowerCase();if(i.indexOf(u)<i.indexOf(h))l.set(a,c)}return Array.from(l.entries()).map(([a,c])=>({base:a,file:c})).sort((a,c)=>a.base.localeCompare(c.base))}function r(){let s=n(),i=s.map((c)=>c.base),o=i.length?i.map((c)=>`'${c}'`).join(" | "):"string",l=s.length?`{
34
+ ${s.map((c)=>{let u=fo(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${u}').default`}).join(`,
35
35
  `)}
36
36
  }`:"Record<string, any>";return`export type ConfigNames = ${o}
37
37
  export type ConfigByName = ${l}
38
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
39
  export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(i)=>({path:i.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:r(),loader:"ts"}))}}}function Bd(e,t={}){let n=Nr.cwd();while(n.includes("storage"))n=fo(n,"..");let r=fo(n,e||"");if(t?.relative)return Tu(Nr.cwd(),r);return r}function _e(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _d(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let e=kt.type;if(e==="renderer"||e==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class ra{async format(e){let t=await _d(),n=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:n})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Dn.pid,hostname:t(),environment:Dn.env.NODE_ENV||"development",platform:Dn.platform,version:Dn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dn.env.NODE_ENV||Dn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ur{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Lr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ra,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ye.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[n]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Is,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Is};return{...Is,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Lr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!_e()&&this.config.writeToFile===!0}async writeToFile(e){let n=(async()=>{let s,i=0,o=3,l=1000;while(i<o)try{try{try{await Eu(this.config.logDirectory,ho.F_OK|ho.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await xu(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Et.from(e);try{if(!hr(this.currentLogFile))await Ms(this.currentLogFile,"",{mode:420});if(s=yo(this.currentLogFile,"a",420),$u(s,a,{flag:"a"}),go(s),s!==void 0)Ns(s),s=void 0;if((await Tn(this.currentLogFile)).size===0){if(await Ms(this.currentLogFile,a,{flag:"w",mode:420}),(await Tn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let u=c;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,m);let h=l*2**i;await new Promise((w)=>setTimeout(w,h)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{Ns(s)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let u=a,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),a}i++;let c=l*2**(i-1);await new Promise((u)=>setTimeout(u,c))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return wn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return wn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return wn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(_e())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,a])=>a.createdAt.getTime()-l.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[l]of s.slice(o))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return As(16).toString("hex")}generateKey(){return As(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),n=As(16),r=wu("aes-256-gcm",t,n),s=Et.isBuffer(e)?e:Et.from(e,"utf8"),i=r.update(s),o=r.final(),l=i.length+o.length,a=r.getAuthTag(),c=Et.allocUnsafe(16+l+16);return n.copy(c,0),i.copy(c,16),o.copy(c,16+i.length),a.copy(c,16+l),{encrypted:c,iv:n}}async compressData(e){return new Promise((t,n)=>{let r=bo(),s=[];r.on("data",(i)=>s.push(i)),r.on("end",()=>t(Et.from(Et.concat(s)))),r.on("error",n),r.write(e),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(_e())return;if(!this.shouldWriteToFile())return;let e=await Tn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await pr(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,c)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${o}`;if(await Tn(n).catch(()=>null))try{if(await po(n,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await br(l)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${n}.1`;await Ms(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=n.replace(/\.log$/,`-${s}.log`);if(await Tn(n).catch(()=>null))await po(n,i)}if(this.currentLogFile=r,t.maxFiles){let i=(await pr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,l)=>l.localeCompare(o));for(let o of i.slice(t.maxFiles))await br(wn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let n=mo(e),r=Su(t),s=bo();await Cu(n,s,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),hr(this.currentLogFile))try{let e=yo(this.currentLogFile,"r+");go(e),Ns(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!_e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await pr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await br(wn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?be.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||_e())return!1;let e=typeof ye.env.NO_COLOR<"u",t=ye.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ye.stderr<"u"&&ye.stderr.isTTY||typeof ye.stdout<"u"&&ye.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:n="",tag:r="",message:s,level:i,showTimestamp:o=!0}=e,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(o)w.push(t);if(i==="warning")w.push("WARN");else if(i==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(s),w.join(" ")}let a=ye.stdout.columns||120,c="";if(i==="warning"||i==="error")c=`${n} ${s}`;else if(i==="info"||i==="success")c=`${n} ${r} ${s}`;else c=`${n} ${r} ${be.cyan(s)}`;if(!o)return c.trim();let u=l(c).trim().length,m=l(t).length,h=Math.max(1,a-2-u-m);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):i});let n=/%([sdijfo%])/g,r=0,s=e.replace(n,(i,o)=>{if(o==="%")return"%";if(r>=t.length)return i;let l=t[r++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return i}});if(r<t.length)s+=` ${t.slice(r).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,s)=>{let i=be.underline(be.blue(r)),o=this.toAbsoluteFilePath(s);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,a="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(n,r)=>be.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>be.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>be.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>be.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>be.strikethrough(r)),t}supportsHyperlinks(){if(_e())return!1;let e=ye.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=ye.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(Ru(t)||t.startsWith("./")||t.startsWith("../"))t=ku(t);else return null;return hr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,n=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(e,t,...n){if(!this.shouldLog(e))return;let r=new Date,s=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,n);let{consoleText:a,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":qd[e],h=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",w;switch(e){case"debug":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:be.gray(a),level:e}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:be.green(a),level:e}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.error(w),l){let N=l.split(`
40
+ `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(i)=>({path:i.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:r(),loader:"ts"}))}}}function Pd(e,t={}){let n=Nr.cwd();while(n.includes("storage"))n=mo(n,"..");let r=mo(n,e||"");if(t?.relative)return wu(Nr.cwd(),r);return r}function _e(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Id(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ct<"u"){let e=Ct.type;if(e==="renderer"||e==="worker")return!1;return!!(Ct.versions&&(Ct.versions.node||Ct.versions.bun))}return!1}class sa{async format(e){let t=await Id(),n=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:n})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:wn.pid,hostname:t(),environment:wn.env.NODE_ENV||"development",platform:wn.platform,version:wn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wn.env.NODE_ENV||wn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ur{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Lr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new sa,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ye.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[n]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Fs,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Fs};return{...Fs,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Lr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!_e()&&this.config.writeToFile===!0}async writeToFile(e){let n=(async()=>{let s,i=0,o=3,l=1000;while(i<o)try{try{try{await xu(this.config.logDirectory,po.F_OK|po.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Ru(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:xt.from(e);try{if(!hr(this.currentLogFile))await Ps(this.currentLogFile,"",{mode:420});if(s=ho(this.currentLogFile,"a",420),Eu(s,a,{flag:"a"}),yo(s),s!==void 0)Bs(s),s=void 0;if((await bn(this.currentLogFile)).size===0){if(await Ps(this.currentLogFile,a,{flag:"w",mode:420}),(await bn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let u=c;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let m=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,m);let h=l*2**i;await new Promise((w)=>setTimeout(w,h)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{Bs(s)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let u=a,m=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),a}i++;let c=l*2**(i-1);await new Promise((u)=>setTimeout(u,c))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Tn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Tn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Tn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(_e())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,a])=>a.createdAt.getTime()-l.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[l]of s.slice(o))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Os(16).toString("hex")}generateKey(){return Os(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),n=Os(16),r=Du("aes-256-gcm",t,n),s=xt.isBuffer(e)?e:xt.from(e,"utf8"),i=r.update(s),o=r.final(),l=i.length+o.length,a=r.getAuthTag(),c=xt.allocUnsafe(16+l+16);return n.copy(c,0),i.copy(c,16),o.copy(c,16+i.length),a.copy(c,16+l),{encrypted:c,iv:n}}async compressData(e){return new Promise((t,n)=>{let r=To(),s=[];r.on("data",(i)=>s.push(i)),r.on("end",()=>t(xt.from(xt.concat(s)))),r.on("error",n),r.write(e),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(_e())return;if(!this.shouldWriteToFile())return;let e=await bn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await pr(this.config.logDirectory),i=s.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,c)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${o}`;if(await bn(n).catch(()=>null))try{if(await bo(n,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await br(l)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${n}.1`;await Ps(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),i=n.replace(/\.log$/,`-${s}.log`);if(await bn(n).catch(()=>null))await bo(n,i)}if(this.currentLogFile=r,t.maxFiles){let i=(await pr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,l)=>l.localeCompare(o));for(let o of i.slice(t.maxFiles))await br(Tn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let n=go(e),r=$u(t),s=To();await vu(n,s,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),hr(this.currentLogFile))try{let e=ho(this.currentLogFile,"r+");yo(e),Bs(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!_e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await pr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await br(Tn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?be.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||_e())return!1;let e=typeof ye.env.NO_COLOR<"u",t=ye.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ye.stderr<"u"&&ye.stderr.isTTY||typeof ye.stdout<"u"&&ye.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:n="",tag:r="",message:s,level:i,showTimestamp:o=!0}=e,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(o)w.push(t);if(i==="warning")w.push("WARN");else if(i==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(s),w.join(" ")}let a=ye.stdout.columns||120,c="";if(i==="warning"||i==="error")c=`${n} ${s}`;else if(i==="info"||i==="success")c=`${n} ${r} ${s}`;else c=`${n} ${r} ${be.cyan(s)}`;if(!o)return c.trim();let u=l(c).trim().length,m=l(t).length,h=Math.max(1,a-2-u-m);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):i});let n=/%([sdijfo%])/g,r=0,s=e.replace(n,(i,o)=>{if(o==="%")return"%";if(r>=t.length)return i;let l=t[r++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return i}});if(r<t.length)s+=` ${t.slice(r).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,s)=>{let i=be.underline(be.blue(r)),o=this.toAbsoluteFilePath(s);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,a="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(n,r)=>be.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>be.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>be.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>be.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>be.strikethrough(r)),t}supportsHyperlinks(){if(_e())return!1;let e=ye.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=ye.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(ku(t)||t.startsWith("./")||t.startsWith("../"))t=Cu(t);else return null;return hr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,n=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(e,t,...n){if(!this.shouldLog(e))return;let r=new Date,s=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,n);let{consoleText:a,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":jd[e],h=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",w;switch(e){case"debug":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:be.gray(a),level:e}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:be.green(a),level:e}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:s,icon:m,tag:h,message:a,level:e}),console.error(w),l){let N=l.split(`
41
41
  `);for(let R of N)if(R.trim()&&!R.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:be.gray(` ${R}`),level:e,showTimestamp:!1}))}break}}else if(!_e()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}let u=`${i} ${this.environment}.${e.toUpperCase()}: ${c}
42
42
  `;if(l)u+=`${l}
43
43
  `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let n={update:(l,a)=>{},finish:(l)=>{},interrupt:(l,a)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!_e()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!_e()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,a="info")=>{if(!_e()&&ye.stdout.isTTY)ye.stdout.write(`
44
44
  `);if(this[a==="warning"?"warn":a](l),this.activeProgressBar&&this.shouldStyleConsole()&&!_e()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":be.blue("\u25D0"),tag:n,message:`${be.cyan(e)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),s=Math.round(r-t),i=`${e} completed in ${s}ms`,o=new Date,l=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(n)c+=` ${JSON.stringify(n)}`;if(c+=`
45
- `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":be.green("\u2713"),tag:u,message:`${i}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!_e())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,n=new Ur(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(_e())throw Error("createReadStream is not supported in browser environments");if(!hr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mo(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Et.isBuffer(e)?e:Et.from(e,"base64"),s=r.subarray(0,16),i=r.subarray(r.length-16),o=r.subarray(16,r.length-16),l=Du("aes-256-gcm",n,s);l.setAuthTag(i);let a=l.update(o),c=l.final(),u=a.length+c.length,m=Et.allocUnsafe(u);return a.copy(m,0),c.copy(m,a.length),m.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return _e()}isServerMode(){return!_e()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:s,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
45
+ `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":be.green("\u2713"),tag:u,message:`${i}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!_e())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,n=new Ur(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(_e())throw Error("createReadStream is not supported in browser environments");if(!hr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return go(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=xt.isBuffer(e)?e:xt.from(e,"base64"),s=r.subarray(0,16),i=r.subarray(r.length-16),o=r.subarray(16,r.length-16),l=Su("aes-256-gcm",n,s);l.setAuthTag(i);let a=l.update(o),c=l.final(),u=a.length+c.length,m=xt.allocUnsafe(u);return a.copy(m,0),c.copy(m,a.length),m.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return _e()}isServerMode(){return!_e()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:s,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
46
46
  `),a=Math.max(...l.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(a)}\u2510`,u=`\u2514${"\u2500".repeat(a)}\u2518`,m=l.map((h)=>this.formatConsoleMessage({timestamp:n,message:be.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:be.cyan(c),showTimestamp:!1})),m.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:n,message:be.cyan(u),showTimestamp:!1}))}else if(!_e())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let o=`${r} ${this.environment}.INFO: [BOX] ${i}
47
47
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(_e())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${be.cyan("?")} ${e} (y/n) `);let n=(r)=>{let s=r.toString().trim().toLowerCase();ye.stdin.removeListener("data",n);try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!1)}catch{}ye.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!0)}catch{}ye.stdin.resume(),ye.stdin.once("data",n)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let n=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,c=0;if(n=e.replace(a,(u,m)=>{if(m==="%")return"%";if(c>=t.length)return u;let h=t[c++];switch(m){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),c<t.length)n+=` ${t.slice(c).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:r,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?be.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${be.blue("\u25D0")} `;console.error(`${c}${a} ${be.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
48
48
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ye.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*n/100),s=e.barLength-r,i=be.green("\u2501".repeat(r)),o=be.gray("\u2501".repeat(s)),l=`[${i}${o}]`,a=`${n}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||n===100?be.green("\u2713"):be.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${be.gray(this.formatTag(this.name))}`:"",h=`\r${u}${m} ${l} ${a}${c}`,w=ye.stdout.columns||80,N=" ".repeat(Math.max(0,w-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${N}`,ye.stdout.write(e.lastRenderedLine),t)ye.stdout.write(`
49
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||_e()||!ye.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(_e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await pr(this.config.logDirectory),n=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let i=wn(this.config.logDirectory,r);if(e.before)try{if((await Tn(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}n.push(i)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await br(r),console.warn(`Deleted log file: ${r}`)}catch(s){console.error(`Failed to delete log file ${r}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function jd(e,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:s=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),l===n||!s(o))break;if(r>0)await new Promise((c)=>setTimeout(c,r))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class oi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,n={}){let{prefix:r,useCamelCase:s=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:l=!1,trackPerformance:a=!0}=n,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],u,{useCamelCase:s,useBackwardCompatibility:i,customParsers:o,verbose:l,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Ys.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=o.map((u)=>this.formatEnvKey(u,r.useCamelCase)),a=`${n}_${l.join("_")}`,c=r.useBackwardCompatibility?`${n}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,n,r);else{let u=wr.env[a]||(c?wr.env[c]:void 0);if(u!==void 0){if(r.verbose){let m=wr.env[a]?a:c}try{e[s]=this.parseEnvironmentValue(u,typeof i,a,r.customParsers,r.configName)}catch(m){if(m instanceof ii)throw m;throw Gt.envVar(a,u,typeof i,r.configName)}}}}}parseEnvironmentValue(e,t,n,r,s){for(let[i,o]of Object.entries(r))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw Gt.envVar(n,e,`${t} (via ${i.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},n=e.toUpperCase();for(let[r,s]of Object.entries(wr.env))if(r.startsWith(n)&&s!==void 0)t[r]=s;return t}validateEnvironmentVariable(e,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(e,t,n,{})}catch(s){r.push(`Cannot parse value "${t}" as ${n}: ${s}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,n={}){let{prefix:r,format:s="text"}=n,i=r||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),s){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=`${n}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,n,r);else r.push({key:l,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let n=`Environment Variables for ${t}:
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||_e()||!ye.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(_e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await pr(this.config.logDirectory),n=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let i=Tn(this.config.logDirectory,r);if(e.before)try{if((await bn(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}n.push(i)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await br(r),console.warn(`Deleted log file: ${r}`)}catch(s){console.error(`Failed to delete log file ${r}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Wd(e,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:s=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),l===n||!s(o))break;if(r>0)await new Promise((c)=>setTimeout(c,r))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class ci{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,n={}){let{prefix:r,useCamelCase:s=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:l=!1,trackPerformance:a=!0}=n,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),m={...t};return this.processObject(m,[],u,{useCamelCase:s,useBackwardCompatibility:i,customParsers:o,verbose:l,configName:e}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return ei.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=o.map((u)=>this.formatEnvKey(u,r.useCamelCase)),a=`${n}_${l.join("_")}`,c=r.useBackwardCompatibility?`${n}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,n,r);else{let u=wr.env[a]||(c?wr.env[c]:void 0);if(u!==void 0){if(r.verbose){let m=wr.env[a]?a:c}try{e[s]=this.parseEnvironmentValue(u,typeof i,a,r.customParsers,r.configName)}catch(m){if(m instanceof li)throw m;throw Yt.envVar(a,u,typeof i,r.configName)}}}}}parseEnvironmentValue(e,t,n,r,s){for(let[i,o]of Object.entries(r))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw Yt.envVar(n,e,`${t} (via ${i.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},n=e.toUpperCase();for(let[r,s]of Object.entries(wr.env))if(r.startsWith(n)&&s!==void 0)t[r]=s;return t}validateEnvironmentVariable(e,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(e,t,n,{})}catch(s){r.push(`Cannot parse value "${t}" as ${n}: ${s}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,n={}){let{prefix:r,format:s="text"}=n,i=r||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),s){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,n,r){for(let[s,i]of Object.entries(e)){let o=[...t,s],l=`${n}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,n,r);else r.push({key:l,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let n=`Environment Variables for ${t}:
50
50
 
51
51
  `;for(let r of e)n+=`${r.key}
52
52
  `,n+=` Type: ${r.type}
@@ -58,11 +58,11 @@ export type ConfigOf = Config
58
58
  `;n+=`| Variable | Type | Description | Example |
59
59
  `,n+=`|----------|------|-------------|----------|
60
60
  `;for(let r of e)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
61
- `;return n}}function Wd(e,t,n={}){return da(e,t,n,new WeakMap)}function da(e,t,n,r){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=n;if(t===null||t===void 0)return i?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return fa(e,t,s,r);if(!st(t)||!st(e))return t;return Jd(e,t,n,r)}function fa(e,t,n,r){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(n){case"replace":return t;case"concat":return Ud(e,t);case"smart":return Qd(e,t,r);default:return t}return t}function Ud(e,t){let n=[...t];for(let r of e)if(!n.some((s)=>Gs(s,r)))n.push(r);return n}function Qd(e,t,n){if(t.length===0)return e;if(e.length===0)return t;if(st(t[0])&&st(e[0]))return Vd(e,t,n);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}function Vd(e,t,n){let r=[...t];for(let s of e){if(!st(s)){r.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let l of i)if(l in s){if(r.find((c)=>st(c)&&(l in c)&&c[l]===s[l])){o=!0;break}}if(!o)r.push(s)}return r}function Jd(e,t,n,r){let s=t;if(st(s)&&r.has(s))return r.get(s);let i={...e};if(st(s))r.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let l=s[o],a=i[o];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){i[o]=l;continue}if(st(l)&&st(a))i[o]=da(a,l,n,r);else if(Array.isArray(l)||Array.isArray(a))i[o]=fa(a,l,n.arrayMergeMode||"smart",r);else i[o]=l}return i}function ma(e,t,n="replace"){return Wd(e,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Gs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Gs(e[n],t[n]))return!1;return!0}if(st(e)&&st(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Gs(e[s],t[s]))return!1}return!0}return!1}function st(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ga{extensions=Po;async loadFromPath(e,t,n={}){let{arrayStrategy:r="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:l=!1}=n;if(s){let c=kr.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let a=async()=>{if(!Dr(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),m=u.default||u,h="default"in u,w=Object.keys(u).length>0;if(!h&&!w)throw new Kr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new Kr(e,Error("Configuration must export a valid object"),"unknown");let y={config:ma(t,m,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)kr.setWithFileCheck("file",y,e,i);return y}catch(c){throw c instanceof Error?Gt.configLoad(e,c):Gt.configLoad(e,Error(String(c)))}};if(o)return Ys.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,n={}){for(let r of e)try{let s=await this.loadFromPath(r,t,n);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(n.verbose)console.warn(`Failed to load config from ${r}:`,s)}return null}generateConfigPaths(e,t,n){return qc({name:e,directory:t,alias:n})}generateNamePatterns(e,t){return _o({name:e,alias:t})}checkFileAccess(e){return jd(async()=>Dr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,n){let r=[];if(!Dr(e))return r;if(t||n){let s=this.generateNamePatterns(t||"",n);for(let i of s)for(let o of this.extensions){let l=Mo(e,`${i}${o}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let l=Mo(e,o);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(e){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((n)=>n.test(e))}async validateConfigFile(e){let t=[];try{if(!Dr(e))return t.push("Configuration file does not exist"),t;let n=await import(e),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let n=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let s=await this.loadFromPath(r,{},t);if(s)n.set(r,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${r}:`,s)}})),n}}class ya{async validateConfiguration(e,t,n={}){let{stopOnFirstError:r=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:l=!0,verbose:a=!1}=n,c=async()=>{let u=[],m=[],h={stopOnFirstError:r,validateRequired:s,validateTypes:i,customRules:o,trackPerformance:l,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(w){return u.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:u,warnings:m}}};if(l)return await Ys.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,n){try{if(!Hd(t))throw new Fr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),s=r.default||r;if(Array.isArray(s))return this.validateWithRules(e,s,n);else return this.validateWithJSONSchema(e,s,n)}catch(r){throw new Fr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,n){let r=[],s=[];return this.validateObjectAgainstSchema(e,t,"",r,s,n),{isValid:r.length===0,errors:r,warnings:s}}validateObjectAgainstSchema(e,t,n,r,s,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=n?`${n}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,r,s,i),i.stopOnFirstError&&r.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[l,a]of Object.entries(t.properties))if(l in o){let c=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],a,c,r,s,i),i.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!l.has(a))s.push({path:n?`${n}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,n){let r=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),l=this.validateWithRule(o,i,i.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(o){r.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:s}}validateWithRule(e,t,n){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let s=t.validator(e);if(s)r.push({path:n,message:t.message||s,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let n=t.split("."),r=e;for(let s of n)if(r&&typeof r==="object"&&s in r)r=r[s];else return;return r}generateRulesFromInterface(e){let t=[],n=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,s,i,o]=r;t.push({path:s,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:zd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Gd(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class ha{fileLoader=new ga;envProcessor=new oi;validator=new ya;async loadConfig(e){let t=Date.now(),{cache:n,performance:r,schema:s,validate:i,...o}=e;try{if(n?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let l;try{l=await this.loadConfigurationStrategies(o,!0,n)}catch(a){if(o.configFile)throw a;let c=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(c)throw a;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),m=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw a;if(m&&(!c||!h))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(s||i)await this.validateConfiguration(l.config,s,i,o.name);if(n?.enabled&&l)this.cacheResult(o.name||"",l,n,o);if(r?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(a);if(r.slowThreshold&&a.duration>r.slowThreshold)lt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);l.metrics=a}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let a=Date.now()-t;throw lt.error(`Configuration loading failed after ${a}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,n){let{name:r="",alias:s,configFile:i,cwd:o,configDir:l,defaultConfig:a,checkEnv:c=!0,arrayStrategy:u="replace",verbose:m=!1}=e,h=o||qr.cwd(),w=[];if(i){let g=bt(h,i);w.push(g);let p=c?Pn(r,a,m):a,E=await this.fileLoader.tryLoadFromPaths([g],p,{arrayStrategy:u,verbose:m,cacheTtl:n?.ttl,useCache:!n?.ttl||n.ttl>100});if(!E)throw Gt.configNotFound(r||i,w,s);if(m)lt.success(`Configuration loaded from explicit path: ${g}`);return this.finalizeResult(E,w,c,r,m)}let N=await this.loadLocalConfiguration(r,s,h,l,a,u,m,c,n);if(N)return w.push(...this.getLocalSearchPaths(r,s,h,l)),this.finalizeResult(N,w,c,r,m);let R=await this.loadHomeConfiguration(r,s,a,u,m,c);if(R)return w.push(...this.getHomeSearchPaths(r,s)),this.finalizeResult(R,w,c,r,m);let y=await this.loadPackageJsonConfiguration(r,s,h,a,u,m,c);if(y)return w.push(bt(h,"package.json")),this.finalizeResult(y,w,c,r,m);if(w.push(...this.getAllSearchPaths(r,s,h,l)),t)throw Gt.configNotFound(r,w,s);return{...await this.applyEnvironmentVariables(r,a,c,m),warnings:[`No configuration file found for "${r}"${Gd(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,n,r,s,i,o,l,a){let c=l?Pn(e,s,o):s,u=this.getLocalDirectories(n,r);for(let m of u){if(o)lt.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(e,m,t),w=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(w){if(o)lt.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(e,t,n,r,s,i){if(!e)return null;let o=i?Pn(e,n,s):n,l=[bt(dn(),".config",e),bt(dn(),".config"),dn()];for(let a of l){if(s)lt.info(`Checking home directory: ${a}`);let c=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(c,o,{arrayStrategy:r,verbose:s});if(u){if(s)lt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,n,r,s,i,o){let l=o?Pn(e,r,i):r;try{let a=bt(n,"package.json");if(!Wc(a))return null;let c={};try{c=JSON.parse(Uc(a,"utf8"))}catch(h){if(i)lt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=c[e],m=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let w of h){if(!w)continue;if(c[w]){u=c[w],m=w;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)lt.success(`Configuration loaded from package.json: ${m}`);return{config:ma(l,u,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)lt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,n,r){if(!n||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Pn(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,n,r,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,n,r){let s=[];if(n){let i=n(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw Gt.configValidation(r||"unknown",s,r)}checkCache(e,t){let n=this.generateCacheKey(e,t);return kr.get(n)||null}cacheResult(e,t,n,r){let s=this.generateCacheKey(e,r);kr.set(s,t,void 0,n.ttl)}generateCacheKey(e,t){let n=[e];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configFile)n.push(`configFile:${t.configFile}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(e,t){return jc({cwd:e,configDir:t})}getAllSearchPaths(e,t,n,r){let s=[];return s.push(...this.getLocalSearchPaths(e,t,n,r)),s.push(...this.getHomeSearchPaths(e,t)),s.push(bt(n,"package.json")),s}getLocalSearchPaths(e,t,n,r){let s=this.getLocalDirectories(n,r),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let n=[bt(dn(),".config",e),bt(dn(),".config"),dn()],r=[];for(let s of n)r.push(...this.fileLoader.generateConfigPaths(e,s,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}async function pa(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},n="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(n)r=await Ls.loadConfig(e);else r=await Ls.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){if(e.configFile)throw r;let s=r instanceof Error?r.name:"UnknownError",i=r instanceof Error?r.message:String(r);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)lt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ls.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}function Pn(e,t,n=!1){let r=new oi,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,l=[]){let a={...o};for(let[c,u]of Object.entries(o)){let m=[...l,c],h=[`${s}_${m.join("_").toUpperCase()}`,`${s}_${m.map((R)=>R.toUpperCase()).join("")}`,`${s}_${m.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,N;for(let R of h)if(w=qr.env[R],w!==void 0){N=R;break}if(w!==void 0&&N)if(typeof u==="boolean")a[c]=["true","1","yes"].includes(w.toLowerCase());else if(typeof u==="number"){let R=Number(w);if(!Number.isNaN(R))a[c]=R}else if(Array.isArray(u))try{a[c]=JSON.parse(w)}catch{a[c]=w.split(",").map((R)=>R.trim())}else a[c]=w;else if(u&&typeof u==="object"&&!Array.isArray(u))a[c]=i(u,m)}return a}return i(t)}var kr,Ys,Po,vu,Au=(e)=>e,Mu=(e,t)=>{for(var n in t)vu(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Nu.bind(t,n)})},Ou=(e,t)=>()=>(e&&(t=e(e=0)),t),Ko,Ho,Sn,qn,zo,od,ad,wo,$r,js,qe,Ee,ld,Do,cd,So,ud,dd,Os,fd,$o,Eo,Bs,md,gd,yd,hd,Er,Go,pd,je,bd,Td,xo,xr,Ws,Pe,pe,wd,Ro,Dd,ko,Sd,$d,Ps,Ed,Co,vo,xd,_s,Rd,kd,Cd,vd,Ad,Rr,Yo,Nd,Md="0.15.6",Ze,_r,Kn,Us,Qs,Ir,Vs,Js,Fn,Hs,zs,It,Xo,Zo,ct,Ct,ea,ta,Od,Pd,na,Lr,wh,Le,be,Dh,Id,Sh,Ld,$h,Eh,Ao,xh,Kd,Fd,Rh,No,kh,Ch,vh,Ah,Nh,Is,qd,Mh,dt,sa,Kr,ia,oa,ii,aa,la,Fr,ca,ua,Gt,zd,lt,Ls,Ih,Lh;var ba=ut(()=>{kr=new Oo,Ys=new Bo,Po=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];vu=Object.defineProperty;Ko={};Mu(Ko,{withErrorRecovery:()=>jo,tryLoadConfig:()=>nd,loadConfigWithResult:()=>ed,loadConfig:()=>Jo,isRetryableError:()=>Hu,isConfigNotFoundError:()=>Ju,isBunfigError:()=>Wo,globalPerformanceMonitor:()=>qn,globalCache:()=>Sn,getEnvOrDefault:()=>zu,generateConfigTypes:()=>rd,defaultGeneratedDir:()=>ta,defaultConfigDir:()=>ea,deepMergeWithArrayStrategy:()=>ni,deepMerge:()=>Uo,createLibraryConfig:()=>sd,config:()=>td,bunfigPlugin:()=>id,applyEnvVarsToConfig:()=>In,TypeGenerationError:()=>Js,SchemaValidationError:()=>Fn,PluginError:()=>zs,PerformanceMonitor:()=>Zs,FileSystemError:()=>Vs,ErrorFactory:()=>It,EnvVarError:()=>Ir,EnvProcessor:()=>jr,ConfigValidator:()=>ri,ConfigValidationError:()=>Us,ConfigNotFoundError:()=>_r,ConfigMergeError:()=>Qs,ConfigLoader:()=>si,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>Wr,ConfigCache:()=>Xs,CacheUtils:()=>zo,BunfigError:()=>Ze,BrowserConfigError:()=>Hs,ArrayMergeStrategies:()=>Xo});Od=Ou(async()=>{Ho=import.meta.require,Sn=new Xs,qn=new Zs,zo={createKey:Bu,isEquivalent:Pu,estimateMemoryUsage:_u},od=Ar(Fs.cwd(),"config"),ad=Ar(Fs.cwd(),"src/generated"),wo=vr.env.CLARITY_LOG_DIR||Gc(Ku(),"logs"),$r={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},js=await Fu(),qe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Ee=qe,ld=qe.red,Do=qe.green,cd=qe.yellow,So=qe.blue,ud=qe.magenta,dd=qe.cyan,Os=qe.white,fd=qe.gray,$o=qe.bgRed,Eo=qe.bgYellow,Bs=qe.bold,md=qe.dim,gd=qe.italic,yd=qe.underline,hd=qe.reset,Er={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Go={debug:"\uD83D\uDD0D",info:So("\u2139"),success:Do("\u2713"),warning:Eo(Os(Bs(" WARN "))),error:$o(Os(Bs(" ERROR ")))},pd=new Or("stacks"),je=new Or("bunfig",{showTags:!0}),bd=Qe(Ln.cwd(),"config"),Td=Qe(Ln.cwd(),"src/generated"),xo=Cr.env.CLARITY_LOG_DIR||Hc(Uu(),"logs"),xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ws=await Qu(),Pe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},pe=Pe,wd=Pe.red,Ro=Pe.green,Dd=Pe.yellow,ko=Pe.blue,Sd=Pe.magenta,$d=Pe.cyan,Ps=Pe.white,Ed=Pe.gray,Co=Pe.bgRed,vo=Pe.bgYellow,xd=Pe.bgGray,_s=Pe.bold,Rd=Pe.dim,kd=Pe.italic,Cd=Pe.underline,vd=Pe.strikethrough,Ad=Pe.reset,Rr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Yo={debug:"\uD83D\uDD0D",info:ko("\u2139"),success:Ro("\u2713"),warning:vo(Ps(_s(" WARN "))),error:Co(Ps(_s(" ERROR ")))},Nd=new Pr("stacks"),Ze=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},_r=class extends Ze{code="CONFIG_NOT_FOUND";constructor(t,n,r){let s=r?` or alias "${r}"`:"";super(`Configuration "${t}"${s} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},Kn=class extends Ze{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Us=class extends Ze{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Qs=class extends Ze{code="CONFIG_MERGE_ERROR";constructor(t,n,r,s){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:s,originalError:r.name,originalMessage:r.message});this.cause=r}},Ir=class extends Ze{code="ENV_VAR_ERROR";constructor(t,n,r,s){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:s})}},Vs=class extends Ze{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Js=class extends Ze{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Fn=class extends Ze{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Hs=class extends Ze{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,s){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:s})}},zs=class extends Ze{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},It={configNotFound(e,t,n){return new _r(e,t,n)},configLoad(e,t,n){return new Kn(e,t,n)},configValidation(e,t,n){return new Us(e,t,n)},configMerge(e,t,n,r){return new Qs(e,t,n,r)},envVar(e,t,n,r){return new Ir(e,t,n,r)},fileSystem(e,t,n){return new Vs(e,t,n)},typeGeneration(e,t,n){return new Js(e,t,n)},schemaValidation(e,t,n){return new Fn(e,t,n)},browserConfig(e,t,n,r){return new Hs(e,t,n,r)},plugin(e,t,n){return new zs(e,t,n)}},Xo={replace:"replace",concat:"concat",smart:"smart"},Zo=/^https?:\/\//,ct=new Pr("bunfig",{showTags:!0}),Ct=new si,ea=Ve(Yt.cwd(),"config"),ta=Ve(Yt.cwd(),"src/generated")});Pd=Nr.env.CLARITY_LOG_DIR||bu(Bd(),"logs"),na={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Pd,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lr={...na},wh=(async()=>{try{let{loadConfig:e}=await Od().then(()=>Ko),t=await e({name:"clarity",alias:"logging",defaultConfig:na,cwd:Nr.cwd()});if(t)Object.assign(Lr,t)}catch{}return Lr})();Le={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},be=Le,Dh=Le.red,Id=Le.green,Sh=Le.yellow,Ld=Le.blue,$h=Le.magenta,Eh=Le.cyan,Ao=Le.white,xh=Le.gray,Kd=Le.bgRed,Fd=Le.bgYellow,Rh=Le.bgGray,No=Le.bold,kh=Le.dim,Ch=Le.italic,vh=Le.underline,Ah=Le.strikethrough,Nh=Le.reset,Is={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qd={debug:"\uD83D\uDD0D",info:Ld("\u2139"),success:Id("\u2713"),warning:Fd(Ao(No(" WARN "))),error:Kd(Ao(No(" ERROR ")))};Mh=new Ur("stacks");dt=class dt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};sa=class sa extends dt{code="CONFIG_NOT_FOUND";constructor(e,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],s="";if(r.length===1)s=` or alias "${r[0]}"`;else if(r.length>1)s=` or aliases ${r.map((i)=>`"${i}"`).join(", ")}`;super(`Configuration "${e}"${s} not found`,{configName:e,alias:n,searchPaths:t,searchPathCount:t.length})}};Kr=class Kr extends dt{code="CONFIG_LOAD_ERROR";constructor(e,t,n){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}};ia=class ia extends dt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,n){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:n,validationErrors:t,errorCount:t.length})}};oa=class oa extends dt{code="CONFIG_MERGE_ERROR";constructor(e,t,n,r){super(`Failed to merge configuration from "${e}" with "${t}": ${n.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}};ii=class ii extends dt{code="ENV_VAR_ERROR";constructor(e,t,n,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${n}`,{envKey:e,envValue:t,expectedType:n,configName:r})}};aa=class aa extends dt{code="FILE_SYSTEM_ERROR";constructor(e,t,n){super(`File system ${e} failed for "${t}": ${n.message}`,{operation:e,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}};la=class la extends dt{code="TYPE_GENERATION_ERROR";constructor(e,t,n){super(`Failed to generate types from "${e}" to "${t}": ${n.message}`,{configDir:e,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}};Fr=class Fr extends dt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:e,configName:n,validationErrors:t,errorCount:t.length})}};ca=class ca extends dt{code="BROWSER_CONFIG_ERROR";constructor(e,t,n,r){super(`Failed to fetch configuration from "${e}": ${t} ${n}`,{endpoint:e,status:t,statusText:n,configName:r})}};ua=class ua extends dt{code="PLUGIN_ERROR";constructor(e,t,n){super(`Plugin "${e}" failed during ${t}: ${n.message}`,{pluginName:e,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}};Gt={configNotFound(e,t,n){return new sa(e,t,n)},configLoad(e,t,n){return new Kr(e,t,n)},configValidation(e,t,n){return new ia(e,t,n)},configMerge(e,t,n,r){return new oa(e,t,n,r)},envVar(e,t,n,r){return new ii(e,t,n,r)},fileSystem(e,t,n){return new aa(e,t,n)},typeGeneration(e,t,n){return new la(e,t,n)},schemaValidation(e,t,n){return new Fr(e,t,n)},browserConfig(e,t,n,r){return new ca(e,t,n,r)},plugin(e,t,n){return new ua(e,t,n)}};zd=/^https?:\/\//;lt=new Ur("bunfig",{showTags:!0});Ls=new ha;Ih=bt(qr.cwd(),"config"),Lh=bt(qr.cwd(),"src/generated")});import Ta from"process";function ne(e=_.dialect){return e==="mysql"||e==="singlestore"||e==="vitess"}function wa(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ai(e,t,n=new Set){let r={...e};n.add(t);for(let s of Object.keys(t)){if($a.has(s))continue;let i=t[s];if(wa(i)&&!n.has(i)){let o=r[s];r[s]=ai(wa(o)?o:{},i,n)}else r[s]=i}return n.delete(t),r}function Vr(e){if(e)return e;let t=Ta.env.DB_DIALECT||Ta.env.DB_CONNECTION;if(t)return t;return _.dialect||"postgres"}function Z(e){if(_.dialect==="postgres")return`$${e}`;return"?"}function ve(e,t=1){if(e<=0)return"";if(_.dialect==="postgres"){let n=`$${t}`;for(let r=1;r<e;r++)n+=`, $${t+r}`;return n}return e===1?"?":`?${", ?".repeat(e-1)}`}async function Jr(){if(!Qr.fileLoaded){Qr.fileLoaded=!0;let e=await pa({name:"query-builder",alias:"qb",defaultConfig:Sa}),t={};for(let[n,r]of Object.entries(e??{}))if(!Qr.explicit.has(n))t[n]=r;Ea(t)}return _}function Ea(e){let t=ai(_,e),n=_;for(let r of Object.keys(t)){if($a.has(r))continue;n[r]=t[r]}}function xa(e){if(e.dialect&&jn&&e.dialect!==jn){let t=`${jn}->${e.dialect}`;if(!Da.has(t))Da.add(t),console.warn(`[query-builder] Configuring dialect '${e.dialect}' overrides the previously configured dialect '${jn}'. 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(e.dialect)jn=e.dialect;for(let t of Object.keys(e))Qr.explicit.add(t);Ea(e)}function jh(e){return e}var Sa,$a,Yd,_,Xd,Qr,jn=null,Da;var Me=ut(()=>{ba();Sa={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}},$a=new Set(["__proto__","constructor","prototype"]);Yd=Symbol.for("bun-query-builder.config"),_=globalThis[Yd]??=ai({},Sa),Xd=Symbol.for("bun-query-builder.config-state"),Qr=globalThis[Xd]??={explicit:new Set,fileLoaded:!1};Da=new Set});function ef(){let e=_.sqlite?.pragmas;return Array.isArray(e)?e:Zd}function Wn(e){for(let t of ef())try{e.run(t)}catch{}}var Zd;var Hr=ut(()=>{Me();Zd=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:Ra}=globalThis.Bun;import{Database as nf}from"bun:sqlite";import{mkdirSync as rf}from"fs";import{dirname as sf}from"path";import Qn from"process";function Un(e){return e}function tf(e){return e!==null&&typeof e==="object"?e:null}function ka(e,t){if(t.length===0||!/\$\d/.test(e))return{sql:e,params:t};let n=[],r="",s=0;for(let i=0;i<e.length;i++){let o=e[i];if(o==="'"||o==='"'||o==="`"){let l=of(e,i,o);r+=e.slice(i,l),i=l-1;continue}if(o==="-"&&e[i+1]==="-"){let l=e.indexOf(`
62
- `,i),a=l===-1?e.length:l;r+=e.slice(i,a),i=a-1;continue}if(o==="/"&&e[i+1]==="*"){let l=e.indexOf("*/",i+2),a=l===-1?e.length:l+2;r+=e.slice(i,a),i=a-1;continue}if(o==="$"){let l=/^\d+/.exec(e.slice(i+1))?.[0];if(l){let a=Number(l);if(s=Math.max(s,a),a>=1&&a<=t.length){n.push(t[a-1]),r+="?",i+=l.length;continue}}}r+=o}if(s>t.length)throw Error(`SQL references $${s} but only ${t.length} value${t.length===1?" was":"s were"} provided`);if(n.length===0)return{sql:e,params:t};return{sql:r,params:n}}function of(e,t,n){for(let r=t+1;r<e.length;r++){if(e[r]!==n)continue;if(e[r+1]===n){r++;continue}return r+1}return e.length}class Na{db;constructor(e){if(e!==":memory:"&&!e.startsWith(":")){let t=sf(e);if(t&&t!==".")rf(t,{recursive:!0})}this.db=new nf(e),Wn(this.db)}query(e,t=[]){let n=ka(e,t);return this.db.prepare(n.sql).all(...n.params)}run(e,t=[]){let n=ka(e,t);return this.db.prepare(n.sql).run(...n.params)}close(){this.db.close()}get database(){return this.db}}function Ca(e){return{__raw:!0,value:e,toString:()=>e}}function va(e){let t=e.trimStart();for(;;)if(t.startsWith("--")){let n=t.indexOf(`
63
- `);t=n===-1?"":t.slice(n+1).trimStart()}else if(t.startsWith("/*")){let n=t.indexOf("*/");t=n===-1?"":t.slice(n+2).trimStart()}else return t}function af(e){let t=[],n="",r=!1,s=!1,i=!1,o=!1;for(let a=0;a<e.length;a++){let c=e[a],u=e[a+1];if(!r&&!s&&!o&&c==="-"&&u==="-"){i=!0,n+=c;continue}if(i&&(c===`
64
- `||c==="\r")){i=!1,n+=c;continue}if(!r&&!s&&!i&&c==="/"&&u==="*"){o=!0,n+=c;continue}if(o&&c==="*"&&u==="/"){o=!1,n+=c+u,a++;continue}if(i||o){n+=c;continue}if(c==="'"&&!s){if(r&&u==="'"){n+=c+u,a++;continue}r=!r,n+=c;continue}if(c==='"'&&!r){s=!s,n+=c;continue}if(c===";"&&!r&&!s){let m=va(n.trim());if(m)t.push(m);n="";continue}n+=c}let l=va(n.trim());if(l)t.push(l);return t}function Aa(e){let t=new Na(e);function n(i,...o){let l=i[0],a=[];for(let c=0;c<o.length;c++){let u=o[c],m=tf(u);if(m&&typeof m.sql==="string"&&Array.isArray(m.values))l+=m.sql+(i[c+1]||""),a.push(...m.values);else if(m&&(m.__raw||m.raw)){let h=m.raw,w=m.__raw?m.value:typeof h==="string"?h:h();l+=w+(i[c+1]||"")}else if(Array.isArray(u)){let h=u.map(()=>"?").join(", ");l+=h+(i[c+1]||""),a.push(...u)}else l+=`?${i[c+1]||""}`,a.push(u)}return{sql:l,values:a,execute:()=>{try{let c=l.trim().toUpperCase();if(c.startsWith("SELECT")||c.startsWith("PRAGMA")||/\bRETURNING\b/.test(c)){let u=t.query(l,Un(a));return Promise.resolve(u)}else{let u=t.run(l,Un(a));return Promise.resolve(u)}}catch(c){return Promise.reject(c)}},raw:()=>l,toString:()=>l,cancel:()=>{}}}function r(i,...o){if(Array.isArray(i)&&"raw"in i)return n(i,...o);if(typeof i==="string")return Ca(i);return n([""])}r.raw=(i)=>Ca(i),r.unsafe=(i,o=[])=>{let l=()=>{try{let a=i.trim().toUpperCase();if(a.startsWith("SELECT")||a.startsWith("PRAGMA")||/\bRETURNING\b/.test(a)){let c=t.query(i,Un(o));return Promise.resolve(c)}else{let c=t.run(i,Un(o));return Promise.resolve(c)}}catch(a){return Promise.reject(a)}};return{sql:i,values:o,execute:l,then:(a,c)=>l().then(a,c),raw:()=>i,toString:()=>i,cancel:()=>{}}},r.close=()=>(t.close(),Promise.resolve()),r.query=(i,o)=>{try{let l=t.query(i,Un(o||[]));return Promise.resolve(l)}catch(l){return Promise.reject(l)}},r.file=async(i,o)=>{try{let{readFileSync:l}=await import("fs"),a=l(i,"utf-8"),c=af(a);for(let u of c){let m=u.trim();if(!m||m.startsWith("--"))continue;let h=m.toUpperCase();if(h.startsWith("SELECT")||h.startsWith("PRAGMA"))t.query(u);else t.run(u)}return Promise.resolve([])}catch(l){return Promise.reject(l)}};let s=0;return r.begin=async(i,o)=>{let l=typeof i==="function"?i:o;if(typeof l!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let a=s>0,c=`qb_sp_${s}`;if(a)t.run(`SAVEPOINT ${c}`);else t.run("BEGIN");s++;try{let u=await l(r);if(s--,a)t.run(`RELEASE SAVEPOINT ${c}`);else t.run("COMMIT");return u}catch(u){s--;try{if(a)t.run(`ROLLBACK TO SAVEPOINT ${c}`),t.run(`RELEASE SAVEPOINT ${c}`);else t.run("ROLLBACK")}catch{}throw u}},r.savepoint=r.begin,r.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},r._wrapper=t,r}function lf(e){let t=e.replace(/^(?:sqlite|sqlite3|file):/i,"");if(t===e)return e;return(t.startsWith("///")?t.slice(2):t.startsWith("//")?t.slice(2):t)||":memory:"}function zr(e=_.database){let t=Qn.env.DB_DATABASE||e?.database||"";return String(t).replace(/^['"]|['"]$/g,"")}function cf(e,t){if((e==="postgres"||e==="mysql"||e==="singlestore"||e==="vitess")&&Qn.env.DB_CONNECTION===e){let c=Qn.env,u=(c.DB_DATABASE||t.database||"").replace(/^['"]|['"]$/g,""),m=c.DB_USERNAME||t.username,h=c.DB_PASSWORD??t.password??"",w=c.DB_HOST||t.host||"localhost",N=c.DB_PORT||t.port,R=e==="postgres"?"postgres":"mysql",y=c.DB_SSL==="true"||c.DB_SSL==="1"||t.ssl?"?ssl=true":"";return`${R}://${m}:${h}@${w}${N?`:${N}`:""}/${u}${y}`}if(t.url)return e==="sqlite"?lf(t.url):t.url;let{database:n,username:r,password:s,host:i="localhost",port:o,ssl:l}=t,a=l||Qn.env.DB_SSL==="true"||Qn.env.DB_SSL==="1"?"?ssl=true":"";switch(e){case"postgres":return`postgres://${r}:${s}@${i}${o?`:${o}`:""}/${n}${a}`;case"mysql":case"singlestore":case"vitess":return`mysql://${r}:${s}@${i}${o?`:${o}`:""}/${n}${a}`;case"sqlite":if(n===":memory:")return":memory:";return n||":memory:";default:throw Error(`Unsupported dialect: ${e}`)}}function Ma(e){if(!e)return{};let t={},n=(r)=>Math.max(0,Math.round(r/1000));if(typeof e.max==="number"&&Number.isFinite(e.max))t.max=e.max;if(typeof e.idleTimeoutMs==="number"&&Number.isFinite(e.idleTimeoutMs))t.idleTimeout=n(e.idleTimeoutMs);if(typeof e.acquireTimeoutMs==="number"&&Number.isFinite(e.acquireTimeoutMs))t.connectionTimeout=n(e.acquireTimeoutMs);if(typeof e.maxLifetimeMs==="number"&&Number.isFinite(e.maxLifetimeMs))t.maxLifetime=n(e.maxLifetimeMs);return t}function uf(){let e=_.dialect,t=cf(e,_.database);try{if(e==="sqlite")return Aa(t);let n=Ma(_.database.pool);return Object.keys(n).length>0?new Ra(t,n):new Ra(t)}catch(n){if(console.error(`[query-builder] Failed to create database connection for dialect '${e}': ${n.message}`),e==="sqlite")return Aa(":memory:");throw n}}function df(){let e=_.database;return JSON.stringify({dialect:_.dialect,database:e.database,username:e.username,password:e.password,host:e.host,port:e.port,url:e.url,pool:Ma(e.pool)})}function Lt(e=!1){let t=df();if(e||Xt!==null&&li!==t||!Xt){if(Xt)Oa();Xt=uf(),li=t}return Xt}function ff(){let e=Xt;return Xt=null,li=null,e}async function mf(e){if(!e||typeof e.close!=="function")return;await e.close()}function Oa(){mf(ff()).catch((t)=>{console.error(`[query-builder] Failed to close database connection: ${t.message}`)})}async function ci(e){try{return await e(Lt())}catch(t){if(t?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||t?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let n=Lt(!0);return await e(n)}throw t}}function gf(){return new Proxy(function(){},{get(e,t){let n=Lt(),r=n[t];if(typeof r==="function")return r.bind(n);return r},apply(e,t,n){return Lt()(...n)}})}var Xt=null,li=null,te;var Kt=ut(()=>{Me();Hr();te=gf()});function $n(e){return e==="integer"||e==="bigint"||e==="float"||e==="double"||e==="decimal"}function Ba(e){if(typeof e!=="string")return;switch(e.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Zr(e){switch(e){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}var ui=()=>{};function di(e){let t=String(e).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(t.endsWith("y")&&!/[aeou]y$/.test(t))return`${t.slice(0,-1)}ies`;if(t.endsWith("s")||t.endsWith("x")||t.endsWith("ch")||t.endsWith("sh"))return`${t}es`;return`${t}s`}function Ft(e){return typeof e?.table==="string"&&e.table.length>0?e.table:di(String(e?.name??""))}function bf(e){return e.endsWith("s")?e.slice(0,-1):e}function Tf(e){if(e.endsWith("ies")&&e.length>3){let t=e.slice(0,-3),n=t[t.length-1];if(n&&!"aeiou".includes(n))return`${t}y`}if(e.endsWith("es")&&e.length>2){let t=e.slice(0,-2);if(t.endsWith("s")||t.endsWith("x")||t.endsWith("ch")||t.endsWith("sh"))return t}if(e.endsWith("s")&&!e.endsWith("ss")&&!e.endsWith("us")&&!e.endsWith("is"))return e.slice(0,-1);return e}function qt(e){if(e==="none")return(t)=>t;if(e==="inflect")return Tf;return bf}var jt=()=>{};function tn(e){if(e.length===0)return"";let t=[];for(let n of e)if(n.conn==="OR"&&t.length>0)t[t.length-1].push(n);else t.push([n]);return t.map((n,r)=>{let s=n.map((o)=>o.sql).join(" OR "),i=n.length>1&&t.length>1?`(${s})`:s;return r===0?i:`${n[0].conn} ${i}`}).join(" ")}function Ge(e,t,n,r){if(t.length===0)return n?"1 = 1":"1 = 0";return`${e} ${n?"NOT IN":"IN"} (${r})`}function Df(e,t){if(t!=="postgres")return e;let n="",r=0,s=0;while(s<e.length){let i=e[s];if(i==="'"){let o=Pa(e,s,"'");n+=e.slice(s,o),s=o;continue}if(i==='"'){let o=Pa(e,s,'"');n+=e.slice(s,o),s=o;continue}if(i==="$"){let o=e.slice(s).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(o){let l=e.indexOf(o,s+o.length),a=l===-1?e.length:l+o.length;n+=e.slice(s,a),s=a;continue}}if(i==="?"){r++,n+=`$${r}`,s++;continue}n+=i,s++}return n}function Pa(e,t,n){let r=t+1;while(r<e.length){if(e[r]===n){if(e[r+1]===n){r+=2;continue}return r+1}r++}return e.length}function ts(e,t,n=Number.POSITIVE_INFINITY){let r=[],s=0,i=(o)=>o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122||o===95;for(let o=0;o<e.length;o++){let l=e.charCodeAt(o);if(l===45&&e.charCodeAt(o+1)===45){let c=e.indexOf(`
65
- `,o+2);if(c===-1)return r;o=c;continue}if(l===47&&e.charCodeAt(o+1)===42){let c=1,u=o+2;while(u<e.length&&c>0)if(e[u]==="/"&&e[u+1]==="*")c++,u+=2;else if(e[u]==="*"&&e[u+1]==="/")c--,u+=2;else u++;o=u-1;continue}if(l===39||l===34||l===96){let c=o+1;while(c<e.length){if(e.charCodeAt(c)===l){if(e.charCodeAt(c+1)===l){c+=2;continue}break}c++}o=c;continue}if(l===36){let c=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(e.slice(o));if(c){let u=e.indexOf(c[0],o+c[0].length);o=u===-1?e.length:u+c[0].length-1;continue}}if(l===40){s++;continue}if(l===41){s=Math.max(0,s-1);continue}if(s!==0)continue;if(o===0)continue;let a=l&-33;if(a<65||a>90)continue;if(i(e.charCodeAt(o-1)))continue;for(let{key:c,pattern:u}of t){u.lastIndex=o;let m=u.exec(e);if(!m)continue;if(r.push({key:c,start:o,length:m[0].length}),r.length>=n)return r;o+=m[0].length-1;break}}return r}var _a="1 = 0";var ns=()=>{};function xn(e){if(typeof e==="number")return{length:e};return e}function Si(e){if(typeof e==="number")return{max:e};return e}function Gm(e){return typeof e==="function"}function Ym(e){return e.replace(/[A-Z]/g,(t)=>t.toLowerCase())}function wl(e,t){if(!t||typeof t.fractionDigits!=="number")return e;return Number(e.toFixed(t.fractionDigits))}function Ut(e,t={}){if(!e)return t;return new Proxy(e,{get(n,r){if(r in t)return t[r];let s=n[r];if(s!==void 0)return s;let i=n[Ym(r)];if(Gm(i))return i.bind(n);return}})}function Dl(e){let t=(u)=>{let m=Array.isArray(u)?u:[],h=Math.floor(Math.random()*m.length);return m[h]},n=()=>e.string,r=()=>e.number,s=()=>e.random,i=Ut(e.string,{alpha:(u)=>n()?.alpha?.(xn(u)),alphanumeric:(u)=>n()?.alphanumeric?.(xn(u)),numeric:(u)=>n()?.numeric?.(xn(u)),sample:(u)=>n()?.sample?.(xn(u)),hexadecimal:(u)=>n()?.hexadecimal?.(xn(u))}),o=Ut(e.number,{int:(u)=>r()?.int?.(Si(u)),float:(u)=>{let m=Si(u);return wl(Number(r()?.float?.(m)??0),m)}}),l=Ut(e.helpers,{arrayElement:t,arrayElements:(u,m)=>{let h=[...Array.isArray(u)?u:[]],w=typeof m==="number"?m:Math.max(1,Math.floor(Math.random()*h.length));for(let N=h.length-1;N>0;N-=1){let R=Math.floor(Math.random()*(N+1));[h[N],h[R]]=[h[R],h[N]]}return h.slice(0,Math.min(w,h.length))},shuffle:(u)=>{let m=[...Array.isArray(u)?u:[]];for(let h=m.length-1;h>0;h-=1){let w=Math.floor(Math.random()*(h+1));[m[h],m[w]]=[m[w],m[h]]}return m},maybe:(u,m)=>{let h=typeof m?.probability==="number"?m.probability:0.5;return Math.random()<h?u():void 0},slugify:(u)=>String(u??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),c={string:i,number:o,helpers:l,datatype:{boolean:(u)=>{let m=typeof u==="number"?u:u?.probability;if(typeof m==="number")return Math.random()<m;return Boolean(s()?.boolean?.())},number:(u)=>Number(r()?.int?.(Si(u))??0),float:(u)=>wl(Number(r()?.float?.(u)??0),u),uuid:()=>crypto.randomUUID(),string:(u)=>String(n()?.alphanumeric?.({length:u??10})??""),hexadecimal:(u)=>String(n()?.hexadecimal?.(xn(u))??""),array:(u)=>Array.from({length:u??3},()=>n()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:n()?.alphanumeric?.({length:8})})},location:Ut(e.address),address:Ut(e.address),vehicle:Ut(e.vehicle,{vrm:()=>e.vehicle?.registration?.()}),company:Ut(e.company,{catchPhrase:()=>e.company?.catchphrase?.(),buzzPhrase:()=>e.company?.bs?.()??e.company?.buzzword?.()})};return new Proxy(e,{get(u,m){if(m in c)return c[m];let h=u[m];if(h&&typeof h==="object")return Ut(h);return h}})}var $i=()=>{};function us(e){if(typeof e==="string")return{model:e};if(e&&typeof e==="object"&&typeof e.model==="string"){let t=e;return{model:t.model,foreignKey:t.foreignKey,onDelete:t.onDelete}}return null}function Rn(e){if(!e)return[];return(Array.isArray(e)?e:typeof e==="object"?Object.values(e):[]).map(us).filter((n)=>n!==null)}var ds=()=>{};import{Database as Ci}from"bun:sqlite";function on(){let e=new Date().toISOString();return ne(_.dialect)?e.slice(0,19).replace("T"," "):e}function Nt(e,t){if(typeof e!=="string"||e.length===0)throw TypeError(`[bun-query-builder] ${t}: identifier must be a non-empty string, got ${typeof e}`);if(e.length>64)throw TypeError(`[bun-query-builder] ${t}: identifier '${e}' exceeds 64 chars`);if(!vl.test(e))throw TypeError(`[bun-query-builder] ${t}: identifier '${e}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Al(e,t){if(typeof e!=="string"||e.length===0)throw TypeError(`[bun-query-builder] ${t}: identifier must be a non-empty string, got ${typeof e}`);let n=e.split(".");if(n.length>2||n.some((r)=>r.length===0||r.length>64||!vl.test(r)))throw TypeError(`[bun-query-builder] ${t}: invalid ORDER BY column '${e}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Zm(e,t){Ai.set(e,t),kn.clear()}function Nl(){Ai.clear(),kn.clear()}function et(e){if(!fs)try{fs=(tr(),Xm(Il)).getModel}catch{fs=()=>{return}}return fs(e)??Ai.get(e)}function Sl(e){let t=ms.get(e);if(t!==void 0)return t;let n=0,r=e.replace(/\?/g,()=>`$${++n}`);if(ms.size>=eg)ms.clear();return ms.set(e,r),r}function $l(e){if(e==null)return 0;if(typeof e.affectedRows==="number")return e.affectedRows;if(typeof e.count==="number")return e.count;if(Array.isArray(e))return e.length;return 0}function El(e){if(e==null||typeof e!=="object")return null;if("insertId"in e&&e.insertId!=null)return e.insertId;if("lastInsertRowid"in e&&e.lastInsertRowid!=null)return e.lastInsertRowid;return null}class vi{sqliteDb;dialect="sqlite";constructor(e){this.sqliteDb=e}all(e,t){return Promise.resolve(this.sqliteDb.query(e).all(...t))}get(e,t){return Promise.resolve(this.sqliteDb.query(e).get(...t)??void 0)}run(e,t){let n=this.sqliteDb.run(e,t);return Promise.resolve({changes:n.changes,lastInsertId:n.lastInsertRowid})}insert(e,t){return this.run(e,t)}}class Ml{dialect;constructor(e){this.dialect=e}conn(){return Lt()}text(e){return this.dialect==="postgres"?Sl(e):e}async all(e,t){let n=await this.conn().unsafe(this.text(e),t);return Array.isArray(n)?n:[]}async get(e,t){let n=await this.conn().unsafe(this.text(e),t);if(Array.isArray(n))return n[0]??void 0;return n??void 0}async run(e,t){let n=await this.conn().unsafe(this.text(e),t);return{changes:$l(n),lastInsertId:El(n)}}async insert(e,t,n){if(this.dialect==="postgres"){let i=await this.conn().unsafe(`${Sl(e)} RETURNING ${n}`,t),o=Array.isArray(i)?i[0]:i;return{changes:1,lastInsertId:o?o[n]??null:null}}let r=await this.conn().unsafe(e,t),s=El(r);if(s==null){let i=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);s=(Array.isArray(i)?i[0]:i)?.id??null}return{changes:$l(r)||1,lastInsertId:s}}}function aw(e){if(e.database instanceof Ci)sn=e.database;else sn=new Ci(e.database||":memory:",{create:!0}),Wn(sn);Mt=null,er=null}function De(){if(sn){if(!Mt||er!==sn)Mt=new vi(sn),er=sn,Ei="sqlite",xi=null;return Mt}let e=_.dialect,t=_.database?.database??null;if(Mt&&er===null&&Ei===e&&xi===t)return Mt;if(er=null,Ei=e,xi=t,e==="sqlite"){let n=new Ci(t||":memory:",{create:!0});Wn(n),Mt=new vi(n)}else Mt=new Ml(e);return Mt}function lw(){let e=De();if(e.sqliteDb)return e.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${e.dialect}'. Use the async model API instead.`)}function Cn(e){let t=e.traits;return Boolean(t?.useSoftDeletes||t?.softDeletable)}function an(e){let t=e.traits;return Boolean(t?.useTimestamps||t?.timestampable)}function tg(e){let t=xl.get(e);if(t)return t;let n=new Set,r=e.belongsToMany;if(r){if(Array.isArray(r)){for(let s of r)if(typeof s==="string")n.add(s.toLowerCase());else if(s&&typeof s==="object"&&s.model)n.add(s.model.toLowerCase())}else if(typeof r==="object")for(let s of Object.keys(r))n.add(s)}return xl.set(e,n),n}function Ol(e){let t={};for(let[n,r]of Object.entries(e))t[$e(n)]=r;return t}function ng(e){for(let t in e)if($e(t)!==t)return Ol(e);return e}function rg(e,t){if(e[t])return e[t];let n=$e(t);if(e[n])return e[n];for(let r of Object.keys(e))if($e(r)===n)return e[r];return}class Xe{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(e,t={}){this._definition=e,this._attributes=ng({...t}),this._original=null;let n=tg(e);if(n.size===0)return;let r=this;return new Proxy(this,{get(s,i,o){if(typeof i==="string"&&n.has(i)&&!(i in s))return()=>{let l=Bl(e,i);if(!l||l.type!=="belongsToMany")throw Error(`[orm] relation '${i}' did not resolve to a belongsToMany on '${e.name}'`);let a=et(l.relatedModelName),c=a?.getDefinition?.()||a?.definition;if(!c)throw Error(`[orm] related model '${l.relatedModelName}' is not registered`);return new Pl(r,e,l,c)};return Reflect.get(s,i,o)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(e){let t=this._definition.get?.[e];if(t)try{let n=t(this._attributes);if(n!==void 0)return n}catch{}return this._attributes[$e(e)]}getAttribute(e){return this._attributes[$e(e)]}getAttributes(){return{...this._attributes}}set(e,t){if(this._original===null)this._original={...this._attributes};this._attributes[$e(e)]=t}only(e){let t={};for(let n of e)t[n]=this._attributes[$e(n)];return t}except(e){let t=new Set(e.map((r)=>$e(r))),n={};for(let r of Object.keys(this._attributes))if(!t.has(r))n[r]=this._attributes[r];return n}getRelation(e){return this._relations[e]}setRelation(e,t){this._relations[e]=t}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}isDirty(e){if(this._original===null)return!1;if(e){let t=$e(e);return this._attributes[t]!==this._original[t]}return Object.keys(this._attributes).some((t)=>this._attributes[t]!==this._original[t])}isClean(e){return!this.isDirty(e)}getOriginal(e){return this.getOriginalAttributes()[$e(e)]}getChanges(){if(this._original===null)return{};let e={};for(let t of Object.keys(this._attributes))if(this._attributes[t]!==this._original[t])e[t]=this._attributes[t];return e}fill(e){let t=this._definition.attributes;for(let[n,r]of Object.entries(e)){let s=rg(t,n),i=!s&&$e(n).endsWith("_id");if(s?.fillable&&!s?.guarded||i){if(this._original===null)this._original={...this._attributes};this._attributes[$e(n)]=r}}return this}forceFill(e){if(this._original===null)this._original={...this._attributes};let t=Ol(e);Object.assign(this._attributes,t);for(let n of Object.keys(t))this._forced.add(n);return this}async save(){let e=De(),t=this._definition.primaryKey||"id",n=this._definition.hooks,r=this._definition.set||{};for(let[s,i]of Object.entries(r))if(this.isDirty(s))this._attributes[$e(s)]=i(this._attributes);if(this._attributes[t]){await n?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){let o=i.map((a)=>`${a} = ?`).join(", "),l=[...Object.values(s),this._attributes[t]];if(an(this._definition)){let a=on();await e.run(`UPDATE ${this._definition.table} SET ${o}, updated_at = ? WHERE ${t} = ?`,[...Object.values(s),a,this._attributes[t]])}else await e.run(`UPDATE ${this._definition.table} SET ${o} WHERE ${t} = ?`,l)}await n?.afterUpdate?.(this)}else{let s=this._definition.attributes,i={};for(let[c,u]of Object.entries(s)){if(u.guarded&&!this._forced.has($e(c)))continue;let m=$e(c);if(this._attributes[m]!==void 0)i[m]=this._attributes[m]}for(let c of Object.keys(this._attributes))if(c.endsWith("_id")&&c!==t&&!(c in i))i[c]=this._attributes[c];if(an(this._definition)){let c=on();i.created_at=c,i.updated_at=c}if(this._definition.traits?.useUuid&&!i.uuid)i.uuid=crypto.randomUUID();await n?.beforeCreate?.(i);let o=Object.keys(i),l=o.map(()=>"?").join(", "),a=await e.insert(`INSERT INTO ${this._definition.table} (${o.join(", ")}) VALUES (${l})`,Object.values(i),t);for(let[c,u]of Object.entries(i))this._attributes[c]=u;if(a.lastInsertId!=null)this._attributes[t]=a.lastInsertId;await n?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(e){return this.fill(e),this.save()}async fresh(){let e=De(),t=this._definition.primaryKey||"id",n=this._attributes[t];if(n==null)return null;let r=await e.get(`SELECT * FROM ${this._definition.table} WHERE ${t} = ?`,[n]);if(!r)return null;return new Xe(this._definition,r)}async delete(){let e=De(),t=this._definition.primaryKey||"id",n=this._attributes[t],r=this._definition.hooks;if(!n)throw Error("Cannot delete a model without a primary key");if(await r?.beforeDelete?.(this),Cn(this._definition)){let s=on();await e.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${t} = ?`,[s,n]),this._attributes[Qt]=s}else await e.run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[n]);return await r?.afterDelete?.(this),!0}async restore(){if(!Cn(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let e=this._definition.primaryKey||"id",t=this._attributes[e];if(!t)throw Error("Cannot restore a model without a primary key");return await De().run(`UPDATE ${this._definition.table} SET ${Qt} = ? WHERE ${e} = ?`,[null,t]),this._attributes[Qt]=null,this._original=null,this}trashed(){return this._attributes[Qt]!=null}async refresh(){let e=De(),t=this._definition.primaryKey||"id",n=this._attributes[t];if(!n)throw Error("Cannot refresh a model without a primary key");let r=await e.get(`SELECT * FROM ${this._definition.table} WHERE ${t} = ?`,[n]);if(!r)return null;return this._attributes=r,this._original=null,this}replicate(){let e=this._definition.primaryKey||"id",t={...this._attributes};return delete t[e],delete t.uuid,delete t.created_at,delete t.updated_at,new Xe(this._definition,t)}toArray(){let e={...this._attributes};for(let[t,n]of Object.entries(this._relations))if(Array.isArray(n))e[t]=n.map((r)=>r.toArray());else if(n)e[t]=n.toArray();else e[t]=null;return e}toJSON(){let e=new Set;for(let[n,r]of Object.entries(this._definition.attributes))if(r.hidden)e.add(n);let t={};for(let[n,r]of Object.entries(this._attributes))if(!e.has(n))t[n]=r;for(let[n,r]of Object.entries(this._relations))if(Array.isArray(r))t[n]=r.map((s)=>s.toJSON());else if(r)t[n]=r.toJSON();else t[n]=null;return t}}function gt(e){return $e(e)}function $e(e){let t=Rl.get(e);if(t!==void 0)return t;return t=e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Rl.set(e,t),t}function rn(e){let t=kl.get(e);if(t!==void 0)return t;return t=di(e),kl.set(e,t),t}function Cl(e,t){let n=e[t];if(!n)return[];if(Array.isArray(n))return n.map((r)=>typeof r==="string"?r:String(r?.model??"")).filter(Boolean);if(typeof n==="object")return Object.keys(n);if(typeof n==="string")return[n];return[]}function og(e,t){let n=e.name??e.table??"model",s=ig.filter((o)=>Cl(e,o).some((l)=>l.toLowerCase()===t.toLowerCase())).filter((o)=>!gs.includes(o));if(s.length>0)return`[orm] '${n}' declares '${t}' as ${s.join("/")}, which eager loading does not support yet. Supported kinds: ${gs.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let i=gs.flatMap((o)=>Cl(e,o));return i.length>0?`[orm] '${n}' has no relation '${t}'. Available: ${i.join(", ")}.`:`[orm] '${n}' has no relation '${t}' \u2014 it declares no relations at all.`}function Bl(e,t){let{name:n,table:r}=e,s=e.primaryKey||"id";function i(R){if(!R)return null;if(Array.isArray(R)){for(let y of R){let b=typeof y==="string"?y:y?.model||"";if(b&&b.toLowerCase()===t.toLowerCase())return b}return null}if(typeof R==="object"){for(let[y,b]of Object.entries(R))if(y===t||y.toLowerCase()===t.toLowerCase())return typeof b==="string"?b:b?.model||b?.target||y}return null}function o(){let R=e.belongsTo;if(!R)return null;let y=t.toLowerCase(),b=(g)=>{if(typeof g==="string")return{model:g};if(g&&typeof g==="object"&&typeof g.model==="string")return{model:g.model,foreignKey:g.foreignKey};return null};if(Array.isArray(R)){for(let g of R){let p=b(g);if(p&&p.model.toLowerCase()===y)return p}return null}if(typeof R==="object"){for(let[g,p]of Object.entries(R))if(g===t||g.toLowerCase()===y)return b(p)}return null}function l(){let R=e.belongsToMany;if(!R)return null;if(Array.isArray(R)){for(let y of R)if(typeof y==="string"){if(y.toLowerCase()===t.toLowerCase())return{entry:y}}else if(y&&typeof y==="object"&&y.model){if(y.model.toLowerCase()===t.toLowerCase())return{entry:y}}return null}if(typeof R==="object"){for(let[y,b]of Object.entries(R))if(y===t||y.toLowerCase()===t.toLowerCase())return{entry:b}}return null}let a=i(e.hasMany);if(a){let y=et(a)?.getTable?.()||rn(a),b=$e(n)+"_id";return{type:"hasMany",relatedModelName:a,relatedTable:y,foreignKey:b,localKey:s}}let c=i(e.hasOne);if(c){let y=et(c)?.getTable?.()||rn(c),b=$e(n)+"_id";return{type:"hasOne",relatedModelName:c,relatedTable:y,foreignKey:b,localKey:s}}let u=o();if(u){let R=u.model,y=et(R),b=y?.getTable?.()||rn(R),g=y?.getDefinition?.()?.primaryKey||"id",p=u.foreignKey||`${$e(R)}_id`;return{type:"belongsTo",relatedModelName:R,relatedTable:b,foreignKey:p,localKey:g}}let m=l();if(m){let R=typeof m.entry==="object",y=R?m.entry.model:m.entry,g=et(y)?.getTable?.()||rn(y),p=R?m.entry:null,E,D;if(p?.table)E=p.table;else if(p?.through){D=p.through;let v=et(p.through);if(!v)throw Error(`[orm] belongsToMany relation '${t}' on '${n}' references unknown through model '${p.through}'. Make sure '${p.through}' is registered.`);E=v.getTable?.()||v.getDefinition?.()?.table||rn(p.through)}else{let v=Zn(r),x=Zn(g);E=[v,x].sort().join("_")}let J=p?.foreignKey||`${Zn(r)}_id`,B=p?.relatedKey||`${Zn(g)}_id`,W=[];if(p?.pivot?.columns)for(let v of Object.keys(p.pivot.columns))W.push(v);if(D){let v=et(D),x=v?.getDefinition?.()||v?.definition,C=x?.attributes??{},k=x?.primaryKey??"id";for(let P of Object.keys(C)){if(P===J||P===B||P===k)continue;if(!W.includes(P))W.push(P)}}return{type:"belongsToMany",relatedModelName:y,relatedTable:g,foreignKey:J,localKey:s,pivotTable:E,pivotFkParent:J,pivotFkRelated:B,pivotColumns:W,pivotModelName:D,pivotTimestamps:Boolean(p?.pivot?.timestamps)}}let h=(R,y)=>{if(!R||typeof R!=="object"||Array.isArray(R))return null;let b=R[t]??R[Object.keys(R).find((x)=>x.toLowerCase()===t.toLowerCase())??""];if(!b||typeof b!=="object")return null;let{through:g,target:p}=b;if(!g||!p)return null;let E=et(g),D=E?.getDefinition?.()||E?.definition,J=E?.getTable?.()||D?.table||rn(g),B=D?.primaryKey||"id",v=et(p)?.getTable?.()||rn(p);return{type:y,relatedModelName:p,relatedTable:v,foreignKey:`${$e(n)}_id`,localKey:s,throughTable:J,throughForeignKey:`${$e(n)}_id`,throughLocalKey:B,targetForeignKey:`${Zn(J)}_id`}},w=h(e.hasManyThrough,"hasManyThrough");if(w)return w;let N=h(e.hasOneThrough,"hasOneThrough");if(N)return N;return null}function ki(e,t){let n=new Set;for(let r of e){let s=r.get(t);if(s!=null)n.add(s)}return[...n]}function Zn(e){return qt(_.relations?.singularizeStrategy)(e)}class Pl{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(e,t,n,r){this._parent=e,this._parentDef=t,this._resolved=n,this._relatedDef=r}get parentId(){let e=this._parentDef.primaryKey||"id";return this._parent.get(e)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(e,t,n){if(n===void 0)this._wheres.push({sql:`${this.relatedTable}.${e} = ?`,params:[t]});else this._wheres.push({sql:`${this.relatedTable}.${e} ${String(t)} ?`,params:[n]});return this}wherePivot(e,t,n){if(n===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${e} = ?`,params:[t]});else this._pivotWheres.push({sql:`${this.pivotTable}.${e} ${String(t)} ?`,params:[n]});return this}wherePivotIn(e,t){if(!t.length)return this;let n=t.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${e} IN (${n})`,params:[...t]}),this}wherePivotNotIn(e,t){if(!t.length)return this;let n=t.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${e} NOT IN (${n})`,params:[...t]}),this}wherePivotNull(e){return this._pivotWheres.push({sql:`${this.pivotTable}.${e} IS NULL`,params:[]}),this}wherePivotNotNull(e){return this._pivotWheres.push({sql:`${this.pivotTable}.${e} IS NOT NULL`,params:[]}),this}orderBy(e,t="asc"){if(Al(e,"orderBy(column)"),t!=="asc"&&t!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${t}'`);return this._orderBy.push(`${e} ${t.toUpperCase()}`),this}limit(e){if(!Number.isFinite(e)||e<0||!Number.isInteger(e))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${e}`);return this._limit=e,this}offset(e){if(!Number.isFinite(e)||e<0||!Number.isInteger(e))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${e}`);return this._offset=e,this}relatedSelectColumns(){let e=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),t=this._relatedDef.traits;if(t?.useTimestamps||t?.timestampable)e.add("created_at"),e.add("updated_at");if(t?.useSoftDeletes||t?.softDeletable)e.add("deleted_at");if(t?.useUuid)e.add("uuid");return[...e]}buildSelect(){let e=[],n=`SELECT ${this.relatedSelectColumns().map((r)=>`${this.relatedTable}.${r} AS ${Ri}${r}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;n+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,n+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,e.push(this.parentId);for(let r of this._pivotWheres)n+=` AND ${r.sql}`,e.push(...r.params);for(let r of this._wheres)n+=` AND ${r.sql}`,e.push(...r.params);if(this._orderBy.length>0)n+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)n+=` LIMIT ${this._limit}`;if(this._offset!==void 0)n+=` OFFSET ${this._offset}`;return{sql:n,params:e}}hydrateRows(e){let t=this.fkParent,n=this.fkRelated;return e.map((r)=>{let s={},i={};for(let[l,a]of Object.entries(r))if(l.startsWith(Ri))s[l.slice(Ri.length)]=a;else if(l!==t&&l!==n)i[l]=a;let o=new Xe(this._relatedDef,s);return o.pivot=i,o})}async get(){let e=De(),{sql:t,params:n}=this.buildSelect(),r=await e.all(t,n);return this.hydrateRows(r)}async first(){return this._limit=1,(await this.get())[0]}async count(){let e=De(),t=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,n=[this.parentId];for(let s of this._pivotWheres)t+=` AND ${s.sql}`,n.push(...s.params);let r=await e.get(t,n);return Number(r?.count??0)}async exists(){return await this.count()>0}now(){return on()}async attach(e,t={}){let n=De(),r=Array.isArray(e)?e:[e];if(r.length===0)return 0;let s=this._resolved.pivotTimestamps?this.now():null,i=0;for(let o of r){let l={[this.fkParent]:this.parentId,[this.fkRelated]:o,...t};if(s){if(l.created_at===void 0)l.created_at=s;if(l.updated_at===void 0)l.updated_at=s}let a=Object.keys(l),c=a.map(()=>"?").join(", "),u=`INSERT INTO ${this.pivotTable} (${a.join(", ")}) VALUES (${c})`,m=a.map((h)=>l[h]);await n.run(u,m),i++}return i}async detach(e){let t=De(),n=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,r=[this.parentId];if(e!==void 0&&e!==null){let s=Array.isArray(e)?e:[e];if(s.length===0)return 0;let i=s.map(()=>"?").join(", ");n+=` AND ${this.fkRelated} IN (${i})`,r.push(...s)}return(await t.run(n,r)).changes}async updateExistingPivot(e,t){let n=De(),r={...t};if(this._resolved.pivotTimestamps&&r.updated_at===void 0)r.updated_at=this.now();let s=Object.keys(r);if(s.length===0)return 0;let i=s.map((a)=>`${a} = ?`).join(", "),o=`UPDATE ${this.pivotTable} SET ${i} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,l=[...s.map((a)=>r[a]),this.parentId,e];return(await n.run(o,l)).changes}async sync(e){let t=De(),n=new Map;for(let c of e)if(c!=null&&typeof c==="object"&&"id"in c){let{id:u,...m}=c;n.set(u,m)}else n.set(c,{});let r=await t.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),s=new Set(r.map((c)=>c[this.fkRelated])),i=[],o=[],l=[],a=[...s].filter((c)=>!n.has(c));if(a.length>0)await this.detach(a),o.push(...a);for(let[c,u]of n)if(!s.has(c))await this.attach(c,u),i.push(c);else if(Object.keys(u).length>0)await this.updateExistingPivot(c,u),l.push(c);return{attached:i,detached:o,updated:l}}async toggle(e){let t=De(),n=Array.isArray(e)?e:[e];if(n.length===0)return{attached:[],detached:[]};let r=n.map(()=>"?").join(", "),s=await t.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${r})`,[this.parentId,...n]),i=new Set(s.map((a)=>a[this.fkRelated])),o=n.filter((a)=>!i.has(a)),l=n.filter((a)=>i.has(a));if(o.length>0)await this.attach(o);if(l.length>0)await this.detach(l);return{attached:o,detached:l}}}class de{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(e){this._definition=e}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(e,t,n){if(n===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:n,boolean:"and"});return this}orWhere(e,t,n){if(n===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"or"});else this._wheres.push({column:e,operator:t,value:n,boolean:"or"});return this}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}orWhereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"or"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}orWhereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"or"}),this}whereNull(e){return Nt(e,"whereNull(column)"),this._wheres.push({column:e,operator:"=",value:null,boolean:"and"}),this}orWhereNull(e){return Nt(e,"orWhereNull(column)"),this._wheres.push({column:e,operator:"=",value:null,boolean:"or"}),this}whereNotNull(e){return Nt(e,"whereNotNull(column)"),this._wheres.push({column:e,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(e){return Nt(e,"orWhereNotNull(column)"),this._wheres.push({column:e,operator:"!=",value:null,boolean:"or"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orWhereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"or"}),this}whereNotLike(e,t){return this._wheres.push({column:e,operator:"not like",value:t,boolean:"and"}),this}orWhereNotLike(e,t){return this._wheres.push({column:e,operator:"not like",value:t,boolean:"or"}),this}whereRaw(e,...t){return this._wheres.push({raw:e,rawParams:t,boolean:"and"}),this}orWhereRaw(e,...t){return this._wheres.push({raw:e,rawParams:t,boolean:"or"}),this}whereGroup(e){return this._addGroup("and",e)}orWhereGroup(e){return this._addGroup("or",e)}_addGroup(e,t){let n=new de(this._definition);if(t(n),n._wheres.length===0)return this;let r=[],s=n.buildWhereClauses(r);if(!s)return this;return this._wheres.push({raw:`(${s})`,rawParams:r,boolean:e}),this}whereBetween(e,t){return Nt(e,"whereBetween(column)"),this._wheres.push({column:e,operator:">=",value:t[0],boolean:"and"}),this._wheres.push({column:e,operator:"<=",value:t[1],boolean:"and"}),this}whereNotBetween(e,t){Nt(e,"whereNotBetween(column)");let n=gt(e);return this._wheres.push({raw:`(${n} < ? OR ${n} > ?)`,rawParams:[t[0],t[1]],boolean:"and"}),this}when(e,t){if(e)return t(this);return this}orderBy(e,t="asc"){if(Al(e,"orderBy(column)"),t!=="asc"&&t!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${t}'`);return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){for(let t of e)if(!this._withRelations.includes(t))this._withRelations.push(t);return this}getWithRelations(){return this._withRelations}buildWhereClauses(e){let t=[];for(let n of this._wheres){let r;if(n.raw){if(r=n.raw,n.rawParams&&n.rawParams.length>0)e.push(...n.rawParams)}else if(n.value===null){let s=gt(n.column);r=n.operator==="="?`${s} IS NULL`:`${s} IS NOT NULL`}else if(n.operator==="in"||n.operator==="not in"){let s=n.value;r=Ge(gt(n.column),s,n.operator==="not in",s.map(()=>"?").join(", ")),e.push(...s)}else r=`${gt(n.column)} ${n.operator} ?`,e.push(n.value);t.push({conn:n.boolean==="or"?"OR":"AND",sql:r})}return tn(t)}softDeleteClause(){if(this._trashed==="include"||!Cn(this._definition))return"";return this._trashed==="only"?`${Qt} IS NOT NULL`:`${Qt} IS NULL`}assertNoUnappliedClauses(e){let t=[];if(this._limit!==void 0)t.push("limit()");if(this._offset!==void 0)t.push("offset()");if(this._orderBy.length>0)t.push("orderBy()");if(t.length>0)throw TypeError(`[orm] ${e}() cannot apply ${t.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(e){let t=this._wheres.length>0?this.buildWhereClauses(e):"",n=this.softDeleteClause();if(t&&n)return`(${t}) AND ${n}`;return t||n}buildQuery(){let e=[],n=`SELECT ${this._select.map((s)=>s==="*"?s:gt(s)).join(", ")} FROM ${this._definition.table}`,r=this.composeWhere(e);if(r)n+=` WHERE ${r}`;if(this._orderBy.length>0)n+=` ORDER BY ${this._orderBy.map((s)=>`${gt(s.column)} ${s.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)n+=` LIMIT ${this._limit}`;if(this._offset!==void 0)n+=` OFFSET ${this._offset}`;return{sql:n,params:e}}toSql(){return this.buildQuery()}async eagerLoadRelations(e){if(e.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((t)=>this.eagerLoadRelation(t,e)))}async eagerLoadRelation(e,t){let n=De(),r=this._definition.primaryKey||"id",s=`${this._definition.name}:${e}`,i=kn.get(s);if(i===void 0){if(i=Bl(this._definition,e),kn.size>=sg)kn.clear();kn.set(s,i)}if(!i)throw Error(og(this._definition,e));if(i.type==="hasMany"||i.type==="hasOne"){let o=ki(t,r);if(o.length===0)return;let l=o.map(()=>"?").join(", "),a=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${i.foreignKey} IN (${l})`,o),c=et(i.relatedModelName),u=c?.getDefinition?.()||c?.definition||this._definition;if(i.type==="hasMany"){let m=new Map;for(let h of a){let w=h[i.foreignKey];if(!m.has(w))m.set(w,[]);m.get(w).push(h)}for(let h of t){let w=m.get(h.get(r))||[];h.setRelation(e,w.map((N)=>new Xe(u,N)))}}else{let m=new Map;for(let h of a){let w=h[i.foreignKey];if(!m.has(w))m.set(w,h)}for(let h of t){let w=m.get(h.get(r));h.setRelation(e,w?new Xe(u,w):null)}}}if(i.type==="belongsTo"){let o=new Set;for(let w of t){let N=w._attributes[i.foreignKey];if(N!=null)o.add(N)}let l=[...o];if(l.length===0)return;let a=l.map(()=>"?").join(", "),c=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${i.localKey} IN (${a})`,l),u=et(i.relatedModelName),m=u?.getDefinition?.()||u?.definition||this._definition,h=new Map;for(let w of c)h.set(w[i.localKey],w);for(let w of t){let N=w._attributes[i.foreignKey],R=h.get(N);w.setRelation(e,R?new Xe(m,R):null)}}if(i.type==="belongsToMany"){let o=ki(t,r);if(o.length===0)return;if(!i.pivotTable||!i.pivotFkParent||!i.pivotFkRelated)return;let l=o.map(()=>"?").join(", "),a=await n.all(`SELECT * FROM ${i.pivotTable} WHERE ${i.pivotFkParent} IN (${l})`,o);if(a.length===0){for(let g of t)g.setRelation(e,[]);return}let c=new Set;for(let g of a){let p=g[i.pivotFkRelated];if(p!=null)c.add(p)}let u=[...c],m=et(i.relatedModelName),h=m?.getDefinition?.()||m?.definition||this._definition,w=h?.primaryKey||"id",N=[];if(u.length>0){let g=u.map(()=>"?").join(", ");N=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${w} IN (${g})`,u)}let R=new Map;for(let g of N)R.set(g[w],g);let y=new Map;for(let g of a){let p=g[i.pivotFkParent];if(!y.has(p))y.set(p,[]);y.get(p).push(g)}let b=new Set([i.pivotFkParent,i.pivotFkRelated]);for(let g of t){let p=g.get(r),D=(y.get(p)||[]).map((J)=>{let B=R.get(J[i.pivotFkRelated]);if(!B)return null;let W=new Xe(h,B),v={};for(let[x,C]of Object.entries(J))if(!b.has(x))v[x]=C;return W.pivot=v,W}).filter((J)=>J!==null);g.setRelation(e,D)}}if(i.type==="hasManyThrough"||i.type==="hasOneThrough"){let o=ki(t,r);if(o.length===0)return;let l=i.throughLocalKey||"id",a=o.map(()=>"?").join(", "),c=await n.all(`SELECT ${l}, ${i.throughForeignKey} FROM ${i.throughTable} WHERE ${i.throughForeignKey} IN (${a})`,o);if(c.length===0){for(let b of t)b.setRelation(e,i.type==="hasManyThrough"?[]:null);return}let u=new Map;for(let b of c)u.set(b[l],b[i.throughForeignKey]);let m=[...new Set(c.map((b)=>b[l]))],h=m.map(()=>"?").join(", "),w=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${i.targetForeignKey} IN (${h})`,m),N=et(i.relatedModelName),R=N?.getDefinition?.()||N?.definition||this._definition,y=new Map;for(let b of w){let g=u.get(b[i.targetForeignKey]);if(g==null)continue;if(!y.has(g))y.set(g,[]);y.get(g).push(new Xe(R,b))}for(let b of t){let g=y.get(b.get(r))||[];b.setRelation(e,i.type==="hasManyThrough"?g:g[0]??null)}}}async get(){let e=De(),{sql:t,params:n}=this.buildQuery(),s=(await e.all(t,n)).map((i)=>new Xe(this._definition,i));if(this._withRelations.length>0)await this.eagerLoadRelations(s);return s}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let e=await this.first();if(!e)throw Error(`No ${this._definition.name} found`);return e}async last(){let e=this._definition.primaryKey||"id";return this._orderBy=[{column:e,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let e=De(),t=[],n=`SELECT COUNT(*) as count FROM ${this._definition.table}`,r=this.composeWhere(t);if(r)n+=` WHERE ${r}`;let s=await e.get(n,t);return Number(s?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let e=await this.get();if(e.length===0)throw Error(`No ${this._definition.name} found`);if(e.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return e[0]}async increment(e,t=1){Nt(e,"increment(column)"),this.assertNoUnappliedClauses("increment");let n=De(),r=[t],s=gt(e),i=`UPDATE ${this._definition.table} SET ${s} = ${s} + ?`;if(an(this._definition))i+=", updated_at = ?",r.push(on());let o=this.composeWhere(r);if(o)i+=` WHERE ${o}`;return(await n.run(i,r)).changes}decrement(e,t=1){return this.increment(e,-t)}async chunk(e,t){let n=0;while(!0){let r=new de(this._definition);r._wheres=[...this._wheres],r._orderBy=[...this._orderBy],r._select=[...this._select],r._withRelations=[...this._withRelations],r._trashed=this._trashed,r._limit=e,r._offset=n*e;let s=await r.get();if(s.length===0)break;if(await t(s)===!1)break;if(s.length<e)break;n++}}async paginate(e=1,t=15){if(typeof e==="object"&&e!==null){let i=e;t=i.perPage??15,e=i.page??1}let n=await this.count(),r=Math.ceil(n/t);this._limit=t,this._offset=(e-1)*t;let s=await this.get();return{data:s,total:n,page:e,perPage:t,lastPage:r,hasMorePages:e<r,isEmpty:s.length===0,from:s.length>0?(e-1)*t+1:null,to:s.length>0?(e-1)*t+s.length:null,meta:{perPage:t,page:e,total:n,lastPage:r}}}async pluck(e){Nt(e,"pluck(column)");let t=De(),n=[],r=gt(e),s=`SELECT ${r} FROM ${this._definition.table}`,i=this.composeWhere(n);if(i)s+=` WHERE ${i}`;if(this._orderBy.length>0)s+=` ORDER BY ${this._orderBy.map((l)=>`${gt(l.column)} ${l.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)s+=` LIMIT ${this._limit}`;if(this._offset!==void 0)s+=` OFFSET ${this._offset}`;return(await t.all(s,n)).map((l)=>l[r])}async aggregate(e,t){Nt(t,`${e}(column)`);let n=De(),r=[],s=`SELECT ${e}(${gt(t)}) as v FROM ${this._definition.table}`,i=this.composeWhere(r);if(i)s+=` WHERE ${i}`;let l=(await n.get(s,r))?.v;if(l==null)return null;if(typeof l==="string"){let a=Number(l);return l.trim()!==""&&!Number.isNaN(a)?a:l}return l}max(e){return this.aggregate("MAX",e)}min(e){return this.aggregate("MIN",e)}async avg(e){return Number(await this.aggregate("AVG",e)??0)||0}async sum(e){return Number(await this.aggregate("SUM",e)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let e=De(),t=[],n=`DELETE FROM ${this._definition.table}`,r=this.composeWhere(t);if(r)n+=` WHERE ${r}`;return(await e.run(n,t)).changes}async update(e){this.assertNoUnappliedClauses("update");let t=De(),n=Object.entries(e),r=n.map(([l])=>`${gt(l)} = ?`).join(", "),s=n.map(([,l])=>l);if(an(this._definition))s.push(on());let i=`UPDATE ${this._definition.table} SET ${r}${an(this._definition)?", updated_at = ?":""}`,o=this.composeWhere(s);if(o)i+=` WHERE ${o}`;return(await t.run(i,s)).changes}}function ag(e){let t={query:()=>new de(e),where(n,r,s){return new de(e).where(n,r,s)},orWhere(n,r,s){return new de(e).orWhere(n,r,s)},whereIn(n,r){return new de(e).whereIn(n,r)},whereNotIn(n,r){return new de(e).whereNotIn(n,r)},whereNull(n){return new de(e).whereNull(n)},whereNotNull(n){return new de(e).whereNotNull(n)},whereLike(n,r){return new de(e).whereLike(n,r)},orderBy(n,r="asc"){return new de(e).orderBy(n,r)},orderByDesc(n){return new de(e).orderByDesc(n)},select(...n){return new de(e).select(...n)},with(...n){return new de(e).with(...n)},limit:(n)=>new de(e).limit(n),take:(n)=>new de(e).take(n),skip:(n)=>new de(e).skip(n),withTrashed:()=>new de(e).withTrashed(),onlyTrashed:()=>new de(e).onlyTrashed(),async find(n){let r=De(),s=e.primaryKey||"id",i=Cn(e)?` AND ${Qt} IS NULL`:"",o=await r.get(`SELECT * FROM ${e.table} WHERE ${s} = ?${i}`,[n]);return o?new Xe(e,o):void 0},async findOrFail(n){let r=await t.find(n);if(!r)throw Error(`${e.name} with id ${n} not found`);return r},async findMany(n){let r=De(),s=e.primaryKey||"id",i=Cn(e)?` AND ${Qt} IS NULL`:"";return(await r.all(`SELECT * FROM ${e.table} WHERE ${s} IN (${n.map(()=>"?").join(", ")})${i}`,n)).map((l)=>new Xe(e,l))},all:()=>new de(e).get(),first:()=>new de(e).first(),firstOrFail:()=>new de(e).firstOrFail(),last:()=>new de(e).last(),count:()=>new de(e).count(),exists:()=>new de(e).exists(),doesntExist:()=>new de(e).doesntExist(),paginate:(n,r)=>new de(e).paginate(n,r),whereBetween(n,r){return new de(e).whereBetween(n,r)},whereNotBetween(n,r){return new de(e).whereNotBetween(n,r)},async create(n){let r=new Xe(e,n);return await r.save(),r},async createMany(n){let r=[];for(let s of n)r.push(await this.create(s));return r},async updateOrCreate(n,r){let s=new de(e);for(let[o,l]of Object.entries(n))s=s.where(o,l);let i=await s.first();if(i)return await i.update(r),i;return this.create({...n,...r})},async firstOrCreate(n,r){let s=new de(e);for(let[o,l]of Object.entries(n))s=s.where(o,l);return await s.first()||this.create({...n,...r})},async destroy(n){let r=De(),s=e.primaryKey||"id";return(await r.run(`DELETE FROM ${e.table} WHERE ${s} = ?`,[n])).changes>0},remove(n){return this.destroy(n)},async truncate(){await De().run(`DELETE FROM ${e.table}`,[])},getDefinition:()=>e,getTable:()=>e.table,make(n={}){return new Xe(e,n)},latest:(n="created_at")=>new de(e).orderByDesc(n),oldest:(n="created_at")=>new de(e).orderBy(n,"asc"),max:(n)=>new de(e).max(n),min:(n)=>new de(e).min(n),avg:(n)=>new de(e).avg(n),sum:(n)=>new de(e).sum(n),pluck(n){return new de(e).pluck(n)}};return new Proxy(t,{get(n,r){if(typeof r==="string"&&r.startsWith("where")&&r.length>5){let s=r.slice(5),i=s.charAt(0).toLowerCase()+s.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(o)=>new de(e).where(i,o)}return Reflect.get(n,r)}})}function _l(e){let t=ag(e);if(e?.name)Zm(e.name,t);return t}async function cw(e){let t=De(),n=$e(e.primaryKey||"id"),r=[],s=new Set([n]);if(r.push(e.autoIncrement!==!1?`${n} INTEGER PRIMARY KEY AUTOINCREMENT`:`${n} INTEGER PRIMARY KEY`),e.traits?.useUuid)r.push("uuid TEXT UNIQUE"),s.add("uuid");for(let[i,o]of Object.entries(e.attributes)){let l=$e(i);if(s.has(l))continue;s.add(l);let a=Ba(o.type),c=Zr(a);if(l.endsWith("_id")&&(a===void 0||$n(a)))c="INTEGER";let u=`${l} ${c}`;if(o.unique)u+=" UNIQUE";if(typeof o.foreignKey==="object"&&o.foreignKey!==null){let m=o.foreignKey;if(u+=` REFERENCES ${m.table}(${m.column??"id"})`,m.onDelete)u+=` ON DELETE ${m.onDelete.toUpperCase()}`;if(m.onUpdate)u+=` ON UPDATE ${m.onUpdate.toUpperCase()}`}r.push(u)}for(let i of Rn(e.belongsTo)){let o=i.foreignKey??`${$e(i.model)}_id`;if(s.has(o))continue;s.add(o),r.push(`${o} INTEGER`)}if(an(e))for(let i of["created_at","updated_at"]){if(s.has(i))continue;s.add(i),r.push(`${i} TEXT`)}if(Cn(e)&&!s.has("deleted_at"))s.add("deleted_at"),r.push("deleted_at TEXT");await t.run(`CREATE TABLE IF NOT EXISTS ${e.table} (${r.join(", ")})`,[])}async function uw(e,t,n){let r=De(),s=e.traits?.useSeeder,i=t??(typeof s==="object"&&s?s.count:10);if(!n)try{let o=await import("./chunk-bbz0pmj9.js");n=Dl(o.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let o=0;o<i;o++){let l={};for(let[c,u]of Object.entries(e.attributes))if(u.factory)l[$e(c)]=u.factory(n);if(an(e)){let c=on();l.created_at=c,l.updated_at=c}if(e.traits?.useUuid)l.uuid=crypto.randomUUID();let a=Object.keys(l);await r.run(`INSERT INTO ${e.table} (${a.join(", ")}) VALUES (${a.map(()=>"?").join(", ")})`,Object.values(l))}}var vl,fs=null,Ai,ms,eg=500,sn=null,Mt=null,er=null,Ei=null,xi=null,Qt="deleted_at",Ri="__btm_rel__",xl,Rl,kl,kn,sg=1000,gs,ig;var Ni=ut(()=>{ui();Me();Kt();Hr();$i();ds();jt();ns();vl=/^[A-Z_][A-Z0-9_]*$/i;Ai=new Map;ms=new Map;xl=new WeakMap;Rl=new Map,kl=new Map,kn=new Map;gs=["hasMany","hasOne","belongsTo","belongsToMany"],ig=[...gs,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var Il={};lg(Il,{clearModelRegistry:()=>Ul,defineModel:()=>Ql,getAllModels:()=>ql,getModel:()=>Fl,getModelRegistry:()=>jl,hasModel:()=>Wl,registerBrowserModels:()=>ug,registerModel:()=>Mi});function Fl(e){return vn.get(e)}function ql(){return[...vn.values()]}function jl(){return Object.fromEntries(vn)}function Wl(e){return vn.has(e)}function Ul(){vn.clear(),Nl()}function Mi(e,t){return vn.set(e,t),t}function cg(){return typeof window<"u"&&typeof document<"u"}function Ql(e){let t;if(cg())t=Ll(e);else{let n=_l(e);t=Object.assign(n,{definition:e,getDefinition:()=>e,getTable:()=>e.table,getName:()=>e.name})}return Mi(e.name,t),t}function ug(e){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...e}}var vn;var tr=ut(()=>{Kl();Ni();vn=new Map});Me();Kt();import{existsSync as Pt,mkdirSync as $c,mkdtempSync as Ig,readdirSync as Ec,readFileSync as sr,rmSync as xc,unlinkSync as qi,writeFileSync as Rc}from"fs";import{tmpdir as Lg}from"os";import{join as tt}from"path";import ji from"process";Me();function yf(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(36).padStart(7,"0").slice(-7)}function hf(e,t=63){if(e.length<=t)return e;let n=`_${yf(e)}`;return e.slice(0,t-n.length)+n}function ft(e,t){let n=`${e}_`,r=t.startsWith(n)?t:`${n}${t}`;return hf(r)}class Ie{quoteIdentifier(e){return`\`${e.replace(/`/g,"``")}\``}getColumnType(e){switch(e.type){case"string":return`varchar(${e.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(e.enumValues&&e.enumValues.length>0)return`ENUM(${e.enumValues.map((n)=>`'${n.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(e){return this.getColumnType(e)}getAutoIncrementClause(e){if(e.isPrimaryKey&&(e.type==="integer"||e.type==="bigint"))return"auto_increment";return""}getDefaultValue(e){if(!e.hasDefault||e.defaultValue===void 0)return"";let t=e.defaultValue;if(typeof t==="string"){let n=t.toUpperCase();if(n==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(n))return`default ${n}`;let s=`'${t.replace(/'/g,"''")}'`;if(e.type==="text"||e.type==="json"||e.type==="enum"&&!e.enumValues?.length)return`default (${s})`;return`default ${s}`}else if(typeof t==="number"||typeof t==="bigint")return`default ${t}`;else if(typeof t==="boolean")return`default ${t?1:0}`;else if(t instanceof Date)return`default '${t.toISOString()}'`;return""}createEnumType(e,t){return""}foreignKeyClauses(e){return e.columns.filter((t)=>t.references).map((t)=>{let n=t.references,r=`${e.table}_${t.name}_fk`,s=`CONSTRAINT ${this.quoteIdentifier(r)} FOREIGN KEY (${this.quoteIdentifier(t.name)}) REFERENCES ${this.quoteIdentifier(n.table)}(${this.quoteIdentifier(n.column)})`;if(n.onDelete)s+=` ON DELETE ${n.onDelete.toUpperCase()}`;if(n.onUpdate)s+=` ON UPDATE ${n.onUpdate.toUpperCase()}`;return s})}createTable(e){let t=[...e.columns.map((n)=>this.renderColumn(n)),...this.foreignKeyClauses(e)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(e.table)} (
61
+ `;return n}}function Ud(e,t,n={}){return fa(e,t,n,new WeakMap)}function fa(e,t,n,r){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=n;if(t===null||t===void 0)return i?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return ma(e,t,s,r);if(!st(t)||!st(e))return t;return Hd(e,t,n,r)}function ma(e,t,n,r){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(n){case"replace":return t;case"concat":return Qd(e,t);case"smart":return Vd(e,t,r);default:return t}return t}function Qd(e,t){let n=[...t];for(let r of e)if(!n.some((s)=>Zs(s,r)))n.push(r);return n}function Vd(e,t,n){if(t.length===0)return e;if(e.length===0)return t;if(st(t[0])&&st(e[0]))return Jd(e,t,n);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let s of e)if(!r.includes(s))r.push(s);return r}return t}function Jd(e,t,n){let r=[...t];for(let s of e){if(!st(s)){r.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let l of i)if(l in s){if(r.find((c)=>st(c)&&(l in c)&&c[l]===s[l])){o=!0;break}}if(!o)r.push(s)}return r}function Hd(e,t,n,r){let s=t;if(st(s)&&r.has(s))return r.get(s);let i={...e};if(st(s))r.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let l=s[o],a=i[o];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){i[o]=l;continue}if(st(l)&&st(a))i[o]=fa(a,l,n,r);else if(Array.isArray(l)||Array.isArray(a))i[o]=ma(a,l,n.arrayMergeMode||"smart",r);else i[o]=l}return i}function ga(e,t,n="replace"){return Ud(e,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Zs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Zs(e[n],t[n]))return!1;return!0}if(st(e)&&st(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Zs(e[s],t[s]))return!1}return!0}return!1}function st(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ya{extensions=_o;async loadFromPath(e,t,n={}){let{arrayStrategy:r="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:l=!1}=n;if(s){let c=kr.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let a=async()=>{if(!Dr(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),m=u.default||u,h="default"in u,w=Object.keys(u).length>0;if(!h&&!w)throw new Kr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new Kr(e,Error("Configuration must export a valid object"),"unknown");let y={config:ga(t,m,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)kr.setWithFileCheck("file",y,e,i);return y}catch(c){throw c instanceof Error?Yt.configLoad(e,c):Yt.configLoad(e,Error(String(c)))}};if(o)return ei.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,n={}){for(let r of e)try{let s=await this.loadFromPath(r,t,n);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(n.verbose)console.warn(`Failed to load config from ${r}:`,s)}return null}generateConfigPaths(e,t,n){return jc({name:e,directory:t,alias:n})}generateNamePatterns(e,t){return Io({name:e,alias:t})}checkFileAccess(e){return Wd(async()=>Dr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,n){let r=[];if(!Dr(e))return r;if(t||n){let s=this.generateNamePatterns(t||"",n);for(let i of s)for(let o of this.extensions){let l=Oo(e,`${i}${o}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let l=Oo(e,o);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(e){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((n)=>n.test(e))}async validateConfigFile(e){let t=[];try{if(!Dr(e))return t.push("Configuration file does not exist"),t;let n=await import(e),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let n=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let s=await this.loadFromPath(r,{},t);if(s)n.set(r,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${r}:`,s)}})),n}}class ha{async validateConfiguration(e,t,n={}){let{stopOnFirstError:r=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:l=!0,verbose:a=!1}=n,c=async()=>{let u=[],m=[],h={stopOnFirstError:r,validateRequired:s,validateTypes:i,customRules:o,trackPerformance:l,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(w){return u.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:u,warnings:m}}};if(l)return await ei.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,n){try{if(!zd(t))throw new Fr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),s=r.default||r;if(Array.isArray(s))return this.validateWithRules(e,s,n);else return this.validateWithJSONSchema(e,s,n)}catch(r){throw new Fr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,n){let r=[],s=[];return this.validateObjectAgainstSchema(e,t,"",r,s,n),{isValid:r.length===0,errors:r,warnings:s}}validateObjectAgainstSchema(e,t,n,r,s,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=n?`${n}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,r,s,i),i.stopOnFirstError&&r.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[l,a]of Object.entries(t.properties))if(l in o){let c=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],a,c,r,s,i),i.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!l.has(a))s.push({path:n?`${n}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,n){let r=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),l=this.validateWithRule(o,i,i.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(o){r.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:s}}validateWithRule(e,t,n){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let s=t.validator(e);if(s)r.push({path:n,message:t.message||s,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let n=t.split("."),r=e;for(let s of n)if(r&&typeof r==="object"&&s in r)r=r[s];else return;return r}generateRulesFromInterface(e){let t=[],n=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,s,i,o]=r;t.push({path:s,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Gd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Yd(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class pa{fileLoader=new ya;envProcessor=new ci;validator=new ha;async loadConfig(e){let t=Date.now(),{cache:n,performance:r,schema:s,validate:i,...o}=e;try{if(n?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let l;try{l=await this.loadConfigurationStrategies(o,!0,n)}catch(a){if(o.configFile)throw a;let c=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(c)throw a;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),m=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw a;if(m&&(!c||!h))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(s||i)await this.validateConfiguration(l.config,s,i,o.name);if(n?.enabled&&l)this.cacheResult(o.name||"",l,n,o);if(r?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(a);if(r.slowThreshold&&a.duration>r.slowThreshold)lt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);l.metrics=a}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let a=Date.now()-t;throw lt.error(`Configuration loading failed after ${a}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,n){let{name:r="",alias:s,configFile:i,cwd:o,configDir:l,defaultConfig:a,checkEnv:c=!0,arrayStrategy:u="replace",verbose:m=!1}=e,h=o||qr.cwd(),w=[];if(i){let g=bt(h,i);w.push(g);let p=c?_n(r,a,m):a,E=await this.fileLoader.tryLoadFromPaths([g],p,{arrayStrategy:u,verbose:m,cacheTtl:n?.ttl,useCache:!n?.ttl||n.ttl>100});if(!E)throw Yt.configNotFound(r||i,w,s);if(m)lt.success(`Configuration loaded from explicit path: ${g}`);return this.finalizeResult(E,w,c,r,m)}let N=await this.loadLocalConfiguration(r,s,h,l,a,u,m,c,n);if(N)return w.push(...this.getLocalSearchPaths(r,s,h,l)),this.finalizeResult(N,w,c,r,m);let R=await this.loadHomeConfiguration(r,s,a,u,m,c);if(R)return w.push(...this.getHomeSearchPaths(r,s)),this.finalizeResult(R,w,c,r,m);let y=await this.loadPackageJsonConfiguration(r,s,h,a,u,m,c);if(y)return w.push(bt(h,"package.json")),this.finalizeResult(y,w,c,r,m);if(w.push(...this.getAllSearchPaths(r,s,h,l)),t)throw Yt.configNotFound(r,w,s);return{...await this.applyEnvironmentVariables(r,a,c,m),warnings:[`No configuration file found for "${r}"${Yd(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,n,r,s,i,o,l,a){let c=l?_n(e,s,o):s,u=this.getLocalDirectories(n,r);for(let m of u){if(o)lt.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(e,m,t),w=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(w){if(o)lt.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(e,t,n,r,s,i){if(!e)return null;let o=i?_n(e,n,s):n,l=[bt(un(),".config",e),bt(un(),".config"),un()];for(let a of l){if(s)lt.info(`Checking home directory: ${a}`);let c=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(c,o,{arrayStrategy:r,verbose:s});if(u){if(s)lt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,n,r,s,i,o){let l=o?_n(e,r,i):r;try{let a=bt(n,"package.json");if(!Uc(a))return null;let c={};try{c=JSON.parse(Qc(a,"utf8"))}catch(h){if(i)lt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=c[e],m=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let w of h){if(!w)continue;if(c[w]){u=c[w],m=w;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)lt.success(`Configuration loaded from package.json: ${m}`);return{config:ga(l,u,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)lt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,n,r){if(!n||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:_n(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,n,r,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,n,r){let s=[];if(n){let i=n(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw Yt.configValidation(r||"unknown",s,r)}checkCache(e,t){let n=this.generateCacheKey(e,t);return kr.get(n)||null}cacheResult(e,t,n,r){let s=this.generateCacheKey(e,r);kr.set(s,t,void 0,n.ttl)}generateCacheKey(e,t){let n=[e];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configFile)n.push(`configFile:${t.configFile}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(e,t){return Wc({cwd:e,configDir:t})}getAllSearchPaths(e,t,n,r){let s=[];return s.push(...this.getLocalSearchPaths(e,t,n,r)),s.push(...this.getHomeSearchPaths(e,t)),s.push(bt(n,"package.json")),s}getLocalSearchPaths(e,t,n,r){let s=this.getLocalDirectories(n,r),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let n=[bt(un(),".config",e),bt(un(),".config"),un()],r=[];for(let s of n)r.push(...this.fileLoader.generateConfigPaths(e,s,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}async function ba(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},n="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(n)r=await qs.loadConfig(e);else r=await qs.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){if(e.configFile)throw r;let s=r instanceof Error?r.name:"UnknownError",i=r instanceof Error?r.message:String(r);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)lt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await qs.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}function _n(e,t,n=!1){let r=new ci,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,l=[]){let a={...o};for(let[c,u]of Object.entries(o)){let m=[...l,c],h=[`${s}_${m.join("_").toUpperCase()}`,`${s}_${m.map((R)=>R.toUpperCase()).join("")}`,`${s}_${m.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,N;for(let R of h)if(w=qr.env[R],w!==void 0){N=R;break}if(w!==void 0&&N)if(typeof u==="boolean")a[c]=["true","1","yes"].includes(w.toLowerCase());else if(typeof u==="number"){let R=Number(w);if(!Number.isNaN(R))a[c]=R}else if(Array.isArray(u))try{a[c]=JSON.parse(w)}catch{a[c]=w.split(",").map((R)=>R.trim())}else a[c]=w;else if(u&&typeof u==="object"&&!Array.isArray(u))a[c]=i(u,m)}return a}return i(t)}var kr,ei,_o,Au,Nu=(e)=>e,Ou=(e,t)=>{for(var n in t)Au(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Mu.bind(t,n)})},Bu=(e,t)=>()=>(e&&(t=e(e=0)),t),Fo,zo,Dn,jn,Go,ad,ld,Do,$r,Qs,qe,Ee,cd,So,ud,$o,dd,fd,_s,md,Eo,xo,Is,gd,yd,hd,pd,Er,Yo,bd,je,Td,wd,Ro,xr,Vs,Pe,pe,Dd,ko,Sd,Co,$d,Ed,Ls,xd,vo,Ao,Rd,Ks,kd,Cd,vd,Ad,Nd,Rr,Xo,Md,Od="0.15.6",Ze,_r,Fn,Js,Hs,Ir,zs,Gs,qn,Ys,Xs,Lt,Zo,ea,ct,vt,ta,na,Bd,_d,ra,Lr,Dh,Le,be,Sh,Ld,$h,Kd,Eh,xh,No,Rh,Fd,qd,kh,Mo,Ch,vh,Ah,Nh,Mh,Fs,jd,Oh,dt,ia,Kr,oa,aa,li,la,ca,Fr,ua,da,Yt,Gd,lt,qs,Lh,Kh;var Ta=ut(()=>{kr=new Bo,ei=new Po,_o=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];Au=Object.defineProperty;Fo={};Ou(Fo,{withErrorRecovery:()=>Wo,tryLoadConfig:()=>rd,loadConfigWithResult:()=>td,loadConfig:()=>Ho,isRetryableError:()=>zu,isConfigNotFoundError:()=>Hu,isBunfigError:()=>Uo,globalPerformanceMonitor:()=>jn,globalCache:()=>Dn,getEnvOrDefault:()=>Gu,generateConfigTypes:()=>sd,defaultGeneratedDir:()=>na,defaultConfigDir:()=>ta,deepMergeWithArrayStrategy:()=>ii,deepMerge:()=>Qo,createLibraryConfig:()=>id,config:()=>nd,bunfigPlugin:()=>od,applyEnvVarsToConfig:()=>Ln,TypeGenerationError:()=>Gs,SchemaValidationError:()=>qn,PluginError:()=>Xs,PerformanceMonitor:()=>ni,FileSystemError:()=>zs,ErrorFactory:()=>Lt,EnvVarError:()=>Ir,EnvProcessor:()=>jr,ConfigValidator:()=>oi,ConfigValidationError:()=>Js,ConfigNotFoundError:()=>_r,ConfigMergeError:()=>Hs,ConfigLoader:()=>ai,ConfigLoadError:()=>Fn,ConfigFileLoader:()=>Wr,ConfigCache:()=>ti,CacheUtils:()=>Go,BunfigError:()=>Ze,BrowserConfigError:()=>Ys,ArrayMergeStrategies:()=>Zo});Bd=Bu(async()=>{zo=import.meta.require,Dn=new ti,jn=new ni,Go={createKey:Pu,isEquivalent:_u,estimateMemoryUsage:Iu},ad=Ar(Ws.cwd(),"config"),ld=Ar(Ws.cwd(),"src/generated"),Do=vr.env.CLARITY_LOG_DIR||Yc(Fu(),"logs"),$r={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Do,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Qs=await qu(),qe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Ee=qe,cd=qe.red,So=qe.green,ud=qe.yellow,$o=qe.blue,dd=qe.magenta,fd=qe.cyan,_s=qe.white,md=qe.gray,Eo=qe.bgRed,xo=qe.bgYellow,Is=qe.bold,gd=qe.dim,yd=qe.italic,hd=qe.underline,pd=qe.reset,Er={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Yo={debug:"\uD83D\uDD0D",info:$o("\u2139"),success:So("\u2713"),warning:xo(_s(Is(" WARN "))),error:Eo(_s(Is(" ERROR ")))},bd=new Or("stacks"),je=new Or("bunfig",{showTags:!0}),Td=Qe(Kn.cwd(),"config"),wd=Qe(Kn.cwd(),"src/generated"),Ro=Cr.env.CLARITY_LOG_DIR||zc(Qu(),"logs"),xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ro,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Vs=await Vu(),Pe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},pe=Pe,Dd=Pe.red,ko=Pe.green,Sd=Pe.yellow,Co=Pe.blue,$d=Pe.magenta,Ed=Pe.cyan,Ls=Pe.white,xd=Pe.gray,vo=Pe.bgRed,Ao=Pe.bgYellow,Rd=Pe.bgGray,Ks=Pe.bold,kd=Pe.dim,Cd=Pe.italic,vd=Pe.underline,Ad=Pe.strikethrough,Nd=Pe.reset,Rr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Xo={debug:"\uD83D\uDD0D",info:Co("\u2139"),success:ko("\u2713"),warning:Ao(Ls(Ks(" WARN "))),error:vo(Ls(Ks(" ERROR ")))},Md=new Pr("stacks"),Ze=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},_r=class extends Ze{code="CONFIG_NOT_FOUND";constructor(t,n,r){let s=r?` or alias "${r}"`:"";super(`Configuration "${t}"${s} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},Fn=class extends Ze{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Js=class extends Ze{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Hs=class extends Ze{code="CONFIG_MERGE_ERROR";constructor(t,n,r,s){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:s,originalError:r.name,originalMessage:r.message});this.cause=r}},Ir=class extends Ze{code="ENV_VAR_ERROR";constructor(t,n,r,s){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:s})}},zs=class extends Ze{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Gs=class extends Ze{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qn=class extends Ze{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Ys=class extends Ze{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,s){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:s})}},Xs=class extends Ze{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Lt={configNotFound(e,t,n){return new _r(e,t,n)},configLoad(e,t,n){return new Fn(e,t,n)},configValidation(e,t,n){return new Js(e,t,n)},configMerge(e,t,n,r){return new Hs(e,t,n,r)},envVar(e,t,n,r){return new Ir(e,t,n,r)},fileSystem(e,t,n){return new zs(e,t,n)},typeGeneration(e,t,n){return new Gs(e,t,n)},schemaValidation(e,t,n){return new qn(e,t,n)},browserConfig(e,t,n,r){return new Ys(e,t,n,r)},plugin(e,t,n){return new Xs(e,t,n)}},Zo={replace:"replace",concat:"concat",smart:"smart"},ea=/^https?:\/\//,ct=new Pr("bunfig",{showTags:!0}),vt=new ai,ta=Ve(Xt.cwd(),"config"),na=Ve(Xt.cwd(),"src/generated")});_d=Nr.env.CLARITY_LOG_DIR||Tu(Pd(),"logs"),ra={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_d,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lr={...ra},Dh=(async()=>{try{let{loadConfig:e}=await Bd().then(()=>Fo),t=await e({name:"clarity",alias:"logging",defaultConfig:ra,cwd:Nr.cwd()});if(t)Object.assign(Lr,t)}catch{}return Lr})();Le={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},be=Le,Sh=Le.red,Ld=Le.green,$h=Le.yellow,Kd=Le.blue,Eh=Le.magenta,xh=Le.cyan,No=Le.white,Rh=Le.gray,Fd=Le.bgRed,qd=Le.bgYellow,kh=Le.bgGray,Mo=Le.bold,Ch=Le.dim,vh=Le.italic,Ah=Le.underline,Nh=Le.strikethrough,Mh=Le.reset,Fs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jd={debug:"\uD83D\uDD0D",info:Kd("\u2139"),success:Ld("\u2713"),warning:qd(No(Mo(" WARN "))),error:Fd(No(Mo(" ERROR ")))};Oh=new Ur("stacks");dt=class dt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};ia=class ia extends dt{code="CONFIG_NOT_FOUND";constructor(e,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],s="";if(r.length===1)s=` or alias "${r[0]}"`;else if(r.length>1)s=` or aliases ${r.map((i)=>`"${i}"`).join(", ")}`;super(`Configuration "${e}"${s} not found`,{configName:e,alias:n,searchPaths:t,searchPathCount:t.length})}};Kr=class Kr extends dt{code="CONFIG_LOAD_ERROR";constructor(e,t,n){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}};oa=class oa extends dt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,n){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:n,validationErrors:t,errorCount:t.length})}};aa=class aa extends dt{code="CONFIG_MERGE_ERROR";constructor(e,t,n,r){super(`Failed to merge configuration from "${e}" with "${t}": ${n.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}};li=class li extends dt{code="ENV_VAR_ERROR";constructor(e,t,n,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${n}`,{envKey:e,envValue:t,expectedType:n,configName:r})}};la=class la extends dt{code="FILE_SYSTEM_ERROR";constructor(e,t,n){super(`File system ${e} failed for "${t}": ${n.message}`,{operation:e,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}};ca=class ca extends dt{code="TYPE_GENERATION_ERROR";constructor(e,t,n){super(`Failed to generate types from "${e}" to "${t}": ${n.message}`,{configDir:e,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}};Fr=class Fr extends dt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:e,configName:n,validationErrors:t,errorCount:t.length})}};ua=class ua extends dt{code="BROWSER_CONFIG_ERROR";constructor(e,t,n,r){super(`Failed to fetch configuration from "${e}": ${t} ${n}`,{endpoint:e,status:t,statusText:n,configName:r})}};da=class da extends dt{code="PLUGIN_ERROR";constructor(e,t,n){super(`Plugin "${e}" failed during ${t}: ${n.message}`,{pluginName:e,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}};Yt={configNotFound(e,t,n){return new ia(e,t,n)},configLoad(e,t,n){return new Kr(e,t,n)},configValidation(e,t,n){return new oa(e,t,n)},configMerge(e,t,n,r){return new aa(e,t,n,r)},envVar(e,t,n,r){return new li(e,t,n,r)},fileSystem(e,t,n){return new la(e,t,n)},typeGeneration(e,t,n){return new ca(e,t,n)},schemaValidation(e,t,n){return new Fr(e,t,n)},browserConfig(e,t,n,r){return new ua(e,t,n,r)},plugin(e,t,n){return new da(e,t,n)}};Gd=/^https?:\/\//;lt=new Ur("bunfig",{showTags:!0});qs=new pa;Lh=bt(qr.cwd(),"config"),Kh=bt(qr.cwd(),"src/generated")});import wa from"process";function ne(e=_.dialect){return e==="mysql"||e==="singlestore"||e==="vitess"}function Da(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ui(e,t,n=new Set){let r={...e};n.add(t);for(let s of Object.keys(t)){if(Ea.has(s))continue;let i=t[s];if(Da(i)&&!n.has(i)){let o=r[s];r[s]=ui(Da(o)?o:{},i,n)}else r[s]=i}return n.delete(t),r}function Vr(e){if(e)return e;let t=wa.env.DB_DIALECT||wa.env.DB_CONNECTION;if(t)return t;return _.dialect||"postgres"}function Z(e){if(_.dialect==="postgres")return`$${e}`;return"?"}function ve(e,t=1){if(e<=0)return"";if(_.dialect==="postgres"){let n=`$${t}`;for(let r=1;r<e;r++)n+=`, $${t+r}`;return n}return e===1?"?":`?${", ?".repeat(e-1)}`}async function Jr(){if(!Qr.fileLoaded){Qr.fileLoaded=!0;let e=await ba({name:"query-builder",alias:"qb",defaultConfig:$a}),t={};for(let[n,r]of Object.entries(e??{}))if(!Qr.explicit.has(n))t[n]=r;xa(t)}return _}function xa(e){let t=ui(_,e),n=_;for(let r of Object.keys(t)){if(Ea.has(r))continue;n[r]=t[r]}}function Ra(e){if(e.dialect&&Wn&&e.dialect!==Wn){let t=`${Wn}->${e.dialect}`;if(!Sa.has(t))Sa.add(t),console.warn(`[query-builder] Configuring dialect '${e.dialect}' overrides the previously configured dialect '${Wn}'. 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(e.dialect)Wn=e.dialect;for(let t of Object.keys(e))Qr.explicit.add(t);xa(e)}function Wh(e){return e}var $a,Ea,Xd,_,Zd,Qr,Wn=null,Sa;var Me=ut(()=>{Ta();$a={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}},Ea=new Set(["__proto__","constructor","prototype"]);Xd=Symbol.for("bun-query-builder.config"),_=globalThis[Xd]??=ui({},$a),Zd=Symbol.for("bun-query-builder.config-state"),Qr=globalThis[Zd]??={explicit:new Set,fileLoaded:!1};Sa=new Set});function tf(){let e=_.sqlite?.pragmas;return Array.isArray(e)?e:ef}function Un(e){for(let t of tf())try{e.run(t)}catch{}}var ef;var Hr=ut(()=>{Me();ef=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:ka}=globalThis.Bun;import{Database as rf}from"bun:sqlite";import{mkdirSync as sf}from"fs";import{dirname as of}from"path";import Vn from"process";function Qn(e){return e}function nf(e){return e!==null&&typeof e==="object"?e:null}function Ca(e,t){if(t.length===0||!/\$\d/.test(e))return{sql:e,params:t};let n=[],r="",s=0;for(let i=0;i<e.length;i++){let o=e[i];if(o==="'"||o==='"'||o==="`"){let l=af(e,i,o);r+=e.slice(i,l),i=l-1;continue}if(o==="-"&&e[i+1]==="-"){let l=e.indexOf(`
62
+ `,i),a=l===-1?e.length:l;r+=e.slice(i,a),i=a-1;continue}if(o==="/"&&e[i+1]==="*"){let l=e.indexOf("*/",i+2),a=l===-1?e.length:l+2;r+=e.slice(i,a),i=a-1;continue}if(o==="$"){let l=/^\d+/.exec(e.slice(i+1))?.[0];if(l){let a=Number(l);if(s=Math.max(s,a),a>=1&&a<=t.length){n.push(t[a-1]),r+="?",i+=l.length;continue}}}r+=o}if(s>t.length)throw Error(`SQL references $${s} but only ${t.length} value${t.length===1?" was":"s were"} provided`);if(n.length===0)return{sql:e,params:t};return{sql:r,params:n}}function af(e,t,n){for(let r=t+1;r<e.length;r++){if(e[r]!==n)continue;if(e[r+1]===n){r++;continue}return r+1}return e.length}class Ma{db;constructor(e){if(e!==":memory:"&&!e.startsWith(":")){let t=of(e);if(t&&t!==".")sf(t,{recursive:!0})}this.db=new rf(e),Un(this.db)}query(e,t=[]){let n=Ca(e,t);return this.db.prepare(n.sql).all(...n.params)}run(e,t=[]){let n=Ca(e,t);return this.db.prepare(n.sql).run(...n.params)}close(){this.db.close()}get database(){return this.db}}function va(e){return{__raw:!0,value:e,toString:()=>e}}function Aa(e){let t=e.trimStart();for(;;)if(t.startsWith("--")){let n=t.indexOf(`
63
+ `);t=n===-1?"":t.slice(n+1).trimStart()}else if(t.startsWith("/*")){let n=t.indexOf("*/");t=n===-1?"":t.slice(n+2).trimStart()}else return t}function lf(e){let t=[],n="",r=!1,s=!1,i=!1,o=!1;for(let a=0;a<e.length;a++){let c=e[a],u=e[a+1];if(!r&&!s&&!o&&c==="-"&&u==="-"){i=!0,n+=c;continue}if(i&&(c===`
64
+ `||c==="\r")){i=!1,n+=c;continue}if(!r&&!s&&!i&&c==="/"&&u==="*"){o=!0,n+=c;continue}if(o&&c==="*"&&u==="/"){o=!1,n+=c+u,a++;continue}if(i||o){n+=c;continue}if(c==="'"&&!s){if(r&&u==="'"){n+=c+u,a++;continue}r=!r,n+=c;continue}if(c==='"'&&!r){s=!s,n+=c;continue}if(c===";"&&!r&&!s){let m=Aa(n.trim());if(m)t.push(m);n="";continue}n+=c}let l=Aa(n.trim());if(l)t.push(l);return t}function Na(e){let t=new Ma(e);function n(i,...o){let l=i[0],a=[];for(let c=0;c<o.length;c++){let u=o[c],m=nf(u);if(m&&typeof m.sql==="string"&&Array.isArray(m.values))l+=m.sql+(i[c+1]||""),a.push(...m.values);else if(m&&(m.__raw||m.raw)){let h=m.raw,w=m.__raw?m.value:typeof h==="string"?h:h();l+=w+(i[c+1]||"")}else if(Array.isArray(u)){let h=u.map(()=>"?").join(", ");l+=h+(i[c+1]||""),a.push(...u)}else l+=`?${i[c+1]||""}`,a.push(u)}return{sql:l,values:a,execute:()=>{try{let c=l.trim().toUpperCase();if(c.startsWith("SELECT")||c.startsWith("PRAGMA")||/\bRETURNING\b/.test(c)){let u=t.query(l,Qn(a));return Promise.resolve(u)}else{let u=t.run(l,Qn(a));return Promise.resolve(u)}}catch(c){return Promise.reject(c)}},raw:()=>l,toString:()=>l,cancel:()=>{}}}function r(i,...o){if(Array.isArray(i)&&"raw"in i)return n(i,...o);if(typeof i==="string")return va(i);return n([""])}r.raw=(i)=>va(i),r.unsafe=(i,o=[])=>{let l=()=>{try{let a=i.trim().toUpperCase();if(a.startsWith("SELECT")||a.startsWith("PRAGMA")||/\bRETURNING\b/.test(a)){let c=t.query(i,Qn(o));return Promise.resolve(c)}else{let c=t.run(i,Qn(o));return Promise.resolve(c)}}catch(a){return Promise.reject(a)}};return{sql:i,values:o,execute:l,then:(a,c)=>l().then(a,c),raw:()=>i,toString:()=>i,cancel:()=>{}}},r.close=()=>(t.close(),Promise.resolve()),r.query=(i,o)=>{try{let l=t.query(i,Qn(o||[]));return Promise.resolve(l)}catch(l){return Promise.reject(l)}},r.file=async(i,o)=>{try{let{readFileSync:l}=await import("fs"),a=l(i,"utf-8"),c=lf(a);for(let u of c){let m=u.trim();if(!m||m.startsWith("--"))continue;let h=m.toUpperCase();if(h.startsWith("SELECT")||h.startsWith("PRAGMA"))t.query(u);else t.run(u)}return Promise.resolve([])}catch(l){return Promise.reject(l)}};let s=0;return r.begin=async(i,o)=>{let l=typeof i==="function"?i:o;if(typeof l!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let a=s>0,c=`qb_sp_${s}`;if(a)t.run(`SAVEPOINT ${c}`);else t.run("BEGIN");s++;try{let u=await l(r);if(s--,a)t.run(`RELEASE SAVEPOINT ${c}`);else t.run("COMMIT");return u}catch(u){s--;try{if(a)t.run(`ROLLBACK TO SAVEPOINT ${c}`),t.run(`RELEASE SAVEPOINT ${c}`);else t.run("ROLLBACK")}catch{}throw u}},r.savepoint=r.begin,r.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},r._wrapper=t,r}function cf(e){let t=e.replace(/^(?:sqlite|sqlite3|file):/i,"");if(t===e)return e;return(t.startsWith("///")?t.slice(2):t.startsWith("//")?t.slice(2):t)||":memory:"}function zr(e=_.database){let t=Vn.env.DB_DATABASE||e?.database||"";return String(t).replace(/^['"]|['"]$/g,"")}function uf(e,t){if((e==="postgres"||e==="mysql"||e==="singlestore"||e==="vitess")&&Vn.env.DB_CONNECTION===e){let c=Vn.env,u=(c.DB_DATABASE||t.database||"").replace(/^['"]|['"]$/g,""),m=c.DB_USERNAME||t.username,h=c.DB_PASSWORD??t.password??"",w=c.DB_HOST||t.host||"localhost",N=c.DB_PORT||t.port,R=e==="postgres"?"postgres":"mysql",y=c.DB_SSL==="true"||c.DB_SSL==="1"||t.ssl?"?ssl=true":"";return`${R}://${m}:${h}@${w}${N?`:${N}`:""}/${u}${y}`}if(t.url)return e==="sqlite"?cf(t.url):t.url;let{database:n,username:r,password:s,host:i="localhost",port:o,ssl:l}=t,a=l||Vn.env.DB_SSL==="true"||Vn.env.DB_SSL==="1"?"?ssl=true":"";switch(e){case"postgres":return`postgres://${r}:${s}@${i}${o?`:${o}`:""}/${n}${a}`;case"mysql":case"singlestore":case"vitess":return`mysql://${r}:${s}@${i}${o?`:${o}`:""}/${n}${a}`;case"sqlite":if(n===":memory:")return":memory:";return n||":memory:";default:throw Error(`Unsupported dialect: ${e}`)}}function Oa(e){if(!e)return{};let t={},n=(r)=>Math.max(0,Math.round(r/1000));if(typeof e.max==="number"&&Number.isFinite(e.max))t.max=e.max;if(typeof e.idleTimeoutMs==="number"&&Number.isFinite(e.idleTimeoutMs))t.idleTimeout=n(e.idleTimeoutMs);if(typeof e.acquireTimeoutMs==="number"&&Number.isFinite(e.acquireTimeoutMs))t.connectionTimeout=n(e.acquireTimeoutMs);if(typeof e.maxLifetimeMs==="number"&&Number.isFinite(e.maxLifetimeMs))t.maxLifetime=n(e.maxLifetimeMs);return t}function df(){let e=_.dialect,t=uf(e,_.database);try{if(e==="sqlite")return Na(t);let n=Oa(_.database.pool);return Object.keys(n).length>0?new ka(t,n):new ka(t)}catch(n){if(console.error(`[query-builder] Failed to create database connection for dialect '${e}': ${n.message}`),e==="sqlite")return Na(":memory:");throw n}}function ff(){let e=_.database;return JSON.stringify({dialect:_.dialect,database:e.database,username:e.username,password:e.password,host:e.host,port:e.port,url:e.url,pool:Oa(e.pool)})}function Kt(e=!1){let t=ff();if(e||Sn!==null&&di!==t||!Sn)Ba(),Sn=df(),di=t;return Sn}function Ba(){let e=Sn;return Sn=null,di=null,e}async function mf(e){if(!e||typeof e.close!=="function")return;await e.close()}function gf(){mf(Ba()).catch((t)=>{console.error(`[query-builder] Failed to close database connection: ${t.message}`)})}async function fi(e){try{return await e(Kt())}catch(t){if(t?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||t?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let n=Kt(!0);return await e(n)}throw t}}function yf(){return new Proxy(function(){},{get(e,t){let n=Kt(),r=n[t];if(typeof r==="function")return r.bind(n);return r},apply(e,t,n){return Kt()(...n)}})}var Sn=null,di=null,te;var Ft=ut(()=>{Me();Hr();te=yf()});function $n(e){return e==="integer"||e==="bigint"||e==="float"||e==="double"||e==="decimal"}function Pa(e){if(typeof e!=="string")return;switch(e.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Zr(e){switch(e){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}var mi=()=>{};function gi(e){let t=String(e).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(t.endsWith("y")&&!/[aeou]y$/.test(t))return`${t.slice(0,-1)}ies`;if(t.endsWith("s")||t.endsWith("x")||t.endsWith("ch")||t.endsWith("sh"))return`${t}es`;return`${t}s`}function qt(e){return typeof e?.table==="string"&&e.table.length>0?e.table:gi(String(e?.name??""))}function Tf(e){return e.endsWith("s")?e.slice(0,-1):e}function wf(e){if(e.endsWith("ies")&&e.length>3){let t=e.slice(0,-3),n=t[t.length-1];if(n&&!"aeiou".includes(n))return`${t}y`}if(e.endsWith("es")&&e.length>2){let t=e.slice(0,-2);if(t.endsWith("s")||t.endsWith("x")||t.endsWith("ch")||t.endsWith("sh"))return t}if(e.endsWith("s")&&!e.endsWith("ss")&&!e.endsWith("us")&&!e.endsWith("is"))return e.slice(0,-1);return e}function jt(e){if(e==="none")return(t)=>t;if(e==="inflect")return wf;return Tf}var Wt=()=>{};function tn(e){if(e.length===0)return"";let t=[];for(let n of e)if(n.conn==="OR"&&t.length>0)t[t.length-1].push(n);else t.push([n]);return t.map((n,r)=>{let s=n.map((o)=>o.sql).join(" OR "),i=n.length>1&&t.length>1?`(${s})`:s;return r===0?i:`${n[0].conn} ${i}`}).join(" ")}function Ge(e,t,n,r){if(t.length===0)return n?"1 = 1":"1 = 0";return`${e} ${n?"NOT IN":"IN"} (${r})`}function Sf(e,t){if(t!=="postgres")return e;let n="",r=0,s=0;while(s<e.length){let i=e[s];if(i==="'"){let o=_a(e,s,"'");n+=e.slice(s,o),s=o;continue}if(i==='"'){let o=_a(e,s,'"');n+=e.slice(s,o),s=o;continue}if(i==="$"){let o=e.slice(s).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(o){let l=e.indexOf(o,s+o.length),a=l===-1?e.length:l+o.length;n+=e.slice(s,a),s=a;continue}}if(i==="?"){r++,n+=`$${r}`,s++;continue}n+=i,s++}return n}function _a(e,t,n){let r=t+1;while(r<e.length){if(e[r]===n){if(e[r+1]===n){r+=2;continue}return r+1}r++}return e.length}function ts(e,t,n=Number.POSITIVE_INFINITY){let r=[],s=0,i=(o)=>o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122||o===95;for(let o=0;o<e.length;o++){let l=e.charCodeAt(o);if(l===45&&e.charCodeAt(o+1)===45){let c=e.indexOf(`
65
+ `,o+2);if(c===-1)return r;o=c;continue}if(l===47&&e.charCodeAt(o+1)===42){let c=1,u=o+2;while(u<e.length&&c>0)if(e[u]==="/"&&e[u+1]==="*")c++,u+=2;else if(e[u]==="*"&&e[u+1]==="/")c--,u+=2;else u++;o=u-1;continue}if(l===39||l===34||l===96){let c=o+1;while(c<e.length){if(e.charCodeAt(c)===l){if(e.charCodeAt(c+1)===l){c+=2;continue}break}c++}o=c;continue}if(l===36){let c=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(e.slice(o));if(c){let u=e.indexOf(c[0],o+c[0].length);o=u===-1?e.length:u+c[0].length-1;continue}}if(l===40){s++;continue}if(l===41){s=Math.max(0,s-1);continue}if(s!==0)continue;if(o===0)continue;let a=l&-33;if(a<65||a>90)continue;if(i(e.charCodeAt(o-1)))continue;for(let{key:c,pattern:u}of t){u.lastIndex=o;let m=u.exec(e);if(!m)continue;if(r.push({key:c,start:o,length:m[0].length}),r.length>=n)return r;o+=m[0].length-1;break}}return r}var Ia="1 = 0";var ns=()=>{};function xn(e){if(typeof e==="number")return{length:e};return e}function xi(e){if(typeof e==="number")return{max:e};return e}function Ym(e){return typeof e==="function"}function Xm(e){return e.replace(/[A-Z]/g,(t)=>t.toLowerCase())}function Dl(e,t){if(!t||typeof t.fractionDigits!=="number")return e;return Number(e.toFixed(t.fractionDigits))}function Qt(e,t={}){if(!e)return t;return new Proxy(e,{get(n,r){if(r in t)return t[r];let s=n[r];if(s!==void 0)return s;let i=n[Xm(r)];if(Ym(i))return i.bind(n);return}})}function Sl(e){let t=(u)=>{let m=Array.isArray(u)?u:[],h=Math.floor(Math.random()*m.length);return m[h]},n=()=>e.string,r=()=>e.number,s=()=>e.random,i=Qt(e.string,{alpha:(u)=>n()?.alpha?.(xn(u)),alphanumeric:(u)=>n()?.alphanumeric?.(xn(u)),numeric:(u)=>n()?.numeric?.(xn(u)),sample:(u)=>n()?.sample?.(xn(u)),hexadecimal:(u)=>n()?.hexadecimal?.(xn(u))}),o=Qt(e.number,{int:(u)=>r()?.int?.(xi(u)),float:(u)=>{let m=xi(u);return Dl(Number(r()?.float?.(m)??0),m)}}),l=Qt(e.helpers,{arrayElement:t,arrayElements:(u,m)=>{let h=[...Array.isArray(u)?u:[]],w=typeof m==="number"?m:Math.max(1,Math.floor(Math.random()*h.length));for(let N=h.length-1;N>0;N-=1){let R=Math.floor(Math.random()*(N+1));[h[N],h[R]]=[h[R],h[N]]}return h.slice(0,Math.min(w,h.length))},shuffle:(u)=>{let m=[...Array.isArray(u)?u:[]];for(let h=m.length-1;h>0;h-=1){let w=Math.floor(Math.random()*(h+1));[m[h],m[w]]=[m[w],m[h]]}return m},maybe:(u,m)=>{let h=typeof m?.probability==="number"?m.probability:0.5;return Math.random()<h?u():void 0},slugify:(u)=>String(u??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),c={string:i,number:o,helpers:l,datatype:{boolean:(u)=>{let m=typeof u==="number"?u:u?.probability;if(typeof m==="number")return Math.random()<m;return Boolean(s()?.boolean?.())},number:(u)=>Number(r()?.int?.(xi(u))??0),float:(u)=>Dl(Number(r()?.float?.(u)??0),u),uuid:()=>crypto.randomUUID(),string:(u)=>String(n()?.alphanumeric?.({length:u??10})??""),hexadecimal:(u)=>String(n()?.hexadecimal?.(xn(u))??""),array:(u)=>Array.from({length:u??3},()=>n()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:n()?.alphanumeric?.({length:8})})},location:Qt(e.address),address:Qt(e.address),vehicle:Qt(e.vehicle,{vrm:()=>e.vehicle?.registration?.()}),company:Qt(e.company,{catchPhrase:()=>e.company?.catchphrase?.(),buzzPhrase:()=>e.company?.bs?.()??e.company?.buzzword?.()})};return new Proxy(e,{get(u,m){if(m in c)return c[m];let h=u[m];if(h&&typeof h==="object")return Qt(h);return h}})}var Ri=()=>{};function us(e){if(typeof e==="string")return{model:e};if(e&&typeof e==="object"&&typeof e.model==="string"){let t=e;return{model:t.model,foreignKey:t.foreignKey,onDelete:t.onDelete}}return null}function Rn(e){if(!e)return[];return(Array.isArray(e)?e:typeof e==="object"?Object.values(e):[]).map(us).filter((n)=>n!==null)}var ds=()=>{};import{Database as vi}from"bun:sqlite";function sn(){let e=new Date().toISOString();return ne(_.dialect)?e.slice(0,19).replace("T"," "):e}function Mt(e,t){if(typeof e!=="string"||e.length===0)throw TypeError(`[bun-query-builder] ${t}: identifier must be a non-empty string, got ${typeof e}`);if(e.length>64)throw TypeError(`[bun-query-builder] ${t}: identifier '${e}' exceeds 64 chars`);if(!Al.test(e))throw TypeError(`[bun-query-builder] ${t}: identifier '${e}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Nl(e,t){if(typeof e!=="string"||e.length===0)throw TypeError(`[bun-query-builder] ${t}: identifier must be a non-empty string, got ${typeof e}`);let n=e.split(".");if(n.length>2||n.some((r)=>r.length===0||r.length>64||!Al.test(r)))throw TypeError(`[bun-query-builder] ${t}: invalid ORDER BY column '${e}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function eg(e,t){Ni.set(e,t),Cn.clear()}function Ml(){Ni.clear(),Cn.clear()}function et(e){if(!fs)try{fs=(tr(),Zm(Ll)).getModel}catch{fs=()=>{return}}return fs(e)??Ni.get(e)}function $l(e){let t=ms.get(e);if(t!==void 0)return t;let n=0,r=e.replace(/\?/g,()=>`$${++n}`);if(ms.size>=tg)ms.clear();return ms.set(e,r),r}function El(e){if(e==null)return 0;if(typeof e.affectedRows==="number")return e.affectedRows;if(typeof e.count==="number")return e.count;if(Array.isArray(e))return e.length;return 0}function xl(e){if(e==null||typeof e!=="object")return null;if("insertId"in e&&e.insertId!=null)return e.insertId;if("lastInsertRowid"in e&&e.lastInsertRowid!=null)return e.lastInsertRowid;return null}class Ai{sqliteDb;dialect="sqlite";constructor(e){this.sqliteDb=e}all(e,t){return Promise.resolve(this.sqliteDb.query(e).all(...t))}get(e,t){return Promise.resolve(this.sqliteDb.query(e).get(...t)??void 0)}run(e,t){let n=this.sqliteDb.run(e,t);return Promise.resolve({changes:n.changes,lastInsertId:n.lastInsertRowid})}insert(e,t){return this.run(e,t)}}class Ol{dialect;constructor(e){this.dialect=e}conn(){return Kt()}text(e){return this.dialect==="postgres"?$l(e):e}async all(e,t){let n=await this.conn().unsafe(this.text(e),t);return Array.isArray(n)?n:[]}async get(e,t){let n=await this.conn().unsafe(this.text(e),t);if(Array.isArray(n))return n[0]??void 0;return n??void 0}async run(e,t){let n=await this.conn().unsafe(this.text(e),t);return{changes:El(n),lastInsertId:xl(n)}}async insert(e,t,n){if(this.dialect==="postgres"){let i=await this.conn().unsafe(`${$l(e)} RETURNING ${n}`,t),o=Array.isArray(i)?i[0]:i;return{changes:1,lastInsertId:o?o[n]??null:null}}let r=await this.conn().unsafe(e,t),s=xl(r);if(s==null){let i=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);s=(Array.isArray(i)?i[0]:i)?.id??null}return{changes:El(r)||1,lastInsertId:s}}}function lw(e){if(e.database instanceof vi)Ot=e.database,ps=!1;else Ot=new vi(e.database||":memory:",{create:!0}),ps=!0,Un(Ot);Dt=null,kn=null}function cw(){let e=ps,t=Ot;if(Ot=null,ps=!1,Dt=null,kn=null,gs=null,ys=null,e&&t)try{t.close()}catch{}}function De(){if(Ot){if(!Dt||kn!==Ot)Dt=new Ai(Ot),kn=Ot,gs="sqlite",ys=null;return Dt}let e=_.dialect,t=_.database?.database??null;if(Dt&&kn===null&&gs===e&&ys===t)return Dt;if(kn=null,gs=e,ys=t,e==="sqlite"){let n=new vi(t||":memory:",{create:!0});Un(n),Dt=new Ai(n)}else Dt=new Ol(e);return Dt}function uw(){let e=De();if(e.sqliteDb)return e.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${e.dialect}'. Use the async model API instead.`)}function vn(e){let t=e.traits;return Boolean(t?.useSoftDeletes||t?.softDeletable)}function on(e){let t=e.traits;return Boolean(t?.useTimestamps||t?.timestampable)}function ng(e){let t=Rl.get(e);if(t)return t;let n=new Set,r=e.belongsToMany;if(r){if(Array.isArray(r)){for(let s of r)if(typeof s==="string")n.add(s.toLowerCase());else if(s&&typeof s==="object"&&s.model)n.add(s.model.toLowerCase())}else if(typeof r==="object")for(let s of Object.keys(r))n.add(s)}return Rl.set(e,n),n}function Bl(e){let t={};for(let[n,r]of Object.entries(e))t[$e(n)]=r;return t}function rg(e){for(let t in e)if($e(t)!==t)return Bl(e);return e}function sg(e,t){if(e[t])return e[t];let n=$e(t);if(e[n])return e[n];for(let r of Object.keys(e))if($e(r)===n)return e[r];return}class Xe{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(e,t={}){this._definition=e,this._attributes=rg({...t}),this._original=null;let n=ng(e);if(n.size===0)return;let r=this;return new Proxy(this,{get(s,i,o){if(typeof i==="string"&&n.has(i)&&!(i in s))return()=>{let l=Pl(e,i);if(!l||l.type!=="belongsToMany")throw Error(`[orm] relation '${i}' did not resolve to a belongsToMany on '${e.name}'`);let a=et(l.relatedModelName),c=a?.getDefinition?.()||a?.definition;if(!c)throw Error(`[orm] related model '${l.relatedModelName}' is not registered`);return new _l(r,e,l,c)};return Reflect.get(s,i,o)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(e){let t=this._definition.get?.[e];if(t)try{let n=t(this._attributes);if(n!==void 0)return n}catch{}return this._attributes[$e(e)]}getAttribute(e){return this._attributes[$e(e)]}getAttributes(){return{...this._attributes}}set(e,t){if(this._original===null)this._original={...this._attributes};this._attributes[$e(e)]=t}only(e){let t={};for(let n of e)t[n]=this._attributes[$e(n)];return t}except(e){let t=new Set(e.map((r)=>$e(r))),n={};for(let r of Object.keys(this._attributes))if(!t.has(r))n[r]=this._attributes[r];return n}getRelation(e){return this._relations[e]}setRelation(e,t){this._relations[e]=t}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}isDirty(e){if(this._original===null)return!1;if(e){let t=$e(e);return this._attributes[t]!==this._original[t]}return Object.keys(this._attributes).some((t)=>this._attributes[t]!==this._original[t])}isClean(e){return!this.isDirty(e)}getOriginal(e){return this.getOriginalAttributes()[$e(e)]}getChanges(){if(this._original===null)return{};let e={};for(let t of Object.keys(this._attributes))if(this._attributes[t]!==this._original[t])e[t]=this._attributes[t];return e}fill(e){let t=this._definition.attributes;for(let[n,r]of Object.entries(e)){let s=sg(t,n),i=!s&&$e(n).endsWith("_id");if(s?.fillable&&!s?.guarded||i){if(this._original===null)this._original={...this._attributes};this._attributes[$e(n)]=r}}return this}forceFill(e){if(this._original===null)this._original={...this._attributes};let t=Bl(e);Object.assign(this._attributes,t);for(let n of Object.keys(t))this._forced.add(n);return this}async save(){let e=De(),t=this._definition.primaryKey||"id",n=this._definition.hooks,r=this._definition.set||{};for(let[s,i]of Object.entries(r))if(this.isDirty(s))this._attributes[$e(s)]=i(this._attributes);if(this._attributes[t]){await n?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){let o=i.map((a)=>`${a} = ?`).join(", "),l=[...Object.values(s),this._attributes[t]];if(on(this._definition)){let a=sn();await e.run(`UPDATE ${this._definition.table} SET ${o}, updated_at = ? WHERE ${t} = ?`,[...Object.values(s),a,this._attributes[t]])}else await e.run(`UPDATE ${this._definition.table} SET ${o} WHERE ${t} = ?`,l)}await n?.afterUpdate?.(this)}else{let s=this._definition.attributes,i={};for(let[c,u]of Object.entries(s)){if(u.guarded&&!this._forced.has($e(c)))continue;let m=$e(c);if(this._attributes[m]!==void 0)i[m]=this._attributes[m]}for(let c of Object.keys(this._attributes))if(c.endsWith("_id")&&c!==t&&!(c in i))i[c]=this._attributes[c];if(on(this._definition)){let c=sn(),u=this._attributes.created_at;i.created_at=u===void 0||u===null?c:u,i.updated_at=c}if(this._definition.traits?.useUuid&&!i.uuid)i.uuid=crypto.randomUUID();await n?.beforeCreate?.(i);let o=Object.keys(i),l=o.map(()=>"?").join(", "),a=await e.insert(`INSERT INTO ${this._definition.table} (${o.join(", ")}) VALUES (${l})`,Object.values(i),t);for(let[c,u]of Object.entries(i))this._attributes[c]=u;if(a.lastInsertId!=null)this._attributes[t]=a.lastInsertId;await n?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(e){return this.fill(e),this.save()}async fresh(){let e=De(),t=this._definition.primaryKey||"id",n=this._attributes[t];if(n==null)return null;let r=await e.get(`SELECT * FROM ${this._definition.table} WHERE ${t} = ?`,[n]);if(!r)return null;return new Xe(this._definition,r)}async delete(){let e=De(),t=this._definition.primaryKey||"id",n=this._attributes[t],r=this._definition.hooks;if(!n)throw Error("Cannot delete a model without a primary key");if(await r?.beforeDelete?.(this),vn(this._definition)){let s=sn();await e.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${t} = ?`,[s,n]),this._attributes[Vt]=s}else await e.run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[n]);return await r?.afterDelete?.(this),!0}async restore(){if(!vn(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let e=this._definition.primaryKey||"id",t=this._attributes[e];if(!t)throw Error("Cannot restore a model without a primary key");return await De().run(`UPDATE ${this._definition.table} SET ${Vt} = ? WHERE ${e} = ?`,[null,t]),this._attributes[Vt]=null,this._original=null,this}trashed(){return this._attributes[Vt]!=null}async refresh(){let e=De(),t=this._definition.primaryKey||"id",n=this._attributes[t];if(!n)throw Error("Cannot refresh a model without a primary key");let r=await e.get(`SELECT * FROM ${this._definition.table} WHERE ${t} = ?`,[n]);if(!r)return null;return this._attributes=r,this._original=null,this}replicate(){let e=this._definition.primaryKey||"id",t={...this._attributes};return delete t[e],delete t.uuid,delete t.created_at,delete t.updated_at,new Xe(this._definition,t)}toArray(){let e={...this._attributes};for(let[t,n]of Object.entries(this._relations))if(Array.isArray(n))e[t]=n.map((r)=>r.toArray());else if(n)e[t]=n.toArray();else e[t]=null;return e}toJSON(){let e=new Set;for(let[n,r]of Object.entries(this._definition.attributes))if(r.hidden)e.add(n);let t={};for(let[n,r]of Object.entries(this._attributes))if(!e.has(n))t[n]=r;for(let[n,r]of Object.entries(this._relations))if(Array.isArray(r))t[n]=r.map((s)=>s.toJSON());else if(r)t[n]=r.toJSON();else t[n]=null;return t}}function gt(e){return $e(e)}function $e(e){let t=kl.get(e);if(t!==void 0)return t;return t=e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),kl.set(e,t),t}function rn(e){let t=Cl.get(e);if(t!==void 0)return t;return t=gi(e),Cl.set(e,t),t}function vl(e,t){let n=e[t];if(!n)return[];if(Array.isArray(n))return n.map((r)=>typeof r==="string"?r:String(r?.model??"")).filter(Boolean);if(typeof n==="object")return Object.keys(n);if(typeof n==="string")return[n];return[]}function ag(e,t){let n=e.name??e.table??"model",s=og.filter((o)=>vl(e,o).some((l)=>l.toLowerCase()===t.toLowerCase())).filter((o)=>!hs.includes(o));if(s.length>0)return`[orm] '${n}' declares '${t}' as ${s.join("/")}, which eager loading does not support yet. Supported kinds: ${hs.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let i=hs.flatMap((o)=>vl(e,o));return i.length>0?`[orm] '${n}' has no relation '${t}'. Available: ${i.join(", ")}.`:`[orm] '${n}' has no relation '${t}' \u2014 it declares no relations at all.`}function Pl(e,t){let{name:n,table:r}=e,s=e.primaryKey||"id";function i(R){if(!R)return null;if(Array.isArray(R)){for(let y of R){let b=typeof y==="string"?y:y?.model||"";if(b&&b.toLowerCase()===t.toLowerCase())return b}return null}if(typeof R==="object"){for(let[y,b]of Object.entries(R))if(y===t||y.toLowerCase()===t.toLowerCase())return typeof b==="string"?b:b?.model||b?.target||y}return null}function o(){let R=e.belongsTo;if(!R)return null;let y=t.toLowerCase(),b=(g)=>{if(typeof g==="string")return{model:g};if(g&&typeof g==="object"&&typeof g.model==="string")return{model:g.model,foreignKey:g.foreignKey};return null};if(Array.isArray(R)){for(let g of R){let p=b(g);if(p&&p.model.toLowerCase()===y)return p}return null}if(typeof R==="object"){for(let[g,p]of Object.entries(R))if(g===t||g.toLowerCase()===y)return b(p)}return null}function l(){let R=e.belongsToMany;if(!R)return null;if(Array.isArray(R)){for(let y of R)if(typeof y==="string"){if(y.toLowerCase()===t.toLowerCase())return{entry:y}}else if(y&&typeof y==="object"&&y.model){if(y.model.toLowerCase()===t.toLowerCase())return{entry:y}}return null}if(typeof R==="object"){for(let[y,b]of Object.entries(R))if(y===t||y.toLowerCase()===t.toLowerCase())return{entry:b}}return null}let a=i(e.hasMany);if(a){let y=et(a)?.getTable?.()||rn(a),b=$e(n)+"_id";return{type:"hasMany",relatedModelName:a,relatedTable:y,foreignKey:b,localKey:s}}let c=i(e.hasOne);if(c){let y=et(c)?.getTable?.()||rn(c),b=$e(n)+"_id";return{type:"hasOne",relatedModelName:c,relatedTable:y,foreignKey:b,localKey:s}}let u=o();if(u){let R=u.model,y=et(R),b=y?.getTable?.()||rn(R),g=y?.getDefinition?.()?.primaryKey||"id",p=u.foreignKey||`${$e(R)}_id`;return{type:"belongsTo",relatedModelName:R,relatedTable:b,foreignKey:p,localKey:g}}let m=l();if(m){let R=typeof m.entry==="object",y=R?m.entry.model:m.entry,g=et(y)?.getTable?.()||rn(y),p=R?m.entry:null,E,D;if(p?.table)E=p.table;else if(p?.through){D=p.through;let v=et(p.through);if(!v)throw Error(`[orm] belongsToMany relation '${t}' on '${n}' references unknown through model '${p.through}'. Make sure '${p.through}' is registered.`);E=v.getTable?.()||v.getDefinition?.()?.table||rn(p.through)}else{let v=er(r),x=er(g);E=[v,x].sort().join("_")}let J=p?.foreignKey||`${er(r)}_id`,B=p?.relatedKey||`${er(g)}_id`,W=[];if(p?.pivot?.columns)for(let v of Object.keys(p.pivot.columns))W.push(v);if(D){let v=et(D),x=v?.getDefinition?.()||v?.definition,C=x?.attributes??{},k=x?.primaryKey??"id";for(let P of Object.keys(C)){if(P===J||P===B||P===k)continue;if(!W.includes(P))W.push(P)}}return{type:"belongsToMany",relatedModelName:y,relatedTable:g,foreignKey:J,localKey:s,pivotTable:E,pivotFkParent:J,pivotFkRelated:B,pivotColumns:W,pivotModelName:D,pivotTimestamps:Boolean(p?.pivot?.timestamps)}}let h=(R,y)=>{if(!R||typeof R!=="object"||Array.isArray(R))return null;let b=R[t]??R[Object.keys(R).find((x)=>x.toLowerCase()===t.toLowerCase())??""];if(!b||typeof b!=="object")return null;let{through:g,target:p}=b;if(!g||!p)return null;let E=et(g),D=E?.getDefinition?.()||E?.definition,J=E?.getTable?.()||D?.table||rn(g),B=D?.primaryKey||"id",v=et(p)?.getTable?.()||rn(p);return{type:y,relatedModelName:p,relatedTable:v,foreignKey:`${$e(n)}_id`,localKey:s,throughTable:J,throughForeignKey:`${$e(n)}_id`,throughLocalKey:B,targetForeignKey:`${er(J)}_id`}},w=h(e.hasManyThrough,"hasManyThrough");if(w)return w;let N=h(e.hasOneThrough,"hasOneThrough");if(N)return N;return null}function Ci(e,t){let n=new Set;for(let r of e){let s=r.get(t);if(s!=null)n.add(s)}return[...n]}function er(e){return jt(_.relations?.singularizeStrategy)(e)}class _l{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(e,t,n,r){this._parent=e,this._parentDef=t,this._resolved=n,this._relatedDef=r}get parentId(){let e=this._parentDef.primaryKey||"id";return this._parent.get(e)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(e,t,n){if(n===void 0)this._wheres.push({sql:`${this.relatedTable}.${e} = ?`,params:[t]});else this._wheres.push({sql:`${this.relatedTable}.${e} ${String(t)} ?`,params:[n]});return this}wherePivot(e,t,n){if(n===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${e} = ?`,params:[t]});else this._pivotWheres.push({sql:`${this.pivotTable}.${e} ${String(t)} ?`,params:[n]});return this}wherePivotIn(e,t){if(!t.length)return this;let n=t.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${e} IN (${n})`,params:[...t]}),this}wherePivotNotIn(e,t){if(!t.length)return this;let n=t.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${e} NOT IN (${n})`,params:[...t]}),this}wherePivotNull(e){return this._pivotWheres.push({sql:`${this.pivotTable}.${e} IS NULL`,params:[]}),this}wherePivotNotNull(e){return this._pivotWheres.push({sql:`${this.pivotTable}.${e} IS NOT NULL`,params:[]}),this}orderBy(e,t="asc"){if(Nl(e,"orderBy(column)"),t!=="asc"&&t!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${t}'`);return this._orderBy.push(`${e} ${t.toUpperCase()}`),this}limit(e){if(!Number.isFinite(e)||e<0||!Number.isInteger(e))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${e}`);return this._limit=e,this}offset(e){if(!Number.isFinite(e)||e<0||!Number.isInteger(e))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${e}`);return this._offset=e,this}relatedSelectColumns(){let e=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),t=this._relatedDef.traits;if(t?.useTimestamps||t?.timestampable)e.add("created_at"),e.add("updated_at");if(t?.useSoftDeletes||t?.softDeletable)e.add("deleted_at");if(t?.useUuid)e.add("uuid");return[...e]}buildSelect(){let e=[],n=`SELECT ${this.relatedSelectColumns().map((r)=>`${this.relatedTable}.${r} AS ${ki}${r}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;n+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,n+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,e.push(this.parentId);for(let r of this._pivotWheres)n+=` AND ${r.sql}`,e.push(...r.params);for(let r of this._wheres)n+=` AND ${r.sql}`,e.push(...r.params);if(this._orderBy.length>0)n+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)n+=` LIMIT ${this._limit}`;if(this._offset!==void 0)n+=` OFFSET ${this._offset}`;return{sql:n,params:e}}hydrateRows(e){let t=this.fkParent,n=this.fkRelated;return e.map((r)=>{let s={},i={};for(let[l,a]of Object.entries(r))if(l.startsWith(ki))s[l.slice(ki.length)]=a;else if(l!==t&&l!==n)i[l]=a;let o=new Xe(this._relatedDef,s);return o.pivot=i,o})}async get(){let e=De(),{sql:t,params:n}=this.buildSelect(),r=await e.all(t,n);return this.hydrateRows(r)}async first(){return this._limit=1,(await this.get())[0]}async count(){let e=De(),t=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,n=[this.parentId];for(let s of this._pivotWheres)t+=` AND ${s.sql}`,n.push(...s.params);let r=await e.get(t,n);return Number(r?.count??0)}async exists(){return await this.count()>0}now(){return sn()}async attach(e,t={}){let n=De(),r=Array.isArray(e)?e:[e];if(r.length===0)return 0;let s=this._resolved.pivotTimestamps?this.now():null,i=0;for(let o of r){let l={[this.fkParent]:this.parentId,[this.fkRelated]:o,...t};if(s){if(l.created_at===void 0)l.created_at=s;if(l.updated_at===void 0)l.updated_at=s}let a=Object.keys(l),c=a.map(()=>"?").join(", "),u=`INSERT INTO ${this.pivotTable} (${a.join(", ")}) VALUES (${c})`,m=a.map((h)=>l[h]);await n.run(u,m),i++}return i}async detach(e){let t=De(),n=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,r=[this.parentId];if(e!==void 0&&e!==null){let s=Array.isArray(e)?e:[e];if(s.length===0)return 0;let i=s.map(()=>"?").join(", ");n+=` AND ${this.fkRelated} IN (${i})`,r.push(...s)}return(await t.run(n,r)).changes}async updateExistingPivot(e,t){let n=De(),r={...t};if(this._resolved.pivotTimestamps&&r.updated_at===void 0)r.updated_at=this.now();let s=Object.keys(r);if(s.length===0)return 0;let i=s.map((a)=>`${a} = ?`).join(", "),o=`UPDATE ${this.pivotTable} SET ${i} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,l=[...s.map((a)=>r[a]),this.parentId,e];return(await n.run(o,l)).changes}async sync(e){let t=De(),n=new Map;for(let c of e)if(c!=null&&typeof c==="object"&&"id"in c){let{id:u,...m}=c;n.set(u,m)}else n.set(c,{});let r=await t.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),s=new Set(r.map((c)=>c[this.fkRelated])),i=[],o=[],l=[],a=[...s].filter((c)=>!n.has(c));if(a.length>0)await this.detach(a),o.push(...a);for(let[c,u]of n)if(!s.has(c))await this.attach(c,u),i.push(c);else if(Object.keys(u).length>0)await this.updateExistingPivot(c,u),l.push(c);return{attached:i,detached:o,updated:l}}async toggle(e){let t=De(),n=Array.isArray(e)?e:[e];if(n.length===0)return{attached:[],detached:[]};let r=n.map(()=>"?").join(", "),s=await t.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${r})`,[this.parentId,...n]),i=new Set(s.map((a)=>a[this.fkRelated])),o=n.filter((a)=>!i.has(a)),l=n.filter((a)=>i.has(a));if(o.length>0)await this.attach(o);if(l.length>0)await this.detach(l);return{attached:o,detached:l}}}class de{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(e){this._definition=e}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(e,t,n){if(n===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:n,boolean:"and"});return this}orWhere(e,t,n){if(n===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"or"});else this._wheres.push({column:e,operator:t,value:n,boolean:"or"});return this}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}orWhereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"or"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}orWhereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"or"}),this}whereNull(e){return Mt(e,"whereNull(column)"),this._wheres.push({column:e,operator:"=",value:null,boolean:"and"}),this}orWhereNull(e){return Mt(e,"orWhereNull(column)"),this._wheres.push({column:e,operator:"=",value:null,boolean:"or"}),this}whereNotNull(e){return Mt(e,"whereNotNull(column)"),this._wheres.push({column:e,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(e){return Mt(e,"orWhereNotNull(column)"),this._wheres.push({column:e,operator:"!=",value:null,boolean:"or"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orWhereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"or"}),this}whereNotLike(e,t){return this._wheres.push({column:e,operator:"not like",value:t,boolean:"and"}),this}orWhereNotLike(e,t){return this._wheres.push({column:e,operator:"not like",value:t,boolean:"or"}),this}whereRaw(e,...t){return this._wheres.push({raw:e,rawParams:t,boolean:"and"}),this}orWhereRaw(e,...t){return this._wheres.push({raw:e,rawParams:t,boolean:"or"}),this}whereGroup(e){return this._addGroup("and",e)}orWhereGroup(e){return this._addGroup("or",e)}_addGroup(e,t){let n=new de(this._definition);if(t(n),n._wheres.length===0)return this;let r=[],s=n.buildWhereClauses(r);if(!s)return this;return this._wheres.push({raw:`(${s})`,rawParams:r,boolean:e}),this}whereBetween(e,t){return Mt(e,"whereBetween(column)"),this._wheres.push({column:e,operator:">=",value:t[0],boolean:"and"}),this._wheres.push({column:e,operator:"<=",value:t[1],boolean:"and"}),this}whereNotBetween(e,t){Mt(e,"whereNotBetween(column)");let n=gt(e);return this._wheres.push({raw:`(${n} < ? OR ${n} > ?)`,rawParams:[t[0],t[1]],boolean:"and"}),this}when(e,t){if(e)return t(this);return this}orderBy(e,t="asc"){if(Nl(e,"orderBy(column)"),t!=="asc"&&t!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${t}'`);return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){for(let t of e)if(!this._withRelations.includes(t))this._withRelations.push(t);return this}getWithRelations(){return this._withRelations}buildWhereClauses(e){let t=[];for(let n of this._wheres){let r;if(n.raw){if(r=n.raw,n.rawParams&&n.rawParams.length>0)e.push(...n.rawParams)}else if(n.value===null){let s=gt(n.column);r=n.operator==="="?`${s} IS NULL`:`${s} IS NOT NULL`}else if(n.operator==="in"||n.operator==="not in"){let s=n.value;r=Ge(gt(n.column),s,n.operator==="not in",s.map(()=>"?").join(", ")),e.push(...s)}else r=`${gt(n.column)} ${n.operator} ?`,e.push(n.value);t.push({conn:n.boolean==="or"?"OR":"AND",sql:r})}return tn(t)}softDeleteClause(){if(this._trashed==="include"||!vn(this._definition))return"";return this._trashed==="only"?`${Vt} IS NOT NULL`:`${Vt} IS NULL`}assertNoUnappliedClauses(e){let t=[];if(this._limit!==void 0)t.push("limit()");if(this._offset!==void 0)t.push("offset()");if(this._orderBy.length>0)t.push("orderBy()");if(t.length>0)throw TypeError(`[orm] ${e}() cannot apply ${t.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(e){let t=this._wheres.length>0?this.buildWhereClauses(e):"",n=this.softDeleteClause();if(t&&n)return`(${t}) AND ${n}`;return t||n}buildQuery(){let e=[],n=`SELECT ${this._select.map((s)=>s==="*"?s:gt(s)).join(", ")} FROM ${this._definition.table}`,r=this.composeWhere(e);if(r)n+=` WHERE ${r}`;if(this._orderBy.length>0)n+=` ORDER BY ${this._orderBy.map((s)=>`${gt(s.column)} ${s.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)n+=` LIMIT ${this._limit}`;if(this._offset!==void 0)n+=` OFFSET ${this._offset}`;return{sql:n,params:e}}toSql(){return this.buildQuery()}async eagerLoadRelations(e){if(e.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((t)=>this.eagerLoadRelation(t,e)))}async eagerLoadRelation(e,t){let n=De(),r=this._definition.primaryKey||"id",s=`${this._definition.name}:${e}`,i=Cn.get(s);if(i===void 0){if(i=Pl(this._definition,e),Cn.size>=ig)Cn.clear();Cn.set(s,i)}if(!i)throw Error(ag(this._definition,e));if(i.type==="hasMany"||i.type==="hasOne"){let o=Ci(t,r);if(o.length===0)return;let l=o.map(()=>"?").join(", "),a=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${i.foreignKey} IN (${l})`,o),c=et(i.relatedModelName),u=c?.getDefinition?.()||c?.definition||this._definition;if(i.type==="hasMany"){let m=new Map;for(let h of a){let w=h[i.foreignKey];if(!m.has(w))m.set(w,[]);m.get(w).push(h)}for(let h of t){let w=m.get(h.get(r))||[];h.setRelation(e,w.map((N)=>new Xe(u,N)))}}else{let m=new Map;for(let h of a){let w=h[i.foreignKey];if(!m.has(w))m.set(w,h)}for(let h of t){let w=m.get(h.get(r));h.setRelation(e,w?new Xe(u,w):null)}}}if(i.type==="belongsTo"){let o=new Set;for(let w of t){let N=w._attributes[i.foreignKey];if(N!=null)o.add(N)}let l=[...o];if(l.length===0)return;let a=l.map(()=>"?").join(", "),c=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${i.localKey} IN (${a})`,l),u=et(i.relatedModelName),m=u?.getDefinition?.()||u?.definition||this._definition,h=new Map;for(let w of c)h.set(w[i.localKey],w);for(let w of t){let N=w._attributes[i.foreignKey],R=h.get(N);w.setRelation(e,R?new Xe(m,R):null)}}if(i.type==="belongsToMany"){let o=Ci(t,r);if(o.length===0)return;if(!i.pivotTable||!i.pivotFkParent||!i.pivotFkRelated)return;let l=o.map(()=>"?").join(", "),a=await n.all(`SELECT * FROM ${i.pivotTable} WHERE ${i.pivotFkParent} IN (${l})`,o);if(a.length===0){for(let g of t)g.setRelation(e,[]);return}let c=new Set;for(let g of a){let p=g[i.pivotFkRelated];if(p!=null)c.add(p)}let u=[...c],m=et(i.relatedModelName),h=m?.getDefinition?.()||m?.definition||this._definition,w=h?.primaryKey||"id",N=[];if(u.length>0){let g=u.map(()=>"?").join(", ");N=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${w} IN (${g})`,u)}let R=new Map;for(let g of N)R.set(g[w],g);let y=new Map;for(let g of a){let p=g[i.pivotFkParent];if(!y.has(p))y.set(p,[]);y.get(p).push(g)}let b=new Set([i.pivotFkParent,i.pivotFkRelated]);for(let g of t){let p=g.get(r),D=(y.get(p)||[]).map((J)=>{let B=R.get(J[i.pivotFkRelated]);if(!B)return null;let W=new Xe(h,B),v={};for(let[x,C]of Object.entries(J))if(!b.has(x))v[x]=C;return W.pivot=v,W}).filter((J)=>J!==null);g.setRelation(e,D)}}if(i.type==="hasManyThrough"||i.type==="hasOneThrough"){let o=Ci(t,r);if(o.length===0)return;let l=i.throughLocalKey||"id",a=o.map(()=>"?").join(", "),c=await n.all(`SELECT ${l}, ${i.throughForeignKey} FROM ${i.throughTable} WHERE ${i.throughForeignKey} IN (${a})`,o);if(c.length===0){for(let b of t)b.setRelation(e,i.type==="hasManyThrough"?[]:null);return}let u=new Map;for(let b of c)u.set(b[l],b[i.throughForeignKey]);let m=[...new Set(c.map((b)=>b[l]))],h=m.map(()=>"?").join(", "),w=await n.all(`SELECT * FROM ${i.relatedTable} WHERE ${i.targetForeignKey} IN (${h})`,m),N=et(i.relatedModelName),R=N?.getDefinition?.()||N?.definition||this._definition,y=new Map;for(let b of w){let g=u.get(b[i.targetForeignKey]);if(g==null)continue;if(!y.has(g))y.set(g,[]);y.get(g).push(new Xe(R,b))}for(let b of t){let g=y.get(b.get(r))||[];b.setRelation(e,i.type==="hasManyThrough"?g:g[0]??null)}}}async get(){let e=De(),{sql:t,params:n}=this.buildQuery(),s=(await e.all(t,n)).map((i)=>new Xe(this._definition,i));if(this._withRelations.length>0)await this.eagerLoadRelations(s);return s}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let e=await this.first();if(!e)throw Error(`No ${this._definition.name} found`);return e}async last(){let e=this._definition.primaryKey||"id";return this._orderBy=[{column:e,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let e=De(),t=[],n=`SELECT COUNT(*) as count FROM ${this._definition.table}`,r=this.composeWhere(t);if(r)n+=` WHERE ${r}`;let s=await e.get(n,t);return Number(s?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let e=await this.get();if(e.length===0)throw Error(`No ${this._definition.name} found`);if(e.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return e[0]}async increment(e,t=1){Mt(e,"increment(column)"),this.assertNoUnappliedClauses("increment");let n=De(),r=[t],s=gt(e),i=`UPDATE ${this._definition.table} SET ${s} = ${s} + ?`;if(on(this._definition))i+=", updated_at = ?",r.push(sn());let o=this.composeWhere(r);if(o)i+=` WHERE ${o}`;return(await n.run(i,r)).changes}decrement(e,t=1){return this.increment(e,-t)}async chunk(e,t){let n=0;while(!0){let r=new de(this._definition);r._wheres=[...this._wheres],r._orderBy=[...this._orderBy],r._select=[...this._select],r._withRelations=[...this._withRelations],r._trashed=this._trashed,r._limit=e,r._offset=n*e;let s=await r.get();if(s.length===0)break;if(await t(s)===!1)break;if(s.length<e)break;n++}}async paginate(e=1,t=15){if(typeof e==="object"&&e!==null){let i=e;t=i.perPage??15,e=i.page??1}let n=await this.count(),r=Math.ceil(n/t);this._limit=t,this._offset=(e-1)*t;let s=await this.get();return{data:s,total:n,page:e,perPage:t,lastPage:r,hasMorePages:e<r,isEmpty:s.length===0,from:s.length>0?(e-1)*t+1:null,to:s.length>0?(e-1)*t+s.length:null,meta:{perPage:t,page:e,total:n,lastPage:r}}}async pluck(e){Mt(e,"pluck(column)");let t=De(),n=[],r=gt(e),s=`SELECT ${r} FROM ${this._definition.table}`,i=this.composeWhere(n);if(i)s+=` WHERE ${i}`;if(this._orderBy.length>0)s+=` ORDER BY ${this._orderBy.map((l)=>`${gt(l.column)} ${l.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)s+=` LIMIT ${this._limit}`;if(this._offset!==void 0)s+=` OFFSET ${this._offset}`;return(await t.all(s,n)).map((l)=>l[r])}async aggregate(e,t){Mt(t,`${e}(column)`);let n=De(),r=[],s=`SELECT ${e}(${gt(t)}) as v FROM ${this._definition.table}`,i=this.composeWhere(r);if(i)s+=` WHERE ${i}`;let l=(await n.get(s,r))?.v;if(l==null)return null;if(typeof l==="string"){let a=Number(l);return l.trim()!==""&&!Number.isNaN(a)?a:l}return l}max(e){return this.aggregate("MAX",e)}min(e){return this.aggregate("MIN",e)}async avg(e){return Number(await this.aggregate("AVG",e)??0)||0}async sum(e){return Number(await this.aggregate("SUM",e)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let e=De(),t=[],n=`DELETE FROM ${this._definition.table}`,r=this.composeWhere(t);if(r)n+=` WHERE ${r}`;return(await e.run(n,t)).changes}async update(e){this.assertNoUnappliedClauses("update");let t=De(),n=Object.entries(e),r=n.map(([l])=>`${gt(l)} = ?`).join(", "),s=n.map(([,l])=>l);if(on(this._definition))s.push(sn());let i=`UPDATE ${this._definition.table} SET ${r}${on(this._definition)?", updated_at = ?":""}`,o=this.composeWhere(s);if(o)i+=` WHERE ${o}`;return(await t.run(i,s)).changes}}function lg(e){let t={query:()=>new de(e),where(n,r,s){return new de(e).where(n,r,s)},orWhere(n,r,s){return new de(e).orWhere(n,r,s)},whereIn(n,r){return new de(e).whereIn(n,r)},whereNotIn(n,r){return new de(e).whereNotIn(n,r)},whereNull(n){return new de(e).whereNull(n)},whereNotNull(n){return new de(e).whereNotNull(n)},whereLike(n,r){return new de(e).whereLike(n,r)},orderBy(n,r="asc"){return new de(e).orderBy(n,r)},orderByDesc(n){return new de(e).orderByDesc(n)},select(...n){return new de(e).select(...n)},with(...n){return new de(e).with(...n)},limit:(n)=>new de(e).limit(n),take:(n)=>new de(e).take(n),skip:(n)=>new de(e).skip(n),withTrashed:()=>new de(e).withTrashed(),onlyTrashed:()=>new de(e).onlyTrashed(),async find(n){let r=De(),s=e.primaryKey||"id",i=vn(e)?` AND ${Vt} IS NULL`:"",o=await r.get(`SELECT * FROM ${e.table} WHERE ${s} = ?${i}`,[n]);return o?new Xe(e,o):void 0},async findOrFail(n){let r=await t.find(n);if(!r)throw Error(`${e.name} with id ${n} not found`);return r},async findMany(n){let r=De(),s=e.primaryKey||"id",i=vn(e)?` AND ${Vt} IS NULL`:"";return(await r.all(`SELECT * FROM ${e.table} WHERE ${s} IN (${n.map(()=>"?").join(", ")})${i}`,n)).map((l)=>new Xe(e,l))},all:()=>new de(e).get(),first:()=>new de(e).first(),firstOrFail:()=>new de(e).firstOrFail(),last:()=>new de(e).last(),count:()=>new de(e).count(),exists:()=>new de(e).exists(),doesntExist:()=>new de(e).doesntExist(),paginate:(n,r)=>new de(e).paginate(n,r),whereBetween(n,r){return new de(e).whereBetween(n,r)},whereNotBetween(n,r){return new de(e).whereNotBetween(n,r)},async create(n){let r=new Xe(e,n);return await r.save(),r},async createMany(n){let r=[];for(let s of n)r.push(await this.create(s));return r},async updateOrCreate(n,r){let s=new de(e);for(let[o,l]of Object.entries(n))s=s.where(o,l);let i=await s.first();if(i)return await i.update(r),i;return this.create({...n,...r})},async firstOrCreate(n,r){let s=new de(e);for(let[o,l]of Object.entries(n))s=s.where(o,l);return await s.first()||this.create({...n,...r})},async destroy(n){let r=De(),s=e.primaryKey||"id";return(await r.run(`DELETE FROM ${e.table} WHERE ${s} = ?`,[n])).changes>0},remove(n){return this.destroy(n)},async truncate(){await De().run(`DELETE FROM ${e.table}`,[])},getDefinition:()=>e,getTable:()=>e.table,make(n={}){return new Xe(e,n)},latest:(n="created_at")=>new de(e).orderByDesc(n),oldest:(n="created_at")=>new de(e).orderBy(n,"asc"),max:(n)=>new de(e).max(n),min:(n)=>new de(e).min(n),avg:(n)=>new de(e).avg(n),sum:(n)=>new de(e).sum(n),pluck(n){return new de(e).pluck(n)}};return new Proxy(t,{get(n,r){if(typeof r==="string"&&r.startsWith("where")&&r.length>5){let s=r.slice(5),i=s.charAt(0).toLowerCase()+s.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(o)=>new de(e).where(i,o)}return Reflect.get(n,r)}})}function Il(e){let t=lg(e);if(e?.name)eg(e.name,t);return t}async function dw(e){let t=De(),n=$e(e.primaryKey||"id"),r=[],s=new Set([n]);if(r.push(e.autoIncrement!==!1?`${n} INTEGER PRIMARY KEY AUTOINCREMENT`:`${n} INTEGER PRIMARY KEY`),e.traits?.useUuid)r.push("uuid TEXT UNIQUE"),s.add("uuid");for(let[i,o]of Object.entries(e.attributes)){let l=$e(i);if(s.has(l))continue;s.add(l);let a=Pa(o.type),c=Zr(a);if(l.endsWith("_id")&&(a===void 0||$n(a)))c="INTEGER";let u=`${l} ${c}`;if(o.unique)u+=" UNIQUE";if(typeof o.foreignKey==="object"&&o.foreignKey!==null){let m=o.foreignKey;if(u+=` REFERENCES ${m.table}(${m.column??"id"})`,m.onDelete)u+=` ON DELETE ${m.onDelete.toUpperCase()}`;if(m.onUpdate)u+=` ON UPDATE ${m.onUpdate.toUpperCase()}`}r.push(u)}for(let i of Rn(e.belongsTo)){let o=i.foreignKey??`${$e(i.model)}_id`;if(s.has(o))continue;s.add(o),r.push(`${o} INTEGER`)}if(on(e))for(let i of["created_at","updated_at"]){if(s.has(i))continue;s.add(i),r.push(`${i} TEXT`)}if(vn(e)&&!s.has("deleted_at"))s.add("deleted_at"),r.push("deleted_at TEXT");await t.run(`CREATE TABLE IF NOT EXISTS ${e.table} (${r.join(", ")})`,[])}async function fw(e,t,n){let r=De(),s=e.traits?.useSeeder,i=t??(typeof s==="object"&&s?s.count:10);if(!n)try{let o=await import("./chunk-1nqz3kbp.js");n=Sl(o.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let o=0;o<i;o++){let l={};for(let[c,u]of Object.entries(e.attributes))if(u.factory)l[$e(c)]=u.factory(n);if(on(e)){let c=sn();l.created_at=c,l.updated_at=c}if(e.traits?.useUuid)l.uuid=crypto.randomUUID();let a=Object.keys(l);await r.run(`INSERT INTO ${e.table} (${a.join(", ")}) VALUES (${a.map(()=>"?").join(", ")})`,Object.values(l))}}var Al,fs=null,Ni,ms,tg=500,Ot=null,ps=!1,Dt=null,kn=null,gs=null,ys=null,Vt="deleted_at",ki="__btm_rel__",Rl,kl,Cl,Cn,ig=1000,hs,og;var Mi=ut(()=>{mi();Me();Ft();Hr();Ri();ds();Wt();ns();Al=/^[A-Z_][A-Z0-9_]*$/i;Ni=new Map;ms=new Map;Rl=new WeakMap;kl=new Map,Cl=new Map,Cn=new Map;hs=["hasMany","hasOne","belongsTo","belongsToMany"],og=[...hs,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var Ll={};cg(Ll,{clearModelRegistry:()=>Ql,defineModel:()=>Vl,getAllModels:()=>jl,getModel:()=>ql,getModelRegistry:()=>Wl,hasModel:()=>Ul,registerBrowserModels:()=>dg,registerModel:()=>Oi});function ql(e){return An.get(e)}function jl(){return[...An.values()]}function Wl(){return Object.fromEntries(An)}function Ul(e){return An.has(e)}function Ql(){An.clear(),Ml()}function Oi(e,t){return An.set(e,t),t}function ug(){return typeof window<"u"&&typeof document<"u"}function Vl(e){let t;if(ug())t=Kl(e);else{let n=Il(e);t=Object.assign(n,{definition:e,getDefinition:()=>e,getTable:()=>e.table,getName:()=>e.name})}return Oi(e.name,t),t}function dg(e){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...e}}var An;var tr=ut(()=>{Fl();Mi();An=new Map});Me();Ft();import{existsSync as _t,mkdirSync as Ec,mkdtempSync as Lg,readdirSync as xc,readFileSync as sr,rmSync as Rc,unlinkSync as ji,writeFileSync as kc}from"fs";import{tmpdir as Kg}from"os";import{join as tt}from"path";import Wi from"process";Me();function hf(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(36).padStart(7,"0").slice(-7)}function pf(e,t=63){if(e.length<=t)return e;let n=`_${hf(e)}`;return e.slice(0,t-n.length)+n}function ft(e,t){let n=`${e}_`,r=t.startsWith(n)?t:`${n}${t}`;return pf(r)}class Ie{quoteIdentifier(e){return`\`${e.replace(/`/g,"``")}\``}getColumnType(e){switch(e.type){case"string":return`varchar(${e.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if(e.enumValues&&e.enumValues.length>0)return`ENUM(${e.enumValues.map((n)=>`'${n.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(e){return this.getColumnType(e)}getAutoIncrementClause(e){if(e.isPrimaryKey&&(e.type==="integer"||e.type==="bigint"))return"auto_increment";return""}getDefaultValue(e){if(!e.hasDefault||e.defaultValue===void 0)return"";let t=e.defaultValue;if(typeof t==="string"){let n=t.toUpperCase();if(n==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(n))return`default ${n}`;let s=`'${t.replace(/'/g,"''")}'`;if(e.type==="text"||e.type==="json"||e.type==="enum"&&!e.enumValues?.length)return`default (${s})`;return`default ${s}`}else if(typeof t==="number"||typeof t==="bigint")return`default ${t}`;else if(typeof t==="boolean")return`default ${t?1:0}`;else if(t instanceof Date)return`default '${t.toISOString()}'`;return""}createEnumType(e,t){return""}foreignKeyClauses(e){return e.columns.filter((t)=>t.references).map((t)=>{let n=t.references,r=`${e.table}_${t.name}_fk`,s=`CONSTRAINT ${this.quoteIdentifier(r)} FOREIGN KEY (${this.quoteIdentifier(t.name)}) REFERENCES ${this.quoteIdentifier(n.table)}(${this.quoteIdentifier(n.column)})`;if(n.onDelete)s+=` ON DELETE ${n.onDelete.toUpperCase()}`;if(n.onUpdate)s+=` ON UPDATE ${n.onUpdate.toUpperCase()}`;return s})}createTable(e){let t=[...e.columns.map((n)=>this.renderColumn(n)),...this.foreignKeyClauses(e)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(e.table)} (
66
66
  ${t.join(`,
67
67
  `)}
68
68
  ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(e){let t=this.getColumnType(e).toLowerCase();if(t.includes("text")||t.includes("blob")||t==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let n=t.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(n!==void 0)return{bytes:Number(n)*Ie.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(e,t,n){let r=t.columns.map((i)=>{let o=n?.find((c)=>c.name===i),l=o?this.keyPartWidth(o):{bytes:0,indexableWhole:!0},a=!l.indexableWhole;return{name:i,prefixed:a,bytes:a?Ie.KEY_PREFIX_CHARACTERS*Ie.BYTES_PER_CHARACTER:l.bytes,narrowable:!l.indexableWhole||l.bytes>Ie.KEY_PREFIX_CHARACTERS*Ie.BYTES_PER_CHARACTER}}),s=()=>r.reduce((i,o)=>i+o.bytes,0);while(s()>Ie.MAX_KEY_BYTES){let i=r.filter((o)=>o.narrowable&&!o.prefixed).sort((o,l)=>l.bytes-o.bytes)[0];if(!i)throw Error(`[migrations] Index '${t.name}' on table '${e}' needs ${s()} bytes of key, over MySQL's ${Ie.MAX_KEY_BYTES}. Every column in it is already at its ${Ie.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);i.prefixed=!0,i.bytes=Ie.KEY_PREFIX_CHARACTERS*Ie.BYTES_PER_CHARACTER}return r.map((i)=>i.prefixed?`${this.quoteIdentifier(i.name)}(${Ie.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(i.name))}createIndex(e,t,n){if(t.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${t.name}' on table '${e}' uses WHERE clause: ${t.where}`);let r=t.type==="unique"?"UNIQUE ":"",s=ft(e,t.name),i=this.keyParts(e,t,n).join(", ");return`CREATE ${r}INDEX ${this.quoteIdentifier(s)} ON ${this.quoteIdentifier(e)} (${i});`}addForeignKey(e,t,n,r,s,i,o=[]){let l=`${e}_${t}_fk`,a=`ALTER TABLE ${this.quoteIdentifier(e)} ADD CONSTRAINT ${this.quoteIdentifier(l)} FOREIGN KEY (${this.quoteIdentifier(t)}) REFERENCES ${this.quoteIdentifier(n)}(${this.quoteIdentifier(r)})`;if(s)a+=` ON DELETE ${s.toUpperCase()}`;if(i)a+=` ON UPDATE ${i.toUpperCase()}`;let c=[...new Set(o)].map((u)=>`ALTER TABLE ${this.quoteIdentifier(e)} DROP FOREIGN KEY ${this.quoteIdentifier(u)};`).join(`
@@ -88,7 +88,7 @@ ${a};`:`${a};`}addColumn(e,t){let n=this.getColumnType(t),r=[this.quoteIdentifie
88
88
  );`}tableKindSuffix(e){switch(e){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex(e,t,n){if(t.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${t.name}' on table '${e}' uses WHERE clause: ${t.where}`);return super.createIndex(e,t,n)}}class Xr extends Ie{sharded;constructor(e=!0){super();this.sharded=e}getAutoIncrementClause(e){return this.sharded?"":super.getAutoIncrementClause(e)}renderColumn(e){if(!this.sharded||!e.references)return super.renderColumn(e);let{references:t,...n}=e;return super.renderColumn(n)}foreignKeyClauses(e){return this.sharded?[]:super.foreignKeyClauses(e)}createTable(e){return super.createTable(e)}addForeignKey(...e){return this.sharded?"":super.addForeignKey(...e)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
89
89
  migration VARCHAR(255) NOT NULL PRIMARY KEY,
90
90
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
91
- )`}}ui();class es{quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}getColumnType(e){if(e.name.endsWith("_id")&&$n(e.type))return"INTEGER";if(e.type==="enum"){if(e.enumValues&&e.enumValues.length>0){let t=e.enumValues.map((n)=>`'${n.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(e.name)} IN (${t}))`}return"TEXT"}return Zr(e.type)}getPrimaryKeyType(e){return this.getColumnType(e)}getAutoIncrementClause(e){if(e.isPrimaryKey&&(e.type==="integer"||e.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(e){if(!e.hasDefault||e.defaultValue===void 0)return"";let t=e.defaultValue;if(typeof t==="string"){if(t.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(t.toUpperCase()))return`default ${t.toUpperCase()}`;return`default '${t.replace(/'/g,"''")}'`}else if(typeof t==="number"||typeof t==="bigint")return`default ${t}`;else if(typeof t==="boolean")return`default ${t?1:0}`;else if(t instanceof Date)return`default '${t.toISOString()}'`;return""}createEnumType(e,t){return""}createTable(e){let t=e.columns.map((n)=>this.renderColumn(n)).join(`,
91
+ )`}}mi();class es{quoteIdentifier(e){return`"${e.replace(/"/g,'""')}"`}getColumnType(e){if(e.name.endsWith("_id")&&$n(e.type))return"INTEGER";if(e.type==="enum"){if(e.enumValues&&e.enumValues.length>0){let t=e.enumValues.map((n)=>`'${n.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(e.name)} IN (${t}))`}return"TEXT"}return Zr(e.type)}getPrimaryKeyType(e){return this.getColumnType(e)}getAutoIncrementClause(e){if(e.isPrimaryKey&&(e.type==="integer"||e.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(e){if(!e.hasDefault||e.defaultValue===void 0)return"";let t=e.defaultValue;if(typeof t==="string"){if(t.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(t.toUpperCase()))return`default ${t.toUpperCase()}`;return`default '${t.replace(/'/g,"''")}'`}else if(typeof t==="number"||typeof t==="bigint")return`default ${t}`;else if(typeof t==="boolean")return`default ${t?1:0}`;else if(t instanceof Date)return`default '${t.toISOString()}'`;return""}createEnumType(e,t){return""}createTable(e){let t=e.columns.map((n)=>this.renderColumn(n)).join(`,
92
92
  `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(e.table)} (
93
93
  ${t}
94
94
  );`}createIndex(e,t){let n=t.type==="unique"?"UNIQUE ":"",r=ft(e,t.name),s=t.columns.map((o)=>this.quoteIdentifier(o)).join(", "),i=t.where?` WHERE ${t.where}`:"";return`CREATE ${n}INDEX IF NOT EXISTS ${this.quoteIdentifier(r)} ON ${this.quoteIdentifier(e)} (${s})${i};`}addForeignKey(e,t,n,r,s,i){return""}addColumn(e,t){let n=this.getColumnType(t),r=[this.quoteIdentifier(t.name),n];if(!t.isNullable&&!t.isPrimaryKey)r.push("not null");let s=this.getDefaultValue(t);if(s)r.push(s);return`ALTER TABLE ${this.quoteIdentifier(e)} ADD COLUMN ${r.join(" ")};`}modifyColumn(e,t){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(e)}.${this.quoteIdentifier(t.name)}`}renameColumn(e,t,n){return`ALTER TABLE ${this.quoteIdentifier(e)} RENAME COLUMN ${this.quoteIdentifier(t)} TO ${this.quoteIdentifier(n)};`}renameTable(e,t){return`ALTER TABLE ${this.quoteIdentifier(e)} RENAME TO ${this.quoteIdentifier(t)};`}rebuildTable(e){let{target:t,tempName:n,columnSource:r}=e,s=(c)=>this.quoteIdentifier(c),i=t.columns.map((c)=>this.renderColumn(c)).join(`,
@@ -99,7 +99,7 @@ ${a};`:`${a};`}addColumn(e,t){let n=this.getColumnType(t),r=[this.quoteIdentifie
99
99
  id INTEGER PRIMARY KEY AUTOINCREMENT,
100
100
  migration TEXT NOT NULL UNIQUE,
101
101
  executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
102
- )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(e,t){return`json_extract(${e}, '$.' || ${t})`}dateBucket(e,t,n=0){let r=n===0?e:`datetime(${e}, '${n>=0?"+":"-"}${Math.abs(n)} hours')`;switch(t){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${r})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${r}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${r})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${r})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${r})`}}booleanLiteral(e){return e?"TRUE":"FALSE"}renderColumn(e){let t=this.getColumnType(e),n=[this.quoteIdentifier(e.name),t];if(e.isPrimaryKey){n.push("PRIMARY KEY");let s=this.getAutoIncrementClause(e);if(s)n.push(s)}if(!e.isNullable&&!e.isPrimaryKey)n.push("not null");let r=this.getDefaultValue(e);if(r)n.push(r);if(e.references){if(n.push(`REFERENCES ${this.quoteIdentifier(e.references.table)}(${this.quoteIdentifier(e.references.column)})`),e.references.onDelete)n.push(`ON DELETE ${e.references.onDelete.toUpperCase()}`);if(e.references.onUpdate)n.push(`ON UPDATE ${e.references.onUpdate.toUpperCase()}`)}return n.join(" ")}}function Tt(e,t={}){switch(e){case"postgres":return new Gr;case"mysql":return new Ie;case"singlestore":return new Yr;case"vitess":return new Xr(t.vitessSharded??_.vitess?.sharded??!0);case"sqlite":return new es;default:throw Error(`Unsupported dialect: ${e}`)}}Kt();async function pf(e={}){let t=e.iterations||1000,n=e.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${t}`),console.log(`-- Operations: ${n.join(", ")}`),console.log();let r=ie();console.log("-- Setting up test table...");try{await te.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await te.unsafe(`
102
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(e,t){return`json_extract(${e}, '$.' || ${t})`}dateBucket(e,t,n=0){let r=n===0?e:`datetime(${e}, '${n>=0?"+":"-"}${Math.abs(n)} hours')`;switch(t){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${r})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${r}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${r})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${r})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${r})`}}booleanLiteral(e){return e?"TRUE":"FALSE"}renderColumn(e){let t=this.getColumnType(e),n=[this.quoteIdentifier(e.name),t];if(e.isPrimaryKey){n.push("PRIMARY KEY");let s=this.getAutoIncrementClause(e);if(s)n.push(s)}if(!e.isNullable&&!e.isPrimaryKey)n.push("not null");let r=this.getDefaultValue(e);if(r)n.push(r);if(e.references){if(n.push(`REFERENCES ${this.quoteIdentifier(e.references.table)}(${this.quoteIdentifier(e.references.column)})`),e.references.onDelete)n.push(`ON DELETE ${e.references.onDelete.toUpperCase()}`);if(e.references.onUpdate)n.push(`ON UPDATE ${e.references.onUpdate.toUpperCase()}`)}return n.join(" ")}}function Tt(e,t={}){switch(e){case"postgres":return new Gr;case"mysql":return new Ie;case"singlestore":return new Yr;case"vitess":return new Xr(t.vitessSharded??_.vitess?.sharded??!0);case"sqlite":return new es;default:throw Error(`Unsupported dialect: ${e}`)}}Ft();async function bf(e={}){let t=e.iterations||1000,n=e.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${t}`),console.log(`-- Operations: ${n.join(", ")}`),console.log();let r=ie();console.log("-- Setting up test table...");try{await te.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await te.unsafe(`
103
103
  CREATE TABLE bench_users (
104
104
  id INTEGER PRIMARY KEY AUTOINCREMENT,
105
105
  name TEXT NOT NULL,
@@ -110,7 +110,7 @@ ${a};`:`${a};`}addColumn(e,t){let n=this.getColumnType(t),r=[this.quoteIdentifie
110
110
  `).execute();for(let o=0;o<100;o++)await te.unsafe(`
111
111
  INSERT INTO bench_users (name, email, created_at)
112
112
  VALUES (?, ?, ?)
113
- `,[`User ${o}`,`user${o}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(o){throw console.error("-- Failed to setup test table:",o),o}let s=[];if(n.includes("select")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.selectFrom("bench_users").where({active:1}).limit(10).execute(),o.push(performance.now()-a)}s.push({operation:"SELECT with WHERE + LIMIT",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("select")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.selectFrom("bench_users").where({id:1}).first(),o.push(performance.now()-a)}s.push({operation:"SELECT by ID (first)",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("count")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.selectFrom("bench_users").count(),o.push(performance.now()-a)}s.push({operation:"COUNT",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("insert")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.insertInto("bench_users").values({name:`Bench User ${l}`,email:`bench${l}@example.com`,created_at:new Date().toISOString()}).execute(),o.push(performance.now()-a)}s.push({operation:"INSERT",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("update")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.updateTable("bench_users").set({active:0}).where({id:1}).execute(),o.push(performance.now()-a)}s.push({operation:"UPDATE by ID",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("delete")){let o=[],l=[];for(let a=0;a<t;a++){let c=await r.insertInto("bench_users").values({name:"To Delete",email:`delete${a}@example.com`,created_at:new Date().toISOString()}).execute();l.push(c)}for(let a=0;a<t;a++){let c=performance.now();await r.deleteFrom("bench_users").where({id:l[a]}).execute(),o.push(performance.now()-c)}s.push({operation:"DELETE by ID",avgTime:o.reduce((a,c)=>a+c,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}console.log("-- Benchmark Results"),console.log();let i=Math.max(...s.map((o)=>o.operation.length));console.log("Operation".padEnd(i+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(i+2+12+12+12+12));for(let o of s){let l=o.operation.padEnd(i+2),a=o.avgTime.toFixed(3).padStart(12),c=o.minTime.toFixed(3).padStart(12),u=o.maxTime.toFixed(3).padStart(12),m=(1000/o.avgTime).toFixed(0).padStart(12);console.log(`${l}${a}${c}${u}${m}`)}console.log();try{await te.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(o){console.error("-- Warning: Failed to cleanup test table:",o)}}Me();Kt();Me();jt();function wf(e){return qt(_.relations?.singularizeStrategy)(e)}function en(e,t,n,r={}){let s=r.singularize??wf,o=e.relations?.[t]?.belongsToMany?.[n];if(o==null)return null;let l=typeof o==="object",a=l?o:null,c=l?a.model:o,u=e.modelToTable[c]||c,m,h;if(a?.table)m=a.table;else if(a?.through){if(h=a.through,m=e.modelToTable[a.through],!m)throw Error(`[query-builder] belongsToMany relation '${n}' on '${t}' references unknown through model '${a.through}'. Make sure '${a.through}' is registered via defineModels({...}).`)}else{let g=s(t),p=s(u);m=[g,p].sort().join("_")}let w=a?.foreignKey??`${s(t)}_id`,N=a?.relatedKey??`${s(u)}_id`,R={};if(a?.pivot?.columns)Object.assign(R,a.pivot.columns);if(h&&r.models){let g=r.models[h],p=g?.definition??g?.getDefinition?.()??g,E=p?.attributes??{};for(let[D,J]of Object.entries(E)){if(D===w||D===N||D===(p?.primaryKey??"id"))continue;R[D]={default:J?.default,nullable:J?.nullable,validation:J?.validation}}}let y=Boolean(a?.pivot?.timestamps),b=Object.keys(R);return{pivotTable:m,fkParent:w,fkRelated:N,pivotColumns:b,pivotColumnDefs:R,pivotModelName:h,timestamps:y,relatedModelName:c,relatedTable:u,hasConfig:l}}function*Op(e,t={}){let n=e.relations;if(!n)return;for(let[r,s]of Object.entries(n)){let i=s?.belongsToMany;if(!i)continue;for(let o of Object.keys(i)){let l=en(e,r,o,t);if(l)yield{parentTable:r,relationKey:o,resolved:l}}}}jt();ns();function wt(e){return typeof e==="object"&&e!==null&&"raw"in e&&typeof e.raw==="string"}function fi(e,t,n){if(Array.isArray(t)){let s=ve(t.length,n.length+1),i=Ge(e,t,!1,s);return n.push(...t),i}let r=`${e} = ${Z(n.length+1)}`;return n.push(t),r}function Vn(e){return typeof e==="object"&&e!==null&&"sql"in e&&typeof e.sql==="string"&&(!("parameters"in e)||Array.isArray(e.parameters))}function Jn(e,t){let n=e.parameters??[];if(_.dialect!=="postgres"||n.length===0)return{text:e.sql,parameters:n};let r=0,s=e.sql.replace(/\?/g,(i)=>{if(r>=n.length)return i;return Z(t+r++)});if(r!==n.length)throw TypeError(`[query-builder] SQL expression declares ${n.length} parameters but contains only ${r} placeholders`);return{text:s,parameters:n}}function qp(e,...t){if(typeof e==="string")return{raw:e};let n=e[0];for(let r=0;r<t.length;r++)n+=vt(t[r])+e[r+1];return{raw:n}}function Ye(e){return ne(_.dialect)?`\`${e.replace(/`/g,"``")}\``:`"${e.replace(/"/g,'""')}"`}function rs(e,t=1){let n=Object.keys(e[0]??{}),r=[],s=t,i=e.map((o)=>`(${n.map((a)=>(r.push(o[a]),Z(s++))).join(", ")})`);return{colsSql:n.map(Ye).join(", "),valuesSql:i.join(", "),params:r,nextIndex:s}}function Hn(e){return Boolean(e&&(e.onSlowQuery||e.slowQueryThresholdMs!=null&&e.slowQueryThresholdMs>=0))}function ot(e,t=_.dialect){if(!ne(t))return e;let n=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(e.trim());if(!n)return e;let[,r,s,i]=n,o=s?`\`${r}\`.\`${s}\``:`\`${r}\``;return i?`${o} AS \`${i}\``:o}function Sf(e,t=_.dialect){if(!ne(t)||e===null||e===void 0)return e;if(typeof e==="string"){let n=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(e);if(!n)return e;let[,r,s]=n;return`${r} ${s.length===5?`${s}:00`:s}`}if(!(e instanceof Date)||Number.isNaN(e.getTime()))return e;return e.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function Ia(e){if(typeof e==="string")return ot(e);if(wt(e))return e.raw;if(e&&typeof e==="object"){let t=e;if(typeof t.raw==="function")return String(t.raw());if(typeof t.sql==="string")return t.sql;let n=String(e);if(n!=="[object Object]")return n}throw TypeError(`[query-builder] select(): unsupported column ${String(e)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function $f(e){let t=/\(|\)|\bORDER\s+BY\b/gi,n=0,r;while(r=t.exec(e))if(r[0]==="(")n++;else if(r[0]===")")n=Math.max(0,n-1);else if(n===0)return!0;return!1}var he={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},La=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function G(e,t){if(!he.IDENTIFIER.test(e)){let n=t?` in ${t}`:"";throw Error(`[query-builder] Invalid identifier${n}: '${e}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function Oe(e,t){if(typeof e!=="string")throw TypeError(`[query-builder] ${t}: operator must be a string, got ${typeof e}`);let n=e.toLowerCase();if(!La.has(n))throw TypeError(`[query-builder] ${t}: refusing to use '${e}' as a SQL operator \u2014 not in the allowed set (${[...La].join(", ")})`);return e}function it(e,t){if(typeof e!=="string"||e.length===0)throw TypeError(`[query-builder] ${t}: identifier must be a non-empty string, got ${typeof e}`);if(e.length>129)throw TypeError(`[query-builder] ${t}: identifier '${e}' too long`);let n=e.split(".");if(n.length>2)throw TypeError(`[query-builder] ${t}: identifier '${e}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let r of n)if(!/^[A-Z_][A-Z0-9_]*$/i.test(r))throw TypeError(`[query-builder] ${t}: identifier segment '${r}' contains characters outside [A-Za-z0-9_]`)}function nn(e,t){if(typeof e==="string")return Ef(t),e;if(e===null||e===void 0)throw TypeError(`[query-builder] ${t}: fragment must be a SqlFragment, got ${e}`);if(wt(e))return e.raw;if(typeof e==="object"){let n=e;if(typeof n.raw==="string")return n.raw;if(typeof n.raw==="function"){let s=n.raw();if(typeof s==="string")return s}if(typeof n.sql==="string")return n.sql;let r=String(e);if(r!=="[object Object]"&&r!=="[object Promise]")return r}throw TypeError(`[query-builder] ${t}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}var Ka=new Set;function Ef(e){if(Ka.has(e))return;Ka.add(e),console.warn(`[query-builder] ${e}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function xf(e,t=_.dialect){return ne(t)?e.replace(/\\/g,"\\\\").replace(/'/g,"''"):e.replace(/'/g,"''")}function vt(e){if(e===null)return"NULL";if(typeof e==="number"&&Number.isFinite(e))return String(e);if(typeof e==="boolean")return e?"1":"0";if(typeof e==="string")return`'${xf(e)}'`;if(e instanceof Date)return`'${e.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof e}`)}function Rf(e,t){let n=Array.isArray(e)?e:e?[e]:[],r=[];if(n.length)r.push(`PARTITION BY ${n.join(", ")}`);if(t&&t.length)r.push(`ORDER BY ${t.map(([s,i])=>`${s} ${i==="desc"?"DESC":"ASC"}`).join(", ")}`);return r.length?`OVER (${r.join(" ")})`:"OVER ()"}class Fa{cache=new Map;maxSize=100;get(e){let t=this.cache.get(e);if(!t)return null;if(Date.now()>t.expiresAt)return this.cache.delete(e),null;return this.cache.delete(e),this.cache.set(e,t),t.data}set(e,t,n){if(this.cache.has(e))this.cache.delete(e);if(this.cache.size>=this.maxSize){let r=Date.now(),s=!1;for(let[i,o]of this.cache)if(r>o.expiresAt){if(this.cache.delete(i),s=!0,this.cache.size<this.maxSize)break}if(!s){let i=this.cache.keys().next().value;if(i!==void 0)this.cache.delete(i)}}this.cache.set(e,{data:t,expiresAt:Date.now()+n})}clear(){this.cache.clear()}setMaxSize(e){this.maxSize=Math.max(0,Math.floor(e));while(this.cache.size>this.maxSize){let t=this.cache.keys().next().value;if(t===void 0)break;this.cache.delete(t)}}}var is=new Fa;function kf(e){let t=String(e?.message||"").toLowerCase();return t.includes("deadlock")||t.includes("serialization failure")||t.includes("could not serialize access")||t.includes("deadlock found when trying to get lock")||t.includes("lock wait timeout exceeded")||t.includes("database is locked")||t.includes("busy")}function Cf(e,t){if(!t||t.length===0)return!1;let n=e&&(e.code||e.sqlState||e.sqlstate);if(!n)return!1;return t.includes(n)}function vf(e){return new Promise((t)=>setTimeout(t,e))}var ss=new Map,Af=500,Nf=[{key:"GROUP_BY",pattern:/GROUP\s+BY\b/iy},{key:"ORDER_BY",pattern:/ORDER\s+BY\b/iy},{key:"HAVING",pattern:/HAVING\b/iy},{key:"OFFSET",pattern:/OFFSET\b/iy},{key:"LIMIT",pattern:/LIMIT\b/iy},{key:"WHERE",pattern:/WHERE\b/iy}],Mf=[{key:"tail",pattern:/GROUP\s+BY\b/iy},{key:"tail",pattern:/ORDER\s+BY\b/iy},{key:"tail",pattern:/HAVING\b/iy},{key:"tail",pattern:/LIMIT\b/iy},{key:"tail",pattern:/OFFSET\b/iy},{key:"tail",pattern:/WINDOW\b/iy},{key:"tail",pattern:/UNION\b/iy},{key:"tail",pattern:/INTERSECT\b/iy},{key:"tail",pattern:/EXCEPT\b/iy},{key:"tail",pattern:/FOR\s+UPDATE\b/iy},{key:"tail",pattern:/FOR\s+SHARE\b/iy},{key:"tail",pattern:/LOCK\s+IN\s+SHARE\s+MODE\b/iy}],Of=[{key:"cut",pattern:/GROUP\s+BY\b/iy},{key:"cut",pattern:/ORDER\s+BY\b/iy},{key:"cut",pattern:/WHERE\b/iy},{key:"cut",pattern:/HAVING\b/iy},{key:"cut",pattern:/LIMIT\b/iy},{key:"cut",pattern:/OFFSET\b/iy},{key:"cut",pattern:/UNION\b/iy}];function zn(e){let t=ss.get(e);if(t!==void 0)return t;let n=Bf(e);if(ss.size>=Af)ss.clear();return ss.set(e,n),n}function Bf(e){let t=ts(e,Nf);if(t.length<=1)return e;let n=e.slice(0,t[0].start).trimEnd(),r={};for(let o=0;o<t.length;o++){let l=t[o].start,a=o+1<t.length?t[o+1].start:e.length,c=e.slice(l,a).trim();if(!r[t[o].key])r[t[o].key]=[];r[t[o].key].push(c)}let i=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((o)=>r[o]).map((o)=>r[o].join(" ")).join(" ");return i?`${n} ${i}`:n}function Pf(e,t){let n=Math.max(1,t?.baseMs??50),r=Math.max(1,t?.factor??2),s=Math.max(n,t?.maxMs??2000),i=Math.min(s,n*r**Math.max(0,e-1));if(t?.jitter)i=Math.min(s,i*(0.9+Math.random()*0.2));return Math.floor(i)}function ie(e){let t=e?.sql??Lt(),n=e?.meta,r=e?.schema,s=(y,b)=>{let g=n?.temporalColumns?.[y];if(!g||g.length===0||!ne(_.dialect))return b;return b.map((p)=>{let E=null;for(let D of g){if(!(D in p))continue;let J=Sf(p[D]);if(J!==p[D])E=E??{...p},E[D]=J}return E??p})};function i(y){if(typeof y==="number")return y;let b=String(y),g=7;for(let p=0;p<b.length;p++)g=g*31+b.charCodeAt(p)|0;return Math.abs(g)}function o(){if(!e?.hooks)return _.hooks;return{..._.hooks,...e.hooks}}let l=new Map;function a(y){if(Array.isArray(y)){let[D,J,B]=y;G(D,"where(column)");let W=String(D);switch(J){case"in":if(Array.isArray(B)){let v=ve(B.length);return t.unsafe(`${W} IN (${v})`,B)}return t.unsafe(`${W} IN (${Z(1)})`,[B]);case"not in":if(Array.isArray(B)){let v=ve(B.length);return t.unsafe(`${W} NOT IN (${v})`,B)}return t.unsafe(`${W} NOT IN (${Z(1)})`,[B]);case"like":return t.unsafe(`${W} LIKE ${Z(1)}`,[B]);case"is":case"is not":{if(B!==null&&B!==void 0)throw TypeError(`[query-builder] where(..., '${J}', ?): operator '${J}' only accepts NULL/undefined as value, got ${typeof B} (${String(B)})`);return t.unsafe(`${W} IS ${J==="is not"?"NOT ":""}NULL`)}case"!=":return t.unsafe(`${W} <> ${Z(1)}`,[B]);case"<":case">":case"<=":case">=":case"=":return t.unsafe(`${W} ${J} ${Z(1)}`,[B]);default:throw TypeError(`[query-builder] where(..., '${String(J)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in y)return y.raw;let b=Object.keys(y);if(b.length===0)return t.unsafe("");let g=[],p=[],E=1;for(let D of b){G(D,"where(object key)");let J=y[D];if(Array.isArray(J)){let B=ve(J.length,E);g.push(`${D} IN (${B})`),p.push(...J),E+=J.length}else g.push(`${D} = ${Z(E++)}`),p.push(J)}return t.unsafe(g.join(" AND "),p)}function c(y,b,g){if(!g)return b;let p=a(g);return t`${b} WHERE ${p}`}function u(y){let b=_.debug?.captureText;if(_.debug)_.debug.captureText=!0;let g=String(y);if(_.debug)_.debug.captureText=b;return g}function m(y){if(!y||typeof y!=="object")return;if(Array.isArray(y.values))return y.values;if(Array.isArray(y.parameters))return y.parameters;if(Array.isArray(y.params))return y.params;return}function h(y,b,g){let p=o(),E=p?.slowQueryThresholdMs,D=E!=null&&E>=0,J=Boolean(p?.onSlowQuery||D),B=p&&(p.onQueryStart||p.onQueryEnd||p.onQueryError||p.startSpan||J),W=g?.timeoutMs&&g.timeoutMs>0||g?.signal;if(!B&&!W)return y.execute();let v=u(y),x=m(y),C=Date.now(),k;try{if(p?.onQueryStart?.({sql:v,params:x,kind:b}),p?.startSpan)k=p.startSpan({sql:v,params:x,kind:b})}catch{}let P=!1,q=(U,Y)=>{if(P)return;P=!0;let I=Date.now()-C;try{if(U)p?.onQueryError?.({sql:v,params:x,error:U,durationMs:I,kind:b});else if(p?.onQueryEnd?.({sql:v,params:x,durationMs:I,rowCount:Y,kind:b}),D&&I>=E)if(p?.onSlowQuery)p.onSlowQuery({sql:v,params:x,durationMs:I,kind:b});else console.warn(`[query-builder] slow query (${I}ms >= ${E}ms): ${v}`)}catch{}try{k?.end(U)}catch{}},H=y.execute(),M=[H],V;if(g?.timeoutMs&&g.timeoutMs>0){let U=new Promise((Y,I)=>{V=setTimeout(()=>{try{y.cancel?.()}catch{}let Q=Error(`Query timed out after ${g.timeoutMs}ms`);Q.code="EBQBTIMEOUT",I(Q)},g.timeoutMs)});M.push(U)}if(g?.signal){if(g.signal.aborted){try{y.cancel?.()}catch{}let Y=Error("Query aborted");return Y.code="EBQBABORT",q(Y),Promise.reject(Y)}let U=()=>{try{y.cancel?.()}catch{}};g.signal.addEventListener("abort",U,{once:!0}),H.finally(()=>{g.signal?.removeEventListener("abort",U)})}return Promise.race(M).then((U)=>{clearTimeout(V);let Y=Array.isArray(U)?U.length:typeof U==="number"?U:void 0;return q(void 0,Y),U}).catch((U)=>{throw clearTimeout(V),q(U),U})}function w(y){if(typeof y==="number")return Number.isFinite(y)?y:0;if(typeof y==="bigint")return Number(y);if(!y||typeof y!=="object")return 0;let b=y;for(let g of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(b[g]!==void 0&&b[g]!==null)return w(b[g]);if(Array.isArray(y))return y.reduce((g,p)=>g+w(p),0);return 0}function N(y,b){let g=b??u(y);return{sql:g,toString:()=>g,execute:()=>y.execute(),values:()=>y.values(),raw:()=>y.raw()}}function R(y,b){let g=t,p=b&&b.length>0?`SELECT ${b.join(", ")} FROM ${String(y)}`:`SELECT * FROM ${String(y)}`,E=[],D=[],J=!1,B=!1,W=!1,v=null,x=()=>{if(v===null){let d=zn(q());v=D.length>0?t.unsafe(d,D):t.unsafe(d)}return v},C=(d,f)=>{E.push({conn:d,sql:f}),v=null},k=(d,f)=>{C(d==="OR"?"OR":"AND",f)},P=(d)=>{let f=ts(d,Mf,1);return f.length>0?f[0].start:-1},q=(d)=>{let f=tn(d?[...E,d]:E);if(!f)return p;if(J)return`${p} ${B?"AND":"WHERE"} ${f}`;let T=P(p);return T>=0?`${p.slice(0,T)}WHERE ${f} ${p.slice(T)}`:`${p} WHERE ${f}`},H=(d,f)=>{let T=R(y);f(T);let S=T.__whereState?.();if(!S||!S.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let A=D.length,O=A>0&&_.dialect==="postgres"?S.body.replace(/\$(\d+)/g,(K,F)=>`$${Number(F)+A}`):S.body;D.push(...S.params),C(d,`(${O})`)},M=(d,f,T,S,A,O)=>{if(typeof S==="string"&&A!==void 0){G(String(S),`${T}(column)`),Oe(A,`${T}(operator)`);let K=D.length+1;return D.push(O),C(f,`${String(S)} ${String(A)} ${Z(K)}`),d}if(Array.isArray(S)){let[K,F,z]=S,L=String(K);G(L,`${T}(column)`);let j=Oe(F,`${T}(operator)`);if(j==="in"||j==="not in"){let X=Array.isArray(z)?z:[z],ae=ve(X.length,D.length+1),Ae=Ge(ot(L),X,j==="not in",ae);D.push(...X),C(f,Ae)}else{let X=D.length+1;D.push(z),C(f,`${L} ${j} ${Z(X)}`)}return d}if(typeof S==="function")return H(f,S),d;if(S&&typeof S==="object"&&!("raw"in S)){let K=[];for(let F of Object.keys(S)){G(F,`${T}(column)`);let z=S[F];if(Array.isArray(z)){let L=ve(z.length,D.length+1);K.push(Ge(ot(F),z,!1,L)),D.push(...z)}else{let L=D.length+1;K.push(`${F} = ${Z(L)}`),D.push(z)}}if(K.length>0)C(f,K.length>1?`(${K.join(" AND ")})`:K[0]);return d}if(S&&typeof S.raw<"u")return C(f,S.raw),d;return d},V=(d,f)=>{if(E.length>0)p=q(),E.length=0;J=!0;let T=f.__rawState?.();if(T){let S=D.length,A=_.dialect==="postgres"?T.sql.replace(/\$(\d+)/g,(O,K)=>`$${Number(K)+S}`):T.sql;p+=` ${d} ${A}`,D.push(...T.params),B=f.__hasPredicate?.()??he.WHERE.test(A)}else{let S=String(f.toSQL());p+=` ${d} ${S}`,B=f.__hasPredicate?.()??he.WHERE.test(S)}v=null},U=(d)=>{let f=ts(p,Of,1),T=f.length>0?f[0].start:-1;p=T>=0?`${p.slice(0,T)}${d} ${p.slice(T)}`:`${p} ${d}`,v=null},Y=new Set,I,Q,se=!1,oe=!1,fe=!1,at=new Map,nt=new Set,cn=60000,Se=(d)=>qt(_.relations.singularizeStrategy)(d),yt=(d)=>{if(!n)return null;return en(n,String(y),d,{singularize:Se,models:n.models})},zt=(d)=>{if(!d||typeof d!=="object"||nt.size===0)return d;let f;for(let T of Object.keys(d))if(T.startsWith("pivot_")){if(!f)f={};f[T.slice(6)]=d[T],delete d[T]}if(f)d.pivot=f;return d},St=(d)=>{if(nt.size===0||!d)return d;if(Array.isArray(d))for(let f=0;f<d.length;f++)zt(d[f]);else zt(d);return d},Mn=(d)=>{if(!n)return;if(Y.has(d.pivotTable))return;let f=String(y),T=n.primaryKeys[f]??"id";G(d.pivotTable,"wherePivot auto-join (pivot table)"),G(d.fkParent,"wherePivot auto-join (parent FK)"),G(f,"wherePivot auto-join (parent table)"),G(T,"wherePivot auto-join (parent PK)"),v=g`${x()} LEFT JOIN ${g(d.pivotTable)} ON ${g(`${d.pivotTable}.${d.fkParent}`)} = ${g(`${f}.${T}`)}`,p=`${p} LEFT JOIN ${d.pivotTable} ON ${d.pivotTable}.${d.fkParent} = ${f}.${T}`,Y.add(d.pivotTable)},On=(d)=>{if(he.SELECT_STAR.test(p))p=p.replace(he.SELECT_STAR,`SELECT *, ${d}`);else if(he.SELECT.test(p))p=p.replace(he.SELECT_FROM,`SELECT $1, ${d} FROM`);let f=String(x());if(he.SELECT_STAR.test(f)){let T=f.replace(he.SELECT_STAR,`SELECT *, ${d}`);v=t.unsafe(T)}else if(he.SELECT.test(f)){if(he.SELECT_FROM.exec(f)){let S=f.replace(he.SELECT_FROM,`SELECT $1, ${d} FROM`);v=t.unsafe(S)}}},ht=(d,f,T,S)=>{On(`${d} ${Rf(T,S)} AS ${f}`)},ir=(d,f,T,S)=>{G(d,"relationship subquery (parent table)"),G(f,"relationship subquery (target table)"),G(T,"relationship subquery (primary key)");let A=`${d.endsWith("s")?d.slice(0,-1):d}_id`;G(A,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${f} WHERE ${f}.${A} = ${d}.${T}`;if(S){let F=S({where:(z,L,j)=>(G(z,"relationship subquery condition"),`${f}.${z} ${Oe(L,"whereHas callback")} ${vt(j)}`)});if(F)O+=` AND ${F}`}return O},or=(d,f,T,S)=>{G(d,"relationship subquery (parent table)"),G(f,"relationship subquery (target table)"),G(T,"relationship subquery (primary key)");let A=`${f.endsWith("s")?f.slice(0,-1):f}_id`;G(A,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${f} WHERE ${f}.${T} = ${d}.${A}`;if(S){let F=S({where:(z,L,j)=>(G(z,"relationship subquery condition"),`${f}.${z} ${Oe(L,"whereHas callback")} ${vt(j)}`)});if(F)O+=` AND ${F}`}return O},ar=(d,f,T,S,A,O)=>{G(d,"relationship subquery (parent table)"),G(f,"relationship subquery (target table)"),G(T,"relationship subquery (primary key)"),G(S,"relationship subquery (target primary key)");let K=O&&n?en(n,d,O,{singularize:Se,models:n.models}):null,F=Se(d),z=Se(f),L=K?.pivotTable??[F,z].sort().join("_"),j=K?.fkParent??`${F}_id`,X=K?.fkRelated??`${z}_id`;G(L,"relationship subquery (pivot table)"),G(j,"relationship subquery (foreign key A)"),G(X,"relationship subquery (foreign key B)");let ae=`SELECT 1 FROM ${L} JOIN ${f} ON ${f}.${S} = ${L}.${X} WHERE ${L}.${j} = ${d}.${T}`;if(A){let ee=A({where:(Ne,Ue,Je)=>(G(Ne,"relationship subquery condition"),`${f}.${Ne} ${Oe(Ue,"whereHas callback")} ${vt(Je)}`)});if(ee)ae+=` AND ${ee}`}return ae},Mc=(d,f,T)=>{G(d,"withCount (parent table)"),G(f,"withCount (target table)"),G(T,"withCount (primary key)");let S=`${d.endsWith("s")?d.slice(0,-1):d}_id`;return G(S,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${f} WHERE ${f}.${S} = ${d}.${T})`},Oc=(d,f,T,S)=>{G(d,"withCount (parent table)"),G(f,"withCount (target table)"),G(T,"withCount (primary key)");let A=S&&n?en(n,d,S,{singularize:Se,models:n.models}):null,O=Se(d),K=Se(f),F=A?.pivotTable??[O,K].sort().join("_"),z=A?.fkParent??`${O}_id`;return G(F,"withCount (pivot table)"),G(z,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${F} WHERE ${F}.${z} = ${d}.${T})`},lr=(d,f,T)=>{if(!n)return;G(T,`with${d[0]}${d.slice(1).toLowerCase()} (column)`);let S=String(y),A=n.relations?.[S];if(!A)return;let O=Object.entries(A).find(([ee,Ne])=>Ne&&typeof Ne==="object"&&(f in Ne));if(!O)return;let[K,F]=O,z=F[f],L=typeof z==="string"?z:z?.model||z?.target||z,j=n.modelToTable[L]||L,X=n.primaryKeys[S]??"id";G(j,`with${d} (target table)`);let ae=`${d}(${j}.${T})`,Ae;if(K==="hasMany"||K==="hasOne"){let ee=`${S.endsWith("s")?S.slice(0,-1):S}_id`;G(ee,`with${d} (foreign key)`),Ae=`(SELECT ${ae} FROM ${j} WHERE ${j}.${ee} = ${S}.${X})`}else if(K==="belongsToMany"){let ee=n?en(n,S,f,{singularize:Se,models:n.models}):null,Ne=Se(S),Ue=Se(j),Je=ee?.pivotTable??[Ne,Ue].sort().join("_"),We=ee?.fkParent??`${Ne}_id`,le=ee?.fkRelated??`${Ue}_id`,Bn=n.primaryKeys[j]??"id";G(Je,`with${d} (pivot table)`),G(We,`with${d} (foreign key)`),G(le,`with${d} (related key)`),Ae=`(SELECT ${ae} FROM ${Je} JOIN ${j} ON ${j}.${Bn} = ${Je}.${le} WHERE ${Je}.${We} = ${S}.${X})`}else return;On(`${Ae} AS ${f}_${d.toLowerCase()}_${T}`)},Ui=()=>{if(at.size===0)return;let d=[];for(let[f,T]of at.entries()){let S=yt(f);if(!S)continue;for(let O of T)G(O,"withPivot");let A=T.map((O)=>`${S.pivotTable}.${O} AS pivot_${O}`);d.push(...A)}if(d.length>0){let f=d.join(", ");On(f)}};return new Proxy({distinct(){return p=p.replace(/^SELECT\s+/i,"SELECT DISTINCT "),v=null,this},distinctOn(...d){let f=d.map(String).join(", ");return p=p.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${f}) `),v=null,this},selectRaw(d){let f=nn(d,"selectRaw(fragment)"),T=p.indexOf(" FROM ");if(T!==-1)p=`${p.substring(0,T)}, ${f}${p.substring(T)}`;else p+=`, ${f}`;return v=null,this},rowNumber(d="row_number",f,T){let S=[];if(f){let F=Array.isArray(f)?f:[f];S.push(`PARTITION BY ${F.join(", ")}`)}if(T&&T.length)S.push(`ORDER BY ${T.map(([F,z])=>`${F} ${z==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${d}`,K=p.indexOf(" FROM ");if(K!==-1)p=`${p.substring(0,K)}, ${O}${p.substring(K)}`;else p+=`, ${O}`;return v=null,this},denseRank(d="dense_rank",f,T){let S=Array.isArray(f)?f:f?[f]:[],A=[];if(S.length)A.push(`PARTITION BY ${S.join(", ")}`);if(T&&T.length)A.push(`ORDER BY ${T.map(([z,L])=>`${z} ${L==="desc"?"DESC":"ASC"}`).join(", ")}`);let K=`DENSE_RANK() ${A.length?`OVER (${A.join(" ")})`:"OVER ()"} AS ${d}`,F=p.indexOf(" FROM ");if(F!==-1)p=`${p.substring(0,F)}, ${K}${p.substring(F)}`;else p+=`, ${K}`;return v=null,this},rank(d="rank",f,T){let S=Array.isArray(f)?f:f?[f]:[],A=[];if(S.length)A.push(`PARTITION BY ${S.join(", ")}`);if(T&&T.length)A.push(`ORDER BY ${T.map(([z,L])=>`${z} ${L==="desc"?"DESC":"ASC"}`).join(", ")}`);let K=`RANK() ${A.length?`OVER (${A.join(" ")})`:"OVER ()"} AS ${d}`,F=p.indexOf(" FROM ");if(F!==-1)p=`${p.substring(0,F)}, ${K}${p.substring(F)}`;else p+=`, ${K}`;return v=null,this},over(d,f,T={}){return ht(d,f,T.partitionBy,T.orderBy),this},lag(d,f={}){let T=[d,String(f.offset??1)];if(f.defaultValue!==void 0)T.push(String(f.defaultValue));return ht(`LAG(${T.join(", ")})`,f.alias??`${d}_lag`,f.partitionBy,f.orderBy),this},lead(d,f={}){let T=[d,String(f.offset??1)];if(f.defaultValue!==void 0)T.push(String(f.defaultValue));return ht(`LEAD(${T.join(", ")})`,f.alias??`${d}_lead`,f.partitionBy,f.orderBy),this},sumOver(d,f={}){return ht(`SUM(${d})`,f.alias??`${d}_sum`,f.partitionBy,f.orderBy),this},avgOver(d,f={}){return ht(`AVG(${d})`,f.alias??`${d}_avg`,f.partitionBy,f.orderBy),this},countOver(d="*",f={}){return ht(`COUNT(${d})`,f.alias??"count_over",f.partitionBy,f.orderBy),this},minOver(d,f={}){return ht(`MIN(${d})`,f.alias??`${d}_min`,f.partitionBy,f.orderBy),this},maxOver(d,f={}){return ht(`MAX(${d})`,f.alias??`${d}_max`,f.partitionBy,f.orderBy),this},firstValue(d,f={}){return ht(`FIRST_VALUE(${d})`,f.alias??`${d}_first`,f.partitionBy,f.orderBy),this},lastValue(d,f={}){return ht(`LAST_VALUE(${d})`,f.alias??`${d}_last`,f.partitionBy,f.orderBy),this},selectAll(){return this},select(d){if(!d)return this;let f=Array.isArray(d)?d:[d];if(f.length===0)return this;let T=f.map(Ia),S=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(p),A=S?S[1]:"",O=p.indexOf(" FROM ");if(O!==-1)p=`SELECT ${A}${T.join(", ")}${p.substring(O)}`;else p=`SELECT ${A}${T.join(", ")} FROM ${y}`;return v=null,this},addSelect(...d){if(!d.length)return this;let f=d.map(Ia),T=p.indexOf(" FROM ");if(T!==-1)p=`${p.substring(0,T)}, ${f.join(", ")}${p.substring(T)}`;else p+=`, ${f.join(", ")}`;return v=null,this},with(...d){if(!n||!d||d.length===0)return this;let f=[];for(let L of d){if(!L)continue;if(typeof L==="string")f.push({name:L});else if(typeof L==="object"&&!Array.isArray(L))for(let[j,X]of Object.entries(L))if(typeof X==="function")f.push({name:j,callback:X});else f.push({name:j})}if(f.length===0)return this;let T=_.relations.maxEagerLoad??50;if(f.length>T)throw Error(`[query-builder] Too many relationships to eager load (${f.length}). Maximum allowed: ${T}`);let S=String(y),A=new Set,O=new Set,K=new Map,F=(L)=>{let j=n.relations?.[L];if(!j)return[];return[...Object.keys(j.hasOne||{}),...Object.keys(j.hasMany||{}),...Object.keys(j.belongsTo||{}),...Object.keys(j.belongsToMany||{}),...Object.keys(j.hasOneThrough||{}),...Object.keys(j.hasManyThrough||{}),...Object.keys(j.morphOne||{}),...Object.keys(j.morphMany||{}),...Object.keys(j.morphToMany||{}),...Object.keys(j.morphedByMany||{})]},z=(L,j,X=0,ae)=>{let Ae=_.relations.maxDepth??10;if(X>=Ae)throw Error(`[query-builder] Maximum relationship depth (${Ae}) exceeded at '${j}'. Consider using separate queries or increasing maxDepth.`);let ee=n.relations?.[L];if(!ee)return L;let Ne=(ce)=>{if(_.softDeletes?.enabled&&_.softDeletes?.defaultFilter){let ue=_.softDeletes.column||"deleted_at";return` AND ${ce}.${ue} IS NULL`}return""},Ue=(ce)=>{if(!ae)return"";let ue=[],xe=(me,He,pt)=>{G(String(me),"with() constraint column");let un=Oe(He,"with() constraint operator");ue.push(`${ce}.${String(me)} ${un} ${vt(pt)}`)},we=(me)=>()=>{throw Error(`[query-builder] with('${j}', ...): ${me} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},ke={where:(me,He,pt)=>{if(Array.isArray(me))xe(me[0],me[1],me[2]);else if(me&&typeof me==="object")for(let un of Object.keys(me))xe(un,"=",me[un]);else if(He!==void 0&&pt!==void 0)xe(me,He,pt);else if(He!==void 0)xe(me,"=",He);return ke},whereIn:(me,He)=>(G(String(me),"with() constraint column"),ue.push(`${ce}.${String(me)} IN (${He.map(vt).join(", ")})`),ke),whereNull:(me)=>(G(String(me),"with() constraint column"),ue.push(`${ce}.${String(me)} IS NULL`),ke),whereNotNull:(me)=>(G(String(me),"with() constraint column"),ue.push(`${ce}.${String(me)} IS NOT NULL`),ke),orderBy:we("orderBy()"),limit:we("limit()"),offset:we("offset()"),take:we("take()")};return ae(ke),ue.length?` AND ${ue.join(" AND ")}`:""},Je=()=>{let ce=(we)=>{let ke=we?.[j];return ke?n.modelToTable[ke]:void 0},ue=(we)=>{let ke=we?.[j],me=typeof ke==="string"?ke:ke?.model;return me?n.modelToTable[me]:void 0},xe=(we)=>{let ke=we?.[j];return ke?.target?n.modelToTable[ke.target]:void 0};return ce(ee?.hasOne)||ce(ee?.hasMany)||ce(ee?.belongsTo)||ue(ee?.belongsToMany)||xe(ee?.hasOneThrough)||xe(ee?.hasManyThrough)||ce(ee?.morphOne)||ce(ee?.morphMany)||ce(ee?.morphToMany)||ce(ee?.morphedByMany)},We=Je()??(n.modelToTable[j]||n.tableToModel[j]?n.modelToTable[j]??j:j),le=String(We);if(!We||!Je()&&!n.modelToTable[j]&&!n.tableToModel[j]){let ce=F(L);if(ce.length>0&&!ce.includes(j)){let ue=` Available relationships: ${ce.join(", ")}`;throw Error(`[query-builder] Relationship '${j}' not found on table '${L}'.${ue}`)}}if(_.relations.detectCycles!==!1){let ce=`${L}->${le}`;if(A.has(ce))throw Error(`[query-builder] Circular relationship detected: ${ce}. This would cause an infinite loop.`);A.add(ce)}if(!le||le===L)return L;let Bn=ee?.hasOneThrough?.[j]||ee?.hasManyThrough?.[j];if(Bn){let{through:ce,target:ue}=Bn,xe=n.modelToTable[ce]||ce,we=n.modelToTable[ue]||ue,ke=n.primaryKeys[L]??"id",me=n.primaryKeys[xe]??"id",He=`${Se(L)}_id`,pt=`${Se(xe)}_id`;return U(`LEFT JOIN ${xe} ON ${xe}.${He} = ${L}.${ke} LEFT JOIN ${we} ON ${we}.${pt} = ${xe}.${me}`),Y.add(xe),Y.add(we),we}if(Boolean(ee?.belongsToMany?.[j])){let ce=en(n,L,j,{singularize:Se,models:n.models}),ue=ce?.pivotTable??[Se(L),Se(le)].sort().join("_"),xe=n.primaryKeys[L]??"id",we=n.primaryKeys[le]??"id",ke=ce?.fkParent??`${Se(L)}_id`,me=ce?.fkRelated??`${Se(le)}_id`;return U(`LEFT JOIN ${ue} ON ${ue}.${ke} = ${L}.${xe} LEFT JOIN ${le} ON ${le}.${we} = ${ue}.${me}${Ue(le)}`),Y.add(ue),Y.add(le),le}if(Boolean(ee?.morphToMany?.[j])){let ce=j,ue=`${Se(le)}_${ce}`,xe=n.primaryKeys[L]??"id",we=n.primaryKeys[le]??"id",ke=`${ce}_type`,me=`${ce}_id`,He=`${Se(le)}_id`,pt=vt(n.tableToModel[L]||L);return U(`LEFT JOIN ${ue} ON ${ue}.${me} = ${L}.${xe} AND ${ue}.${ke} = ${pt} LEFT JOIN ${le} ON ${le}.${we} = ${ue}.${He}`),Y.add(ue),Y.add(le),le}if(Boolean(ee?.morphedByMany?.[j])){let ce=ee.morphedByMany?.[j]||j,ue=n.modelToTable[ce]||ce,xe=Se(L),we=`${Se(ue)}_${xe}`,ke=n.primaryKeys[L]??"id",me=n.primaryKeys[ue]??"id",He=`${xe}_type`,pt=`${xe}_id`,un=`${Se(ue)}_id`,Kc=vt(n.tableToModel[ue]||ue);return U(`LEFT JOIN ${we} ON ${we}.${un} = ${L}.${ke} LEFT JOIN ${ue} ON ${ue}.${me} = ${we}.${pt} AND ${we}.${He} = ${Kc}`),Y.add(we),Y.add(ue),ue}if(Boolean(ee?.belongsTo?.[j])){let ce=`${Se(le)}_id`,ue=n.primaryKeys[le]??"id";return U(`LEFT JOIN ${le} ON ${L}.${ce} = ${le}.${ue}${Ue(le)}`),Y.add(le),le}let Bc=Boolean(ee?.morphOne?.[j]),Pc=Boolean(ee?.morphMany?.[j]);if(Bc||Pc){let ce=`${j}_type`,ue=`${j}_id`,xe=n.primaryKeys[L]??"id",we=vt(n.tableToModel[L]||L);return U(`LEFT JOIN ${le} ON ${le}.${ue} = ${L}.${xe} AND ${le}.${ce} = ${we}`),Y.add(le),le}let _c=`${Se(L)}_id`,Ic=n.primaryKeys[L]??"id",Lc=`${Ne(le)}${Ue(le)}`;return U(`LEFT JOIN ${le} ON ${le}.${_c} = ${L}.${Ic}${Lc}`),Y.add(le),le};for(let L of f){let j=L.name.trim();if(L.callback)K.set(j,L.callback);let X=j.split("."),ae=S,Ae=0;for(let ee of X){if(!ee||ee.trim().length===0)continue;let Ne=ee.trim(),Ue=K.get(Ne);ae=z(ae,Ne,Ae,Ue)||ae,Ae++}O.add(j)}if(at.size>0){let L=[];for(let[j,X]of at.entries()){let ae=yt(j);if(!ae)continue;let Ae=X.map((ee)=>`${ae.pivotTable}.${ee} AS pivot_${ee}`);L.push(...Ae)}if(L.length>0){let j=L.join(", ");On(j)}}return v=null,this},whereHas(d,f){if(!n)return this;let T=String(y),S=n.relations?.[T];if(!S)throw Error(`[query-builder] No relationships defined for table '${T}'`);let A=Object.entries(S).find(([X,ae])=>ae&&typeof ae==="object"&&(d in ae));if(!A)throw Error(`[query-builder] Relationship '${d}' not found on table '${T}'`);let[O,K]=A,F=K[d],z=typeof F==="string"?F:F?.model||F?.target||F,L=n.modelToTable[z]||z,j;if(O==="hasMany"||O==="hasOne"){let X=n.primaryKeys[T]??"id";j=ir(T,L,X,f)}else if(O==="belongsTo"){let X=n.primaryKeys[L]??"id";j=or(T,L,X,f)}else if(O==="belongsToMany"){let X=n.primaryKeys[T]??"id",ae=n.primaryKeys[L]??"id";j=ar(T,L,X,ae,f,d)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return k("WHERE",`EXISTS (${j})`),this},whereDoesntHave(d,f){if(!n)return this;let T=String(y),S=n.relations?.[T];if(!S)throw Error(`[query-builder] No relationships defined for table '${T}'`);let A=Object.entries(S).find(([X,ae])=>ae&&typeof ae==="object"&&(d in ae));if(!A)throw Error(`[query-builder] Relationship '${d}' not found on table '${T}'`);let[O,K]=A,F=K[d],z=typeof F==="string"?F:F?.model||F?.target||F,L=n.modelToTable[z]||z,j;if(O==="hasMany"||O==="hasOne"){let X=n.primaryKeys[T]??"id";j=ir(T,L,X,f)}else if(O==="belongsTo"){let X=n.primaryKeys[L]??"id";j=or(T,L,X,f)}else if(O==="belongsToMany"){let X=n.primaryKeys[T]??"id",ae=n.primaryKeys[L]??"id";j=ar(T,L,X,ae,f,d)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return k("WHERE",`NOT EXISTS (${j})`),this},has(d){if(!n)return this;let f=String(y),T=n.relations?.[f];if(!T)throw Error(`[query-builder] No relationships defined for table '${f}'`);let S=Object.entries(T).find(([j,X])=>X&&typeof X==="object"&&(d in X));if(!S)throw Error(`[query-builder] Relationship '${d}' not found on table '${f}'`);let[A,O]=S,K=O[d],F=typeof K==="string"?K:K?.model||K?.target||K,z=n.modelToTable[F]||F,L;if(A==="hasMany"||A==="hasOne"){let j=n.primaryKeys[f]??"id";L=ir(f,z,j)}else if(A==="belongsTo"){let j=n.primaryKeys[z]??"id";L=or(f,z,j)}else if(A==="belongsToMany"){let j=n.primaryKeys[f]??"id",X=n.primaryKeys[z]??"id";L=ar(f,z,j,X,void 0,d)}else throw Error(`[query-builder] Unsupported relationship type '${A}' for has`);return k("WHERE",`EXISTS (${L})`),this},doesntHave(d){if(!n)return this;let f=String(y),T=n.relations?.[f];if(!T)throw Error(`[query-builder] No relationships defined for table '${f}'`);let S=Object.entries(T).find(([j,X])=>X&&typeof X==="object"&&(d in X));if(!S)throw Error(`[query-builder] Relationship '${d}' not found on table '${f}'`);let[A,O]=S,K=O[d],F=typeof K==="string"?K:K?.model||K?.target||K,z=n.modelToTable[F]||F,L;if(A==="hasMany"||A==="hasOne"){let j=n.primaryKeys[f]??"id";L=ir(f,z,j)}else if(A==="belongsTo"){let j=n.primaryKeys[z]??"id";L=or(f,z,j)}else if(A==="belongsToMany"){let j=n.primaryKeys[f]??"id",X=n.primaryKeys[z]??"id";L=ar(f,z,j,X,void 0,d)}else throw Error(`[query-builder] Unsupported relationship type '${A}' for doesntHave`);return k("WHERE",`NOT EXISTS (${L})`),this},withCount(...d){if(!n||!d||d.length===0)return this;let f=String(y);for(let T of d){let S=n.relations?.[f];if(!S)continue;let A=Object.entries(S).find(([Ae,ee])=>ee&&typeof ee==="object"&&(T in ee));if(!A)continue;let[O,K]=A,F=K[T],z=typeof F==="string"?F:F?.model||F?.target||F,L=n.modelToTable[z]||z,j=n.primaryKeys[f]??"id",X;if(O==="hasMany"||O==="hasOne")X=Mc(f,L,j);else if(O==="belongsToMany")X=Oc(f,L,j,T);else continue;let ae=`${T}_count`;On(`${X} AS ${ae}`)}return this},withSum(d,f){return lr("SUM",d,f),this},withAvg(d,f){return lr("AVG",d,f),this},withMax(d,f){return lr("MAX",d,f),this},withMin(d,f){return lr("MIN",d,f),this},applyPivotColumns(){return Ui(),this},withPivot(d,...f){if(!n)return this;let T=String(y),S=yt(d);if(!S)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${T}'`);let A=f&&f.length>0?f:S.hasConfig?S.pivotColumns:[];if(A.length===0)return this;if(at.set(d,A),S.hasConfig)nt.add(d);return Ui(),this},wherePivot(d,f,T,S){if(!n)return this;let A=yt(d);if(!A)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);G(A.pivotTable,"wherePivot (pivot table)"),G(f,"wherePivot (column)"),Mn(A);let O=S===void 0?"=":String(T),K=S===void 0?T:S,F=D.length+1,z=`${A.pivotTable}.${f} ${O} ${Z(F)}`;if(D.push(K),C("AND",z),A.hasConfig)nt.add(d);return this},wherePivotIn(d,f,T){if(!n||!Array.isArray(T))return this;let S=yt(d);if(!S)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);G(S.pivotTable,"wherePivotIn (pivot table)"),G(f,"wherePivotIn (column)"),Mn(S);let A=ve(T.length,D.length+1),O=Ge(`${S.pivotTable}.${f}`,T,!1,A);if(D.push(...T),C("AND",O),S.hasConfig)nt.add(d);return this},wherePivotNotIn(d,f,T){if(!n||!Array.isArray(T)||T.length===0)return this;let S=yt(d);if(!S)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);G(S.pivotTable,"wherePivotNotIn (pivot table)"),G(f,"wherePivotNotIn (column)"),Mn(S);let A=ve(T.length,D.length+1),O=`${S.pivotTable}.${f} NOT IN (${A})`;if(D.push(...T),C("AND",O),S.hasConfig)nt.add(d);return this},wherePivotNull(d,f){if(!n)return this;let T=yt(d);if(!T)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);if(G(T.pivotTable,"wherePivotNull (pivot table)"),G(f,"wherePivotNull (column)"),Mn(T),C("AND",`${T.pivotTable}.${f} IS NULL`),T.hasConfig)nt.add(d);return this},wherePivotNotNull(d,f){if(!n)return this;let T=yt(d);if(!T)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);if(G(T.pivotTable,"wherePivotNotNull (pivot table)"),G(f,"wherePivotNotNull (column)"),Mn(T),C("AND",`${T.pivotTable}.${f} IS NOT NULL`),T.hasConfig)nt.add(d);return this},where(d,f,T){if(typeof d==="string"&&f!==void 0){G(String(d),"where(column)"),Oe(f,"where(operator)");let S=String(f).toLowerCase();if(S==="in"||S==="not in"){let O=Array.isArray(T)?T:[T],K=ve(O.length,D.length+1),F=Ge(ot(String(d)),O,S==="not in",K);return D.push(...O),C("AND",F),this}let A=D.length+1;return D.push(T),C("AND",`${ot(String(d))} ${String(f)} ${Z(A)}`),this}if(Array.isArray(d)){let[S,A,O]=d,K=String(S);G(K,"where(column)");let F=Oe(A,"where(operator)");if(F==="in"||F==="not in"){let z=Array.isArray(O)?O:[O],L=ve(z.length,D.length+1),j=Ge(ot(K),z,F==="not in",L);D.push(...z),C("AND",j)}else{let z=D.length+1;D.push(O),C("AND",`${ot(K)} ${F} ${Z(z)}`)}return this}if(d&&typeof d==="object"&&!wt(d)){let S=d,A=Object.keys(S),O=[];for(let K of A){G(K,"where(column)");let F=S[K];if(Array.isArray(F)){let z=ve(F.length,D.length+1);O.push(Ge(ot(K),F,!1,z)),D.push(...F)}else{let z=D.length+1;O.push(`${ot(K)} = ${Z(z)}`),D.push(F)}}if(O.length>0)C("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(wt(d))return C("AND",d.raw),this;if(typeof d==="function")return H("AND",d),this;if(d===void 0||d===null)throw TypeError("where() was called with no condition.");if(typeof d==="string")throw TypeError(`where(${JSON.stringify(d)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof d}.`)},whereNull(d){return G(String(d),"whereNull(column)"),C("AND",`${String(d)} IS NULL`),this},whereNotNull(d){return G(String(d),"whereNotNull(column)"),C("AND",`${String(d)} IS NOT NULL`),this},orWhereNull(d){return G(String(d),"orWhereNull(column)"),C("OR",`${String(d)} IS NULL`),this},orWhereNotNull(d){return G(String(d),"orWhereNotNull(column)"),C("OR",`${String(d)} IS NOT NULL`),this},whereBetween(d,f,T){G(String(d),"whereBetween(column)");let S=D.length+1;return D.push(f,T),C("AND",`${String(d)} BETWEEN ${Z(S)} AND ${Z(S+1)}`),this},orWhereBetween(d,f,T){G(String(d),"orWhereBetween(column)");let S=D.length+1;return D.push(f,T),C("OR",`${String(d)} BETWEEN ${Z(S)} AND ${Z(S+1)}`),this},whereExists(d){return C("AND",`EXISTS (${d.toSQL()})`),this},orWhereExists(d){return C("OR",`EXISTS (${d.toSQL()})`),this},whereGroup(d){return H("AND",d),this},orWhereGroup(d){return H("OR",d),this},__whereState(){return{body:tn(E),params:[...D]}},whereJsonContains(d,f){G(String(d),"whereJsonContains(column)");let T=_.dialect,S=D.length+1;if(T==="postgres"){let O=typeof f==="number"||typeof f==="boolean"?`to_jsonb(${Z(S)})`:Z(S);if(_.sql?.jsonContainsMode==="function")C("AND",`jsonb_contains(${d}, ${O})`);else C("AND",`${d} @> ${O}`);D.push(f)}else if(ne(T))C("AND",`JSON_CONTAINS(${d}, ${Z(S)})`),D.push(JSON.stringify(f));else if(Array.isArray(f)){let A=f.map((O,K)=>`EXISTS (SELECT 1 FROM json_each(${d}) WHERE json_each.value = ${Z(S+K)})`);C("AND",`(${A.join(" AND ")})`);for(let O of f)D.push(O)}else if(f!==null&&typeof f==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else C("AND",`EXISTS (SELECT 1 FROM json_each(${d}) WHERE json_each.value = ${Z(S)})`),D.push(f);return this},whereJsonPath(d,f,T){if(Oe(f,"whereJsonPath(op)"),typeof d!=="string"||d.length===0||d.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof d==="string"?`'${d.slice(0,32)}...'`:typeof d}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(d))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${d}' \u2014 contains characters outside the allowed JSON-path set`);let S=_.dialect,A=D.length+1;if(S==="postgres")C("AND",`${d} ${f} ${Z(A)}`);else if(ne(S))C("AND",`JSON_EXTRACT(${d}) ${f} ${Z(A)}`);else C("AND",`json_extract(${d}) ${f} ${Z(A)}`);return D.push(T),this},whereLike(d,f,T=!1){let S=Z(D.length+1);return k("WHERE",`${T?String(d):`LOWER(${String(d)})`} LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},whereILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("WHERE",`${String(d)} ILIKE ${T}`);else k("WHERE",`LOWER(${String(d)}) LIKE LOWER(${T})`);return D.push(f),v=null,this},orWhereLike(d,f,T=!1){let S=Z(D.length+1);return k("OR",`${T?String(d):`LOWER(${String(d)})`} LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},orWhereILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("OR",`${String(d)} ILIKE ${T}`);else k("OR",`LOWER(${String(d)}) LIKE LOWER(${T})`);return D.push(f),v=null,this},whereNotLike(d,f,T=!1){let S=Z(D.length+1);return k("WHERE",`${T?String(d):`LOWER(${String(d)})`} NOT LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},whereNotILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("WHERE",`${String(d)} NOT ILIKE ${T}`);else k("WHERE",`LOWER(${String(d)}) NOT LIKE LOWER(${T})`);return D.push(f),v=null,this},orWhereNotLike(d,f,T=!1){let S=Z(D.length+1);return k("OR",`${T?String(d):`LOWER(${String(d)})`} NOT LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},orWhereNotILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("OR",`${String(d)} NOT ILIKE ${T}`);else k("OR",`LOWER(${String(d)}) NOT LIKE LOWER(${T})`);return D.push(f),v=null,this},whereAny(d,f,T){if(d.length===0)return C("AND",`(${_a})`),this;let S=D.length+1,A=d.map((O,K)=>`${O} ${f} ${Z(S+K)}`);for(let O=0;O<d.length;O++)D.push(T);return C("AND",`(${A.join(" OR ")})`),this},whereAll(d,f,T){if(d.length===0)return this;let S=D.length+1,A=d.map((O,K)=>`${O} ${f} ${Z(S+K)}`);for(let O=0;O<d.length;O++)D.push(T);return C("AND",`(${A.join(" AND ")})`),this},whereNone(d,f,T){if(d.length===0)return this;let S=D.length+1,A=d.map((O,K)=>`${O} ${f} ${Z(S+K)}`);for(let O=0;O<d.length;O++)D.push(T);return C("AND",`NOT (${A.join(" OR ")})`),this},whereNotBetween(d,f,T){G(String(d),"whereNotBetween(column)");let S=D.length+1;return D.push(f,T),C("AND",`${d} NOT BETWEEN ${Z(S)} AND ${Z(S+1)}`),this},whereDate(d,f,T){G(d,"whereDate(column)");let S=T instanceof Date?T.toISOString():typeof T==="string"?T:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof T}`)})(),A=D.length+1;return D.push(S),C("AND",`${d} ${f} ${Z(A)}`),this},whereRaw(d){return C("AND",nn(d,"whereRaw(fragment)")),this},orWhereRaw(d){return C("OR",nn(d,"orWhereRaw(fragment)")),this},whereColumn(d,f,T){return G(d,"whereColumn(left)"),G(T,"whereColumn(right)"),C("AND",`${d} ${f} ${T}`),this},orWhereColumn(d,f,T){return G(d,"orWhereColumn(left)"),G(T,"orWhereColumn(right)"),C("OR",`${d} ${f} ${T}`),this},whereIn(d,f){if(G(String(d),"whereIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!1,T);D.push(...f),C("AND",S)}else C("AND",`${d} IN (${String(f.toSQL())})`);return this},orWhereIn(d,f){if(G(String(d),"orWhereIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!1,T);D.push(...f),C("OR",S)}else C("OR",`${d} IN (${String(f.toSQL())})`);return this},whereNotIn(d,f){if(G(String(d),"whereNotIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!0,T);D.push(...f),C("AND",S)}else C("AND",`${d} NOT IN (${String(f.toSQL())})`);return this},orWhereNotIn(d,f){if(G(String(d),"orWhereNotIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!0,T);D.push(...f),C("OR",S)}else C("OR",`${d} NOT IN (${String(f.toSQL())})`);return this},whereNested(d){let f=d.toSQL?String(d.toSQL()):String(d);return C("AND",`(${f})`),this},orWhereNested(d){let f=d.toSQL?String(d.toSQL()):String(d);return C("OR",`(${f})`),this},andWhere(d,f,T){return M(this,"AND","andWhere",d,f,T)},orWhere(d,f,T){return M(this,"OR","orWhere",d,f,T)},orderBy(d,f="asc"){let T=f==="asc"?"ASC":"DESC",S=ot(String(d));return p=he.ORDER_BY.test(p)?`${p}, ${S} ${T}`:`${p} ORDER BY ${S} ${T}`,v=null,this},orderByDesc(d){return p=he.ORDER_BY.test(p)?`${p}, ${d} DESC`:`${p} ORDER BY ${d} DESC`,v=null,this},inRandomOrder(){let d=_.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return p=he.ORDER_BY.test(p)?`${p}, ${d}`:`${p} ORDER BY ${d}`,v=null,this},reorder(d,f="asc"){return p=p.replace(/ORDER BY[\s\S]*$/i,""),p+=` ORDER BY ${d} ${f==="asc"?"ASC":"DESC"}`,v=null,this},latest(d){let f=d??_.timestamps.defaultOrderColumn;return p=he.ORDER_BY.test(p)?`${p}, ${f} DESC`:`${p} ORDER BY ${f} DESC`,v=null,this},oldest(d){let f=d??_.timestamps.defaultOrderColumn;return p=he.ORDER_BY.test(p)?`${p}, ${f} ASC`:`${p} ORDER BY ${f} ASC`,v=null,this},limit(d){if(!Number.isFinite(d)||d<0||!Number.isInteger(d))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${d}`);return p=he.LIMIT.test(p)?p.replace(he.LIMIT,` LIMIT ${d}`):`${p} LIMIT ${d}`,v=null,this},offset(d){if(!Number.isFinite(d)||d<0||!Number.isInteger(d))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${d}`);return p=he.OFFSET.test(p)?p.replace(he.OFFSET,` OFFSET ${d}`):`${p} OFFSET ${d}`,v=null,this},join(d,f,T,S){return G(d,"join(table)"),it(f,"join(onLeft)"),it(S,"join(onRight)"),Oe(T,"join(operator)"),U(`JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},joinSub(d,f,T,S,A){return G(f,"joinSub(alias)"),it(T,"joinSub(onLeft)"),it(A,"joinSub(onRight)"),Oe(S,"joinSub(operator)"),U(`JOIN (${String(d.toSQL())}) AS ${f} ON ${T} ${S} ${A}`),Y.add(f),this},innerJoin(d,f,T,S){return G(d,"innerJoin(table)"),it(f,"innerJoin(onLeft)"),it(S,"innerJoin(onRight)"),Oe(T,"innerJoin(operator)"),U(`INNER JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},leftJoin(d,f,T,S){return G(d,"leftJoin(table)"),it(f,"leftJoin(onLeft)"),it(S,"leftJoin(onRight)"),Oe(T,"leftJoin(operator)"),U(`LEFT JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},leftJoinSub(d,f,T,S,A){return G(f,"leftJoinSub(alias)"),it(T,"leftJoinSub(onLeft)"),it(A,"leftJoinSub(onRight)"),Oe(S,"leftJoinSub(operator)"),U(`LEFT JOIN (${String(d.toSQL())}) AS ${f} ON ${T} ${S} ${A}`),Y.add(f),this},rightJoin(d,f,T,S){return G(d,"rightJoin(table)"),it(f,"rightJoin(onLeft)"),it(S,"rightJoin(onRight)"),Oe(T,"rightJoin(operator)"),U(`RIGHT JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},crossJoin(d){return G(d,"crossJoin(table)"),U(`CROSS JOIN ${d}`),Y.add(d),this},crossJoinSub(d,f){return G(f,"crossJoinSub(alias)"),U(`CROSS JOIN (${String(d.toSQL())}) AS ${f}`),Y.add(f),this},selectAllRelations(){if(!r)return this;let d=String(y),f=Object.keys(r[d]?.columns??{}),T=[];if(f.length>0)T.push(g`${g(d)}.*`);for(let S of Y){let A=Object.keys(r[S]?.columns??{});for(let O of A){let K=_.aliasing.relationColumnAliasFormat==="camelCase"?`${S}_${O}`.replace(/_([a-z])/g,(F,z)=>z.toUpperCase()):_.aliasing.relationColumnAliasFormat==="table.dot.column"?`${S}.${O}`:`${S}_${O}`;T.push(g`${g(`${S}.${O}`)} AS ${g(K)}`)}}if(T.length>0){let S=f.length>0?`${d}.*`:"",A=[];for(let F of Y){let z=Object.keys(r[F]?.columns??{});for(let L of z){let j=_.aliasing.relationColumnAliasFormat==="camelCase"?`${F}_${L}`.replace(/_([a-z])/g,(X,ae)=>ae.toUpperCase()):_.aliasing.relationColumnAliasFormat==="table.dot.column"?`${F}.${L}`:`${F}_${L}`;A.push(`${F}.${L} AS ${j}`)}}let O=[S,...A].filter(Boolean).join(", "),K=p.indexOf(" FROM ");if(K!==-1)p=`SELECT ${O}${p.substring(K)}`;else p=`SELECT ${O} FROM ${d}`;v=null}return this},groupBy(...d){if(d.length)p=he.GROUP_BY.test(p)?`${p}, ${d.map((f)=>ot(String(f))).join(", ")}`:`${p} GROUP BY ${d.map((f)=>ot(String(f))).join(", ")}`,v=null;return this},groupByRaw(d){let f=nn(d,"groupByRaw(fragment)");return p=he.GROUP_BY.test(p)?`${p}, ${f}`:`${p} GROUP BY ${f}`,v=null,this},having(d){let f=W?"AND":"HAVING";if(Array.isArray(d)){let T=D.length+1;p=`${p} ${f} ${d[0]} ${d[1]} ${Z(T)}`,D.push(d[2]),W=!0,v=null}else if(d&&typeof d==="object"&&!("raw"in d)){let T=Object.keys(d),S=T.length;if(S){let A=D.length,O=Array.from({length:S});for(let K=0;K<S;K++){let F=T[K];O[K]=`${F} = ${Z(A+K+1)}`,D.push(d[F])}p=`${p} ${f} ${O.join(" AND ")}`,W=!0,v=null}}else if(d&&typeof d.raw<"u")p+=` ${f} ${d.raw}`,W=!0,v=null;return this},havingRaw(d){let f=nn(d,"havingRaw(fragment)");return p+=` ${W?"AND":"HAVING"} ${f}`,W=!0,v=null,this},orderByRaw(d){let f=nn(d,"orderByRaw(fragment)");return p=he.ORDER_BY.test(p)?`${p}, ${f}`:`${p} ORDER BY ${f}`,v=null,this},$call(d){return d(this),this},union(d){return V("UNION",d),this},unionAll(d){return V("UNION ALL",d),this},intersect(d){return V("INTERSECT",d),this},intersectAll(d){return V("INTERSECT ALL",d),this},except(d){return V("EXCEPT",d),this},exceptAll(d){return V("EXCEPT ALL",d),this},forPage(d,f){let T=Math.max(1,Math.floor(d)),S=Math.max(1,Math.floor(f));return p+=` LIMIT ${S} OFFSET ${(T-1)*S}`,v=null,this},toSQL(){let d=zn(q());return{sql:d,toString:()=>d,execute:()=>x().execute(),values:()=>x().values(),raw:()=>x().raw()}},async value(d){let f=g`${x()} LIMIT 1`,T=await h(f,"select",{signal:Q,timeoutMs:I}),[S]=T;return S?.[d]},async pluck(d,f){let T=await h(x(),"select",{signal:Q,timeoutMs:I});if(f){let S={};for(let A of T){let O=String(A?.[f]);if(Object.prototype.hasOwnProperty.call(S,O))throw Error(`[query-builder] pluck(${d}, ${f}): duplicate key '${O}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);S[O]=A?.[d]}return S}return T.map((S)=>S?.[d])},async exists(){let d=g`SELECT EXISTS (${x()}) as e`,f=await h(d,"select",{signal:Q,timeoutMs:I}),[T]=f;return Boolean(T?.e)},async doesntExist(){return!await this.exists()},async paginate(d,f=1,T={}){if(typeof d==="object"&&d!==null){let X=d;f=X.page??1,T=X.tx?{tx:X.tx}:{},d=X.perPage??10}if(!Number.isFinite(d)||d<=0||!Number.isInteger(d))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${d}`);if(!Number.isFinite(f)||f<1||!Number.isInteger(f))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${f}`);if(T.tx){let X=zn(q()),ae=[...D],Ae=await T.tx.unsafe(`SELECT COUNT(*) as c FROM (${X}) as sub`,ae),ee=Number(Ae?.[0]?.c??0),Ne=Math.max(1,Math.ceil(ee/d)),Ue=Math.max(1,Math.min(f,Ne)),Je=(Ue-1)*d;return{data:await T.tx.unsafe(`${X} LIMIT ${d} OFFSET ${Je}`,ae),meta:{perPage:d,page:Ue,total:ee,lastPage:Ne}}}let S=g`SELECT COUNT(*) as c FROM (${x()}) as sub`,A=await h(S,"select",{signal:Q,timeoutMs:I}),[O]=A,K=Number(O?.c??0),F=Math.max(1,Math.ceil(K/d)),z=Math.max(1,Math.min(f,F)),L=(z-1)*d;return{data:await h(g`${x()} LIMIT ${d} OFFSET ${L}`,"select",{signal:Q,timeoutMs:I}),meta:{perPage:d,page:z,total:K,lastPage:F}}},async simplePaginate(d,f=1){let T=Math.max(1,f),S=(T-1)*d,A=await h(g`${x()} LIMIT ${d+1} OFFSET ${S}`,"select",{signal:Q,timeoutMs:I}),O=A.length>d;return{data:O?A.slice(0,d):A,meta:{perPage:d,page:T,hasMore:O}}},async cursorPaginate(d,f,T="id",S="asc"){if(!Number.isInteger(d)||d<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${d}`);let A=(Array.isArray(T)?T:[T]).map(String);for(let We of A)G(We,"cursorPaginate(column)");let O=S==="asc"?">":"<",K=S==="asc"?"ASC":"DESC",F=[...D],z="";if(f!==void 0&&f!==null)if(Array.isArray(T)){let We=f.map((le)=>(F.push(le),Z(F.length)));z=`(${A.join(", ")}) ${O} (${We.join(", ")})`}else F.push(f),z=`${A[0]} ${O} ${Z(F.length)}`;let L=zn(z?q({conn:"AND",sql:z}):q()),j=A.map((We)=>`${We} ${K}`).join(", ");if($f(L))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${j} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let X=F.length>0?t.unsafe(`${L} ORDER BY ${j} LIMIT ${d+1}`,F):t.unsafe(`${L} ORDER BY ${j} LIMIT ${d+1}`),ae=await h(X,"select",{signal:Q,timeoutMs:I}),Ae=ae.length>d,ee=ae.slice(0,d),Ne=ee[ee.length-1],Ue=Ae&&Ne?Array.isArray(T)?T.map((We)=>Ne[We]):Ne[T]:null,Je=ee.length?Array.isArray(T)?T.map((We)=>ee[0]?.[We]):ee[0]?.[T]:null;return{data:ee,meta:{perPage:d,nextCursor:Ue??null,prevCursor:Je}}},async chunk(d,f){let T=1;while(!0){let{data:S,meta:A}=await this.paginate(d,T);if(S.length===0)break;if(await f(S),T>=A.lastPage)break;T+=1}},async chunkById(d,f="id",T){let S;while(!0){let{data:A,meta:O}=await this.cursorPaginate(d,S,f,"asc");if(A.length===0)break;if(T)await T(A);if(S=O.nextCursor,!S)break}},async eachById(d,f="id",T){await this.chunkById(d,f,async(S)=>{for(let A of S)await T?.(A)})},withTimeout(d){return I=Math.max(1,Math.floor(d)),this},abort(d){return Q=d,this},withTrashed(){return se=!0,oe=!1,this},onlyTrashed(){se=!0,oe=!0;let d=_.softDeletes?.column||"deleted_at",f=(A,O)=>{let K=A.toUpperCase(),F=0;for(let z=0;z<A.length;z++){let L=A[z];if(L==="(")F++;else if(L===")")F--;else if(F===0&&K.substring(z,z+5)==="WHERE"&&(z===0||/\s/.test(A[z-1]??""))&&/\s/.test(A[z+5]??""))return`${A.substring(0,z)}WHERE ${O} AND ${A.substring(z+6)}`}return`${A} WHERE ${O}`},T=`${y}.${d} IS NOT NULL`;p=f(p,T);let S=String(x());return v=g([f(S,T)]),this},scope(d,f){let T=String(y),A=n?.scopes?.[T]?.[d];if(A)return A(this,f);return this},when(d,f,T){if(d)return f(this);if(T)return T(this);return this},tap(d){return d(this),this},dump(){return console.log(String(x())),this},dd(){throw console.log(String(x())),Error("Dump and Die")},cache(d=60000){return cn=d,fe=!0,this},async explain(){let d=g`EXPLAIN ${x()}`;return await h(d,"select",{signal:Q,timeoutMs:I})},simple(){return x().simple()},toText(){return q()},async get(){let d=o(),f=d&&(d.onQueryStart||d.onQueryEnd||d.onQueryError||d.startSpan||Hn(d));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!f){let K=t._prepareStatement;if(K){let F=K(q());return St(D.length>0?F.all(...D):F.all())}}let T=q();if(v=D.length>0?t.unsafe(T,D):t.unsafe(T),!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!f){let K=x()._stmt,F=x()._params;if(K)return St(F&&F.length>0?K.all(...F):K.all());return St(await x().execute())}if(!_.softDeletes?.enabled&&!fe&&!I&&!Q)return St(await h(x(),"select"));let S=x();if(_.softDeletes?.enabled&&_.softDeletes.defaultFilter&&!se){let K=_.softDeletes.column,F=String(y);if((r?Boolean(r[F]?.columns?.[K]):!0)&&!he.DELETED_AT.test(q()))k("WHERE",`${String(K)} IS ${oe?"NOT ":""}NULL`),S=x()}let A=fe?`${String(S)}\x00${JSON.stringify(D)}`:"";if(fe){let K=is.get(A);if(K)return K}let O=await h(S,"select",{signal:Q,timeoutMs:I});if(fe)is.set(A,O,cn);return St(O)},async executeTakeFirst(){let d=await h(x(),"select",{signal:Q,timeoutMs:I});return zt(Array.isArray(d)?d[0]:d)},async executeTakeFirstOrThrow(){let d=await this.executeTakeFirst();if(!d)throw Error("Record not found");return d},async first(){let d=o(),f=d&&(d.onQueryStart||d.onQueryEnd||d.onQueryError||d.startSpan||Hn(d));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!f){let A=t._prepareStatement;if(A){let O=q(),K=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,F=A(K),z=D.length>0?F.all(...D):F.all();return zt(z[0])}}let T=await h(g`${x()} LIMIT 1`,"select",{signal:Q,timeoutMs:I}),[S]=T;return zt(S)},async firstOrFail(){let d=await this.first();if(!d)throw Error("Record not found");return d},async find(d){let f=n?.primaryKeys[String(y)]??"id",T=await h(g`${x()} WHERE ${g(f)} = ${d} LIMIT 1`,"select",{signal:Q,timeoutMs:I}),[S]=T;return S},async findOrFail(d){let f=await this.find(d);if(!f)throw Error("Record not found");return f},async findMany(d){let f=n?.primaryKeys[String(y)]??"id";return await h(g`${x()} WHERE ${g(String(f))} IN ${g(d)}`,"select",{signal:Q,timeoutMs:I})},async*lazy(){let d,f=n?.primaryKeys[String(y)]??"id";while(!0){let S=await(d==null?g`${x()} ORDER BY ${g(String(f))} ASC LIMIT 100`:g`${x()} WHERE ${g(String(f))} > ${d} ORDER BY ${g(String(f))} ASC LIMIT 100`).execute();if(S.length===0)break;for(let A of S)yield A;if(d=S[S.length-1]?.[f],d==null)break}},async*lazyById(){let d=n?.primaryKeys[String(y)]??"id",f;while(!0){let S=await(f==null?g`${x()} ORDER BY ${g(String(d))} ASC LIMIT 100`:g`${x()} WHERE ${g(String(d))} > ${f} ORDER BY ${g(String(d))} ASC LIMIT 100`).execute();if(S.length===0)break;for(let A of S)yield A;if(f=S[S.length-1]?.[d],f==null)break}},pipe(d){return d(this)},async count(){let d=q(),f=d.indexOf(" FROM "),T=/ GROUP BY /i.test(d),S;if(T)S=`SELECT COUNT(*) as c FROM (${d}) AS _bqb_count_sub`;else if(f!==-1)S=`SELECT COUNT(*) as c${d.substring(f)}`;else S=`SELECT COUNT(*) as c FROM ${y}`;let A=o(),O=A&&(A.onQueryStart||A.onQueryEnd||A.onQueryError||A.startSpan||Hn(A));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!O){let L=t._prepareStatement;if(L){let j=L(S),X=D.length>0?j.all(...D):j.all();return Number(X[0]?.c??0)}}let K=D.length>0?t.unsafe(S,D):t.unsafe(S),F=await h(K,"select",{signal:Q,timeoutMs:I}),[z]=F;return Number(z?.c??0)},async avg(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT AVG(${d}) as a${f.substring(T)}`:`SELECT AVG(${d}) as a FROM ${y}`,A=o(),O=A&&(A.onQueryStart||A.onQueryEnd||A.onQueryError||A.startSpan||Hn(A));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!O){let L=t._prepareStatement;if(L){let j=L(S),X=D.length>0?j.all(...D):j.all();return Number(X[0]?.a??0)}}let K=D.length>0?t.unsafe(S,D):t.unsafe(S),F=await h(K,"select",{signal:Q,timeoutMs:I}),[z]=F;return Number(z?.a??0)},async sum(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT SUM(${d}) as s${f.substring(T)}`:`SELECT SUM(${d}) as s FROM ${y}`,A=D.length>0?t.unsafe(S,D):t.unsafe(S),O=await h(A,"select",{signal:Q,timeoutMs:I}),[K]=O;return Number(K?.s??0)},async max(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT MAX(${d}) as m${f.substring(T)}`:`SELECT MAX(${d}) as m FROM ${y}`,A=D.length>0?t.unsafe(S,D):t.unsafe(S),O=await h(A,"select",{signal:Q,timeoutMs:I}),[K]=O;return K?.m},async min(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT MIN(${d}) as m${f.substring(T)}`:`SELECT MIN(${d}) as m FROM ${y}`,A=D.length>0?t.unsafe(S,D):t.unsafe(S),O=await h(A,"select",{signal:Q,timeoutMs:I}),[K]=O;return K?.m},lockForUpdate(){return p+=" FOR UPDATE",v=null,this},sharedLock(){let d=_.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return p+=` ${d}`,v=null,this},withCTE(d,f){return G(d,"withCTE(name)"),p=`WITH ${d} AS (${String(f.toSQL())}) ${p}`,v=null,this},withRecursive(d,f){return G(d,"withRecursive(name)"),p=`WITH RECURSIVE ${d} AS (${String(f.toSQL())}) ${p}`,v=null,this},execute(){return h(x(),"select",{signal:Q,timeoutMs:I})},values(){return x().values()},toParams(){return[...D]},__rawState(){return{sql:zn(q()),params:[...D]}},__hasPredicate(){return E.length>0||B},raw(){return x().raw()},get rows(){return},get row(){return},cancel(){try{x().cancel()}catch{}}},{get(d,f,T){let S=Reflect.get(d,f,T);if(S!==void 0)return S;if(typeof f==="string"&&(f.startsWith("where")||f.startsWith("orWhere")||f.startsWith("andWhere"))){let A=f.startsWith("orWhere"),O=f.startsWith("andWhere"),K=`${String(y)}|${f}`,F=l.get(K);if(F===void 0){let L=f.replace(/^(?:or|and)?where/i,"");if(!L)l.set(K,""),F="";else{let j=L.charAt(0).toLowerCase()+L.slice(1),X=L.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ae=r?Object.keys(r[String(y)]?.columns??{}):[];F=[X,j,j.toLowerCase()].find((Ae)=>ae.includes(Ae))??X,l.set(K,F)}}if(F==="")return()=>T;let z=F;return(L)=>{if(Array.isArray(L)){let j=ve(L.length,D.length+1);k(A?"OR":O?"AND":"WHERE",`${z} IN (${j})`),D.push(...L)}else{let j=Z(D.length+1);k(A?"OR":O?"AND":"WHERE",`${z} = ${j}`),D.push(L)}return T}}return Reflect.get(d,f,T)}})}return{configure(y){return xa(y),this},id(y){if(!he.IDENTIFIER.test(y))throw Error(`[query-builder] Invalid identifier: '${y}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return t(String(y))},ids(...y){for(let b of y)if(!he.IDENTIFIER.test(b))throw Error(`[query-builder] Invalid identifier: '${b}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return t(y)},select(y,...b){return R(y,b)},selectFrom(y){return R(y)},selectFromSub(y,b){function g(x){return()=>{throw Error(`[query-builder] selectFromSub(...).${x}() is not supported. Apply ${x}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}G(String(b),"selectFromSub(alias)");let p=typeof y.__rawState==="function"?y.__rawState():null,E=y.toSQL(),D=p?.sql??(typeof E==="string"?E:E?.sql??String(E)),J=p?.params??(Array.isArray(E?.values)?E.values:[]),B=`SELECT * FROM (${D}) AS ${String(b)}`,W=(x,C,k,P)=>{let q=[...x],H=(V,U,Y)=>{G(V,"selectFromSub where(column)");let I=Oe(U,"selectFromSub where(operator)");if(I==="in"||I==="not in"){let se=Array.isArray(Y)?Y:[Y],oe=ve(se.length,q.length+1);return q.push(...se),`${V} ${I.toUpperCase()} (${oe})`}let Q=Z(q.length+1);return q.push(Y),`${V} ${I} ${Q}`},M;if(typeof C==="string"&&k!==void 0)M=H(C,k,P);else if(Array.isArray(C)&&C.length===3)M=H(C[0],C[1],C[2]);else if(C&&typeof C==="object"){let V=Object.entries(C).map(([U,Y])=>H(U,"=",Y));M=V.length>1?`(${V.join(" AND ")})`:V[0]}else return{clause:null,params:x};return{clause:M,params:q}};function v(x,C,k,P=""){let q=tn(C),H=q?`${x} WHERE ${q}${P}`:`${x}${P}`,M=()=>k.length>0?t.unsafe(H,k):t.unsafe(H),V=(I,Q,se,oe)=>{let fe=W(k,Q,se,oe);return fe.clause===null?v(x,C,k,P):v(x,[...C,{conn:I,sql:fe.clause}],fe.params,P)},U=(I,Q)=>{let se=[],oe=[...k],fe=(cn)=>(Se,yt,zt)=>{let St=W(oe,Se,yt,zt);if(St.clause!==null)se.push({conn:cn,sql:St.clause}),oe=St.params;return at},at={where:fe("AND"),andWhere:fe("AND"),orWhere:fe("OR")};Q(at);let nt=tn(se);if(!nt)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return v(x,[...C,{conn:I,sql:`(${nt})`}],oe,P)},Y={distinct(){return v(x.replace(/^SELECT\s+/i,"SELECT DISTINCT "),C,k,P)},distinctOn(...I){let Q=I.map(String).join(", ");return v(x.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${Q}) `),C,k,P)},selectRaw(I){let Q=nn(I,"selectFromSub.selectRaw(fragment)"),se=x.indexOf(" FROM "),oe=se!==-1?`${x.slice(0,se)}, ${Q}${x.slice(se)}`:`${x}, ${Q}`;return v(oe,C,k,P)},$call(I){return I(this)??this},where(I,Q,se){return V("AND",I,Q,se)},andWhere(I,Q,se){return V("AND",I,Q,se)},orWhere(I,Q,se){return V("OR",I,Q,se)},whereGroup(I){return U("AND",I)},orWhereGroup(I){return U("OR",I)},orderBy(I,Q="asc"){G(String(I),"selectFromSub.orderBy(column)");let se=Q==="asc"?"ASC":"DESC",oe=he.ORDER_BY.test(P)?`${P}, ${I} ${se}`:`${P} ORDER BY ${I} ${se}`;return v(x,C,k,oe)},limit(I){if(!Number.isInteger(I)||I<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${I}`);let Q=he.LIMIT.test(P)?P.replace(he.LIMIT,` LIMIT ${I}`):`${P} LIMIT ${I}`;return v(x,C,k,Q)},offset(I){if(!Number.isInteger(I)||I<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${I}`);let Q=he.OFFSET.test(P)?P.replace(he.OFFSET,` OFFSET ${I}`):`${P} OFFSET ${I}`;return v(x,C,k,Q)},toSQL(){return N(M(),H)},async execute(){return h(M(),"select")},async executeTakeFirst(){let I=await h(M(),"select");return Array.isArray(I)?I[0]:I},async executeTakeFirstOrThrow(){let I=await h(M(),"select"),Q=Array.isArray(I)?I[0]:I;if(!Q)throw Error("Record not found");return Q},async get(){return h(M(),"select")},async first(){let I=await h(M(),"select");return Array.isArray(I)?I[0]:I},async firstOrFail(){let I=await h(M(),"select"),Q=Array.isArray(I)?I[0]:I;if(!Q)throw Error("No rows found");return Q},async count(){let I=k.length>0?t.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,k):t.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),Q=await h(I,"select");return Number(Q?.[0]?.c??0)},async exists(){let I=k.length>0?t.unsafe(`SELECT EXISTS(${H}) as e`,k):t.unsafe(`SELECT EXISTS(${H}) as e`),Q=await h(I,"select");return Boolean(Q?.[0]?.e)},async doesntExist(){return!await Y.exists()},values(){return M().values()},raw(){return M().raw()},cancel(){try{M().cancel()}catch{}},whereRaw:g("whereRaw"),whereColumn:g("whereColumn"),orWhereColumn:g("orWhereColumn"),whereIn:g("whereIn"),orWhereIn:g("orWhereIn"),whereNotIn:g("whereNotIn"),orWhereNotIn:g("orWhereNotIn"),whereLike:g("whereLike"),whereILike:g("whereILike"),orWhereLike:g("orWhereLike"),orWhereILike:g("orWhereILike"),whereNotLike:g("whereNotLike"),whereNotILike:g("whereNotILike"),orWhereNotLike:g("orWhereNotLike"),orWhereNotILike:g("orWhereNotILike"),whereAny:g("whereAny"),whereAll:g("whereAll"),whereNone:g("whereNone"),whereNested:g("whereNested"),orWhereNested:g("orWhereNested"),whereDate:g("whereDate"),whereBetween:g("whereBetween"),whereNotBetween:g("whereNotBetween"),whereJsonContains:g("whereJsonContains"),whereJsonPath:g("whereJsonPath"),whereNull:g("whereNull"),orWhereNull:g("orWhereNull"),whereNotNull:g("whereNotNull"),orWhereNotNull:g("orWhereNotNull"),whereExists:g("whereExists"),orWhereExists:g("orWhereExists"),orWhereBetween:g("orWhereBetween"),orWhereRaw:g("orWhereRaw"),whereJsonDoesntContain:g("whereJsonDoesntContain"),whereJsonContainsKey:g("whereJsonContainsKey"),whereJsonDoesntContainKey:g("whereJsonDoesntContainKey"),whereJsonLength:g("whereJsonLength"),join:g("join"),joinSub:g("joinSub"),innerJoin:g("innerJoin"),leftJoin:g("leftJoin"),leftJoinSub:g("leftJoinSub"),rightJoin:g("rightJoin"),crossJoin:g("crossJoin"),crossJoinSub:g("crossJoinSub"),groupBy:g("groupBy"),groupByRaw:g("groupByRaw"),having:g("having"),havingRaw:g("havingRaw"),addSelect:g("addSelect"),select:g("select"),selectAll:g("selectAll"),orderByDesc:g("orderByDesc"),inRandomOrder:g("inRandomOrder"),reorder:g("reorder"),orderByRaw:g("orderByRaw"),union:g("union"),unionAll:g("unionAll"),forPage:g("forPage"),selectAllRelations:g("selectAllRelations"),with:g("with"),value:g("value"),pluck:g("pluck"),cursorPaginate:g("cursorPaginate"),paginate:g("paginate"),simplePaginate:g("simplePaginate"),chunk:g("chunk"),chunkById:g("chunkById"),eachById:g("eachById"),avg:g("avg"),sum:g("sum"),max:g("max"),min:g("min"),find:g("find"),findOrFail:g("findOrFail"),findMany:g("findMany"),latest:g("latest"),oldest:g("oldest"),lazy:g("lazy"),lazyById:g("lazyById"),pipe:(I)=>I(Y),when:g("when"),tap:()=>Y,dump:()=>Y,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>M().simple(),toText:()=>H,toParams:()=>[...k],withTimeout:()=>Y,abort:()=>Y,lockForUpdate:()=>Y,sharedLock:()=>Y,withCTE:()=>Y,withRecursive:()=>Y,cache:()=>Y,clone:()=>Y,withTrashed:()=>Y,onlyTrashed:()=>Y,scope:()=>Y,get rows(){return[]},get row(){return}};return Y}return v(B,[],J)},insertInto(y){let b,g="",p=[],E=[],D=!1,J=()=>W?[]:{changes:0,lastInsertRowid:0},B=()=>{let k=async()=>{return},P=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>B(),andWhere:()=>B(),orWhere:()=>B(),orderBy:()=>B(),limit:()=>B(),offset:()=>B(),toSQL:()=>N(null,""),execute:async()=>[],get:async()=>[],first:k,executeTakeFirst:k,firstOrFail:P,executeTakeFirstOrThrow:P}},W=_.dialect==="postgres",v=(k)=>{let q=k.flat(2).map(String).filter(Boolean),H=q.length>0&&!q.includes("*")?q.map((U)=>x(U)).join(", "):"*",M=async()=>{let U=await h(t.unsafe(g,p),"insert"),Y=Number(U?.lastInsertRowid??0),I=Math.max(1,Number(U?.affectedRows??1)),Q=E.filter((fe)=>fe!==void 0&&fe!==null),se=Y>0?t.unsafe(`SELECT ${H} FROM ${x(String(y))} WHERE ${x("id")} >= ? AND ${x("id")} < ? ORDER BY ${x("id")} ASC`,[Y,Y+I]):Q.length>0?t.unsafe(`SELECT ${H} FROM ${x(String(y))} WHERE ${x("id")} IN (${Q.map(()=>"?").join(", ")}) ORDER BY ${x("id")} ASC`,Q):null;if(!se)return[];let oe=await se.execute();return Array.isArray(oe)?oe:[]},V=async()=>(await M())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>N(t.unsafe(g,p),g),execute:M,get:M,first:V,executeTakeFirst:V,async firstOrFail(){let U=await V();if(!U)throw Error("Insert with RETURNING returned no rows");return U},async executeTakeFirstOrThrow(){let U=await V();if(!U)throw Error("Insert with RETURNING returned no rows");return U}}},x=W?(k)=>`"${String(k).replace(/"/g,'""')}"`:ne(_.dialect)?(k)=>`\`${String(k).replace(/`/g,"``")}\``:(k)=>`"${String(k).replace(/"/g,'""')}"`,C=W?(k)=>`$${k+1}`:(k)=>"?";return{values(k){let P=s(String(y),Array.isArray(k)?k:[k]),q=P.length;if(E=P.map((I)=>I?.id),q===0)return D=!0,b=null,g="",p.length=0,this;D=!1;let H=P[0],M=Object.keys(H),V=M.length,U=q*V;p.length=U;let Y=W?M.map((I)=>x(I)).join(","):M.join(",");if(q===1)if(!W){let I=x(M[0]),Q="?";p[0]=H[M[0]];for(let se=1;se<V;se++)I+=`,${x(M[se])}`,Q+=",?",p[se]=H[M[se]];g=`INSERT INTO ${x(y)}(${I})VALUES(${Q})`}else{g=`INSERT INTO ${x(y)}(${Y})VALUES(`;for(let I=0;I<V;I++){if(I>0)g+=",";g+=C(I),p[I]=H[M[I]]}g+=")"}else{let I=M.map((se)=>x(se)).join(",");g=`INSERT INTO ${x(y)}(${I})VALUES`;let Q=0;for(let se=0;se<q;se++){let oe=P[se];if(se===0)g+="(";else g+="),(";for(let fe=0;fe<V;fe++){if(fe>0)g+=",";g+=C(Q),p[Q++]=oe[M[fe]]}}g+=")"}if(!t._prepareStatement)b=t.unsafe(g,p);return this},returning(...k){if(D)return B();if(ne(_.dialect))return v(k);let P=`${g} RETURNING ${k.join(", ")}`,q=t.unsafe(P,p),H=async()=>{let M=await h(q,"insert");return Array.isArray(M)?M[0]:M};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>N(q,P),execute:()=>h(q,"insert"),get:()=>h(q,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let M=await H();if(!M)throw Error("Insert with RETURNING returned no rows");return M},async executeTakeFirstOrThrow(){let M=await H();if(!M)throw Error("Insert with RETURNING returned no rows");return M}}},toSQL(){if(D)return N(null,"");if(!b)b=t.unsafe(g,p);return N(b,g)},execute(){if(D)return Promise.resolve(J());let k=o();if(!(k&&(k.onQueryStart||k.onQueryEnd||k.onQueryError||k.startSpan||k.beforeCreate||k.afterCreate||Hn(k)))){let q=t._prepareStatement;if(q){let H=q(g);return p.length>0?H.run(...p):H.run()}}if(!b)b=t.unsafe(g,p);return h(b,"insert")},async executeTakeFirst(){if(D)return J();if(!b)b=t.unsafe(g,p);return await h(b,"insert")},async executeTakeFirstOrThrow(){if(D)throw Error("Insert failed");if(!b)b=t.unsafe(g,p);let k=await h(b,"insert");if(!k)throw Error("Insert failed");return k},returningAll(){if(D)return B();let k=`${g} RETURNING *`,P=t.unsafe(k,p),q=async()=>{let H=await h(P,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>N(P,k),execute:()=>h(P,"insert"),get:()=>h(P,"insert"),first:q,executeTakeFirst:q,async firstOrFail(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(y){let b,g=[],p=(B)=>{let W=String(B);if(ne(_.dialect))return`\`${W.replace(/`/g,"``")}\``;return`"${W.replace(/"/g,'""')}"`},E=`UPDATE ${p(String(y))}`,D=!1,J=(B)=>{E=`${E} ${D?"AND":"WHERE"} ${B}`,D=!0};return{set(B){let W=s(String(y),[B])[0],v=Object.keys(W),x=v.length,C=Array.from({length:x});for(let k=0;k<x;k++){let P=v[k],q=W[P];if(wt(q))C[k]=`${p(P)} = ${q.raw}`;else if(Vn(q)){let H=Jn(q,g.length+1);C[k]=`${p(P)} = ${H.text}`,g.push(...H.parameters)}else C[k]=`${p(P)} = ${Z(g.length+1)}`,g.push(q)}return E=`${E} SET ${C.join(", ")}`,b=t.unsafe(E,g),this},where(B,W,v){if(W!==void 0&&(typeof B==="string"||wt(B)||Vn(B))){let x=Oe(W,"updateTable.where"),C;if(typeof B==="string")C=p(B);else if(wt(B))C=B.raw;else{let P=Jn(B,g.length+1);C=P.text,g.push(...P.parameters)}if(x.toLowerCase()==="in"||x.toLowerCase()==="not in"){let P=Array.isArray(v)?v:[v],q=ve(P.length,g.length+1);return J(`${C} ${x.toUpperCase()} (${q})`),g.push(...P),b=t.unsafe(E,g),this}let k=g.length+1;return J(`${C} ${x} ${Z(k)}`),g.push(v),b=t.unsafe(E,g),this}if(Array.isArray(B)){let[x,C,k]=B,P=Oe(C,"updateTable.where");if(P.toLowerCase()==="in"||P.toLowerCase()==="not in"){let H=Array.isArray(k)?k:[k],M=ve(H.length,g.length+1);return J(`${p(String(x))} ${P.toUpperCase()} (${M})`),g.push(...H),b=t.unsafe(E,g),this}let q=g.length+1;return J(`${p(String(x))} ${P} ${Z(q)}`),g.push(k),b=t.unsafe(E,g),this}if(wt(B))return J(B.raw),b=t.unsafe(E,g),this;if(Vn(B)){let x=Jn(B,g.length+1);return J(x.text),g.push(...x.parameters),b=t.unsafe(E,g),this}if(B&&typeof B==="object"){let x=Object.keys(B);if(x.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let C=x.map((k)=>fi(p(k),B[k],g));return J(C.join(" AND ")),b=t.unsafe(E,g),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${B===null?"null":typeof B}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(B){return J(`${p(String(B))} IS NULL`),b=t.unsafe(E,g),this},whereNotNull(B){return J(`${p(String(B))} IS NOT NULL`),b=t.unsafe(E,g),this},returning(...B){let W=this,v=()=>`${E} RETURNING ${B.join(", ")}`,x=()=>g.length>0?t.unsafe(v(),g):t.unsafe(v()),C=async()=>{let M=/\sWHERE\s/i.test(E),V=M?E.slice(E.search(/\sWHERE\s/i)+1):"",U=g.slice(g.length-(V.match(/\?|\$\d+/g)?.length??0)),Y=p("id"),I=await(U.length>0?t.unsafe(`SELECT ${Y} FROM ${p(String(y))}${M?` ${V}`:""}`,U):t.unsafe(`SELECT ${Y} FROM ${p(String(y))}${M?` ${V}`:""}`)).execute().catch(()=>[]),Q=(Array.isArray(I)?I:[]).map((fe)=>fe?.id).filter((fe)=>fe!==void 0&&fe!==null);if(await h(g.length>0?t.unsafe(E,g):t.unsafe(E),"update"),Q.length===0)return[];let se=`SELECT ${B.join(", ")} FROM ${p(String(y))} WHERE ${Y} IN (${Q.map(()=>"?").join(", ")})`,oe=await t.unsafe(se,Q).execute();return Array.isArray(oe)?oe:[]},k=()=>ne(_.dialect)?C():h(x(),"update"),P=async()=>{let M=await k();return Array.isArray(M)?M[0]:M},q=(M)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${M}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},H={where:(...M)=>(W.where(...M),H),andWhere:(...M)=>(W.where(...M),H),whereNull:(...M)=>(W.whereNull(...M),H),whereNotNull:(...M)=>(W.whereNotNull(...M),H),orWhere:q("orWhere"),orderBy:q("orderBy"),limit:q("limit"),offset:q("offset"),toSQL:()=>N(x(),v()),execute:k,get:k,first:P,executeTakeFirst:P,async firstOrFail(){let M=await P();if(!M)throw Error("Update with RETURNING returned no rows");return M},async executeTakeFirstOrThrow(){let M=await P();if(!M)throw Error("Update with RETURNING returned no rows");return M}};return H},toSQL(){if(!b)b=g.length>0?t.unsafe(E,g):t.unsafe(E);return N(b,E)},async execute(){let B=await h(b,"update");return w(B)},async executeTakeFirst(){return{numUpdatedRows:w(await h(b,"update"))}},async executeTakeFirstOrThrow(){let B=w(await h(b,"update"));if(B===0)throw Error("No rows updated");return{numUpdatedRows:B}},returningAll(){let B=()=>`${E} RETURNING *`,W=()=>g.length>0?t.unsafe(B(),g):t.unsafe(B());return{toSQL:()=>N(W(),B()),execute:()=>h(W(),"update"),async executeTakeFirst(){let v=await h(W(),"update");return Array.isArray(v)?v[0]:v},async executeTakeFirstOrThrow(){let v=await h(W(),"update"),x=Array.isArray(v)?v[0]:v;if(!x)throw Error("Update with RETURNING failed");return x}}}}},deleteFrom(y){let b=(x)=>{let C=String(x);if(ne(_.dialect))return`\`${C.replace(/`/g,"``")}\``;return`"${C.replace(/"/g,'""')}"`},p=`DELETE FROM ${b(String(y))}`,E=null,D=[],J=null,B=!1,W=(x)=>{p+=` ${B?"AND":"WHERE"} ${x}`,B=!0},v=()=>{if(E===null)E=D.length>0?t.unsafe(p,D):t.unsafe(p);return E};return{where(x,C,k){if(J=x,typeof x==="string"&&C!==void 0){let P=Oe(C,"deleteFrom.where");if(P.toLowerCase()==="in"||P.toLowerCase()==="not in"){let H=Array.isArray(k)?k:[k],M=ve(H.length,D.length+1);return W(`${b(x)} ${P.toUpperCase()} (${M})`),D.push(...H),E=null,this}let q=D.length+1;return W(`${b(x)} ${P} ${Z(q)}`),D.push(k),E=null,this}if(Array.isArray(x)){let[P,q,H]=x,M=Oe(q,"deleteFrom.where");if(M.toLowerCase()==="in"||M.toLowerCase()==="not in"){let U=Array.isArray(H)?H:[H],Y=ve(U.length,D.length+1);return W(`${b(String(P))} ${M.toUpperCase()} (${Y})`),D.push(...U),E=null,this}let V=D.length+1;return W(`${b(String(P))} ${M} ${Z(V)}`),D.push(H),E=null,this}if(wt(x))return W(x.raw),E=null,this;if(Vn(x)){let P=Jn(x,D.length+1);return W(P.text),D.push(...P.parameters),E=null,this}if(x&&typeof x==="object"){let P=Object.keys(x);if(P.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let q=P.map((H)=>fi(b(H),x[H],D));return W(q.join(" AND ")),E=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${x===null?"null":typeof x}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(x){return W(`${b(String(x))} IS NULL`),E=null,this},whereNotNull(x){return W(`${b(String(x))} IS NOT NULL`),E=null,this},returning(...x){let C=this,k=()=>`${p} RETURNING ${x.join(", ")}`,P=()=>D.length>0?t.unsafe(k(),D):t.unsafe(k()),q=async()=>{await o()?.beforeDelete?.({table:String(y),where:J});let U=ne(_.dialect)?await(async()=>{let Y=p.slice(p.search(/\sFROM\s/i)+1),I=`SELECT ${x.join(", ")} ${Y}`,Q=await(D.length>0?t.unsafe(I,D):t.unsafe(I)).execute();return await h(D.length>0?t.unsafe(p,D):t.unsafe(p),"delete"),Array.isArray(Q)?Q:[]})():await h(P(),"delete");try{await o()?.afterDelete?.({table:String(y),where:J,result:U})}catch{}return U},H=async()=>{let U=await q();return Array.isArray(U)?U[0]:U},M=(U)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${U}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},V={where:(...U)=>(C.where(...U),V),andWhere:(...U)=>(C.where(...U),V),whereNull:(...U)=>(C.whereNull(...U),V),whereNotNull:(...U)=>(C.whereNotNull(...U),V),orWhere:M("orWhere"),orderBy:M("orderBy"),limit:M("limit"),offset:M("offset"),toSQL:()=>N(P(),k()),execute:()=>q(),get:()=>q(),first:H,executeTakeFirst:H,async firstOrFail(){let U=await H();if(!U)throw Error("Delete with RETURNING returned no rows");return U},async executeTakeFirstOrThrow(){let U=await H();if(!U)throw Error("Delete with RETURNING returned no rows");return U}};return V},toSQL(){return N(v(),p)},async execute(){try{await o()?.beforeDelete?.({table:String(y),where:J})}catch(C){throw C}let x=w(await h(v(),"delete"));try{await o()?.afterDelete?.({table:String(y),where:J,result:x})}catch{}return x},async executeTakeFirst(){return{numDeletedRows:w(await h(v(),"delete"))}},async executeTakeFirstOrThrow(){let x=w(await h(v(),"delete"));if(x===0)throw Error("No rows deleted");return{numDeletedRows:x}},returningAll(){let x=()=>`${p} RETURNING *`,C=()=>D.length>0?t.unsafe(x(),D):t.unsafe(x());return{toSQL:()=>N(C(),x()),execute:()=>h(C(),"delete"),async executeTakeFirst(){let k=await h(C(),"delete");return Array.isArray(k)?k[0]:k},async executeTakeFirstOrThrow(){let k=await h(C(),"delete"),P=Array.isArray(k)?k[0]:k;if(!P)throw Error("Delete with RETURNING failed");return P}}}}},table(y){let b=this;return{insert(g){return b.insertInto(y).values(g)},update(g){return b.updateTable(y).set(g)},delete(){return b.deleteFrom(y)},select(...g){if(g.length===0)return b.selectFrom(y);return b.select(y,...g)}}},sql:t,raw(y,...b){return t(y,...b)},simple(y,...b){return t(y,...b).simple()},async advisoryLock(y){if(_.dialect==="postgres"){let b=i(y),g=t`SELECT pg_advisory_lock(${b})`;await h(g,"raw");return}if(ne(_.dialect)){let b=`bqb:${String(y)}`,g=t`SELECT GET_LOCK(${b}, -1) AS ok`;await h(g,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(y){if(_.dialect==="postgres"){let b=i(y),g=t`SELECT pg_try_advisory_lock(${b}) as ok`,p=await h(g,"raw");return Boolean(p?.[0]?.ok)}if(ne(_.dialect)){let b=`bqb:${String(y)}`,g=t`SELECT GET_LOCK(${b}, 0) AS ok`,p=await h(g,"raw");return Number(p?.[0]?.ok)===1}return!1},async advisoryUnlock(y){if(_.dialect==="postgres"){let b=i(y),g=t`SELECT pg_advisory_unlock(${b}) as ok`,p=await h(g,"raw");return Boolean(p?.[0]?.ok)}if(ne(_.dialect)){let b=`bqb:${String(y)}`,g=t`SELECT RELEASE_LOCK(${b}) AS ok`,p=await h(g,"raw");return Number(p?.[0]?.ok)===1}return!1},unsafe(y,b){return t.unsafe(y,b)},file(y,b){return t.file(y,b)},async reserve(){let y=await te.reserve(),b=ie({sql:y,meta:n,schema:r,hooks:e?.hooks});return b.release=()=>y.release(),b},async close(y){await te.close(y)},async listen(y,b){},async unlisten(y){},async notify(y,b){},async copyTo(y,b){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(y,b,g){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let y=t`SELECT 1`;return await h(y,"select"),!0}catch{return!1}},async waitForReady(y){let b=Math.max(1,y?.attempts??10),g=Math.max(10,y?.delayMs??100);for(let p=0;p<b;p++){if(await this.ping())return;await new Promise((E)=>setTimeout(E,g))}throw Error("Database not ready after waiting")},async transaction(y,b){let p={...e?.txDefaults,...b},E=e?.sql??te,D=e?.inTransaction===!0,J=D&&typeof E?.savepoint==="function"?"savepoint":"begin",B=async(x)=>{p.logger?.({type:"start",attempt:x});let C=Date.now();return await E[J](async(k)=>{let P=ie({sql:k,meta:n,schema:r,hooks:e?.hooks,inTransaction:!0});if(p?.isolation&&!D){let M=p.isolation,V=M==="read committed"?"READ COMMITTED":M==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(_.dialect==="postgres")await k.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(ne(_.dialect))await k.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(M!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${M}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(p?.readOnly)if(_.dialect==="postgres")await k.unsafe("SET TRANSACTION READ ONLY");else if(ne(_.dialect))await k.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let q=await y(P),H=Date.now()-C;return p.logger?.({type:"commit",attempt:x,durationMs:H}),q})},W=Math.max(0,p?.retries??0),v=0;for(;;)try{let x=await B(v+1);return p?.afterCommit?.(),x}catch(x){let C=kf(x)||Cf(x,p.sqlStates);if(v<W&&C){v++,p?.onRetry?.(v,x);let k=Pf(v,p.backoff);if(k>0)await vf(k);continue}try{p.onRollback?.(x)}catch{}try{p.afterRollback?.()}catch{}throw x}},async savepoint(y){if(e?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let b=t;if(!b||typeof b.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await b.savepoint(async(g)=>{let p=ie({sql:g,meta:n,schema:r,hooks:e?.hooks,inTransaction:!0});return await y(p)})},async beginDistributed(y,b){return await(e?.sql??te).beginDistributed(y,async(E)=>{let D=ie({sql:E,meta:n,schema:r,hooks:e?.hooks});return await b(D)})},async commitDistributed(y){await te.commitDistributed(y)},async rollbackDistributed(y){await te.rollbackDistributed(y)},setTransactionDefaults(y){e={...e,txDefaults:{...e?.txDefaults,...y}}},transactional(y,b){return(...g)=>this.transaction((p)=>y(p,...g),b)},async insertOrIgnore(y,b){let g=Array.isArray(b)?b:[b];if(!g.length)return;let{colsSql:p,valuesSql:E,params:D}=rs(g),J=Ye(String(y)),B=ne(_.dialect)?`INSERT IGNORE INTO ${J} (${p}) VALUES ${E}`:`INSERT INTO ${J} (${p}) VALUES ${E} ON CONFLICT DO NOTHING`;return t.unsafe(B,D).execute()},async insertGetId(y,b,g="id"){let{colsSql:p,valuesSql:E,params:D}=rs([b]),J=Ye(String(y));if(ne(_.dialect)){await t.unsafe(`INSERT INTO ${J} (${p}) VALUES ${E}`,D).execute();let[W]=await t.unsafe("SELECT LAST_INSERT_ID() as id").execute();return W?.id}if(_.dialect==="sqlite"){let W=await t.unsafe(`INSERT INTO ${J} (${p}) VALUES ${E}`,D).execute();if(W?.lastInsertRowid!=null)return W.lastInsertRowid;let[v]=await t.unsafe("SELECT last_insert_rowid() as id").execute();return v?.id}let[B]=await t.unsafe(`INSERT INTO ${J} (${p}) VALUES ${E} RETURNING ${Ye(String(g))} as id`,D).execute();return B?.id},async updateOrInsert(y,b,g){let p=Ye(String(y)),E=Object.keys(b),D=1,J=E.map((k)=>`${Ye(k)} = ${Z(D++)}`).join(" AND "),B=E.map((k)=>b[k]);if((await t.unsafe(`SELECT 1 FROM ${p} WHERE ${J} LIMIT 1`,B).execute()).length){let k=Object.keys(g),P=1,q=k.map((V)=>`${Ye(V)} = ${Z(P++)}`).join(", "),H=E.map((V)=>`${Ye(V)} = ${Z(P++)}`).join(" AND "),M=[...k.map((V)=>g[V]),...E.map((V)=>b[V])];return await t.unsafe(`UPDATE ${p} SET ${q} WHERE ${H}`,M).execute(),!0}let{colsSql:v,valuesSql:x,params:C}=rs([{...b,...g}]);return await t.unsafe(`INSERT INTO ${p} (${v}) VALUES ${x}`,C).execute(),!0},async upsert(y,b,g,p){let E=g.map((q)=>String(q)),D=(p??[]).map((q)=>String(q)),J=b;if(!J.length)return;let{colsSql:B,valuesSql:W,params:v}=rs(J),x=Ye(String(y)),C=`INSERT INTO ${x} (${B}) VALUES ${W}`;if(ne(_.dialect)){if(D.length===0)return t.unsafe(`INSERT IGNORE INTO ${x} (${B}) VALUES ${W}`,v).execute();let q=D.map((H)=>`${Ye(H)} = VALUES(${Ye(H)})`).join(", ");return t.unsafe(`${C} ON DUPLICATE KEY UPDATE ${q}`,v).execute()}let k=E.map(Ye).join(", ");if(D.length===0)return t.unsafe(`${C} ON CONFLICT (${k}) DO NOTHING`,v).execute();let P=D.map((q)=>`${Ye(q)} = EXCLUDED.${Ye(q)}`).join(", ");return t.unsafe(`${C} ON CONFLICT (${k}) DO UPDATE SET ${P}`,v).execute()},async save(y,b){let g=n?.primaryKeys[String(y)]??"id",p=b[g];if(p!=null)if(await this.selectFrom(y).find(p)){await this.updateTable(y).set(b).where({[g]:p}).execute();let D=await this.selectFrom(y).find(p);if(!D)throw Error("save() failed to retrieve updated row");return D}else return await this.create(y,b);return await this.create(y,b)},async remove(y,b){return await this.deleteFrom(y).where({id:b}).execute()},async find(y,b){return await this.selectFrom(y).find(b)},async findOrFail(y,b){return await this.selectFrom(y).findOrFail(b)},async findMany(y,b){return await this.selectFrom(y).findMany(b)},async latest(y,b){return await this.selectFrom(y).latest(b).first()},async oldest(y,b){return await this.selectFrom(y).oldest(b).first()},skip(y,b){return this.selectFrom(y).offset(b)},async rawQuery(y){let b=Date.now();try{o()?.onQueryStart?.({sql:y,kind:"raw"});let g=await t.unsafe(y);return o()?.onQueryEnd?.({sql:y,durationMs:Date.now()-b,kind:"raw"}),g}catch(g){throw o()?.onQueryError?.({sql:y,error:g,durationMs:Date.now()-b,kind:"raw"}),g}},async create(y,b){let g=n?.primaryKeys[String(y)]??"id";try{await o()?.beforeCreate?.({table:String(y),data:b})}catch(p){throw p}if(_.dialect==="postgres"){let p=t`INSERT INTO ${t(String(y))} ${t(b)} RETURNING ${t(String(g))} as id`,[E]=await p.execute();if(!E?.id)throw console.error(`create() failed to get insert ID for table ${String(y)}`),console.error("Inserted values:",b),Error(`create() failed to get insert ID for table ${String(y)}`);let D=await this.selectFrom(y).find(E.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(y)} with id ${E.id}`),console.error("Inserted values:",b),Error(`create() failed to retrieve inserted row for table ${String(y)} with id ${E.id}`);try{await o()?.afterCreate?.({table:String(y),data:b,result:D})}catch{}return D}else{let p=await this.insertGetId(y,b,g);if(p==null)throw Error(`create() failed to get insert ID for table ${String(y)}`);let E=await this.selectFrom(y).find(p);if(!E)throw console.error(`create() failed to retrieve inserted row for table ${String(y)} with id ${p}`),console.error("Inserted values:",b),Error(`create() failed to retrieve inserted row for table ${String(y)} with id ${p}`);try{await o()?.afterCreate?.({table:String(y),data:b,result:E})}catch{}return E}},async createMany(y,b){if(!b?.length)return;let g=b[0],p=Object.keys(g),E=p.length,D=b.length,J=Array.from({length:D*E}),B=ne(_.dialect)?(x)=>`\`${String(x).replace(/`/g,"``")}\``:(x)=>`"${String(x).replace(/"/g,'""')}"`,W=`INSERT INTO ${B(String(y))}(${p.map(B).join(",")})VALUES`,v=0;for(let x=0;x<D;x++){if(x>0)W+=",";W+="(";let C=b[x];for(let k=0;k<E;k++){if(k>0)W+=",";W+=Z(v+1),J[v++]=C[p[k]]}W+=")"}return t.unsafe(W,J).execute()},async insertMany(y,b){if(!b?.length)return;let g=b[0],p=Object.keys(g),E=p.length,D=b.length,J=D*E,B=Array(J),W=_.dialect==="postgres",v;if(!W){let k=Array(E);for(let P=0;P<E;P++)k[P]="?";v=`(${k.join(",")})`}else v="";let x=Array(D+2);x[0]=`INSERT INTO ${y}(${p.join(",")})VALUES`;let C=0;if(!W){for(let k=0;k<D;k++){let P=b[k];x[k+1]=v;for(let q=0;q<E;q++)B[C++]=P[p[q]]}return t.unsafe(x[0]+x.slice(1,D+1).join(","),B).execute()}for(let k=0;k<D;k++){let P=b[k],q=Array(E);for(let H=0;H<E;H++)q[H]=`$${C+1}`,B[C++]=P[p[H]];x[k+1]=`(${q.join(",")})`}return t.unsafe(x[0]+x.slice(1,D+1).join(","),B).execute()},async updateMany(y,b,g){let p=Object.keys(g),E=p.length;if(E===0)return 0;let D=[],J=Array.from({length:E});for(let W=0;W<E;W++)J[W]=`${p[W]}=${Z(W+1)}`,D.push(g[p[W]]);let B=`UPDATE ${y} SET ${J.join(",")}`;if(Array.isArray(b)){let W=Oe(String(b[1]),"updateMany");B+=` WHERE ${b[0]} ${W} ${Z(D.length+1)}`,D.push(b[2])}else if(wt(b))B+=` WHERE ${b.raw}`;else if(Vn(b)){let W=Jn(b,D.length+1);B+=` WHERE ${W.text}`,D.push(...W.parameters)}else if(b&&typeof b==="object"&&Object.keys(b).length>0){let W=Object.keys(b).map((v)=>fi(v,b[v],D));B+=` WHERE ${W.join(" AND ")}`}else if(b&&typeof b==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${b===null?"null":typeof b}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return t.unsafe(B,D).execute()},async deleteMany(y,b){if(!Array.isArray(b)||b.length===0)return 0;let g=n?.primaryKeys[String(y)]??"id",p=b.length;if(_.dialect==="postgres"){let D=Array(p);for(let J=0;J<p;J++)D[J]=`$${J+1}`;return t.unsafe(`DELETE FROM ${y} WHERE ${g} IN (${D.join(",")})`,b).execute()}let E=Array(p);for(let D=0;D<p;D++)E[D]="?";return t.unsafe(`DELETE FROM ${y} WHERE ${g} IN (${E.join(",")})`,b).execute()},async firstOrCreate(y,b,g){let p=await this.selectFrom(y).where(b).first();if(p)return p;return await this.create(y,{...b,...g})},async updateOrCreate(y,b,g){let p=await this.selectFrom(y).where(b).first();if(p){await this.updateTable(y).set(g).where(b).execute();let E=n?.primaryKeys[String(y)]??"id",D=p[E],J=D!=null?await this.selectFrom(y).find(D):await this.selectFrom(y).where(b).first();if(!J)throw Error("updateOrCreate() failed to retrieve updated row");return J}return await this.create(y,{...b,...g})},async count(y,b){let g=b?t(String(b)):t`*`,p=t`SELECT COUNT(${g}) as c FROM ${t(String(y))}`,[E]=await p.execute();return Number(E?.c??0)},async sum(y,b){let g=t`SELECT SUM(${t(String(b))}) as s FROM ${t(String(y))}`,[p]=await g.execute();return Number(p?.s??0)},async avg(y,b){let g=t`SELECT AVG(${t(String(b))}) as a FROM ${t(String(y))}`,[p]=await g.execute();return Number(p?.a??0)},async min(y,b){let g=t`SELECT MIN(${t(String(b))}) as m FROM ${t(String(y))}`,[p]=await g.execute();return p?.m},async max(y,b){let g=t`SELECT MAX(${t(String(b))}) as m FROM ${t(String(y))}`,[p]=await g.execute();return p?.m},getRelationships(y){if(!n?.relations)return{};let b=n.relations[y];if(!b)return{};let g={};for(let[p,E]of Object.entries(b))if(E&&typeof E==="object"&&Object.keys(E).length>0)g[p]=E;return g},hasRelationship(y,b){if(!n?.relations)return!1;let g=n.relations[y];if(!g)return!1;return Object.values(g).some((p)=>p&&typeof p==="object"&&(b in p))},getRelationshipType(y,b){if(!n?.relations)return null;let g=n.relations[y];if(!g)return null;for(let[p,E]of Object.entries(g))if(E&&typeof E==="object"&&b in E)return p;return null},getRelationshipTarget(y,b){if(!n?.relations)return null;let g=n.relations[y];if(!g)return null;for(let[p,E]of Object.entries(g))if(E&&typeof E==="object"&&b in E){let D=E[b];if(typeof D==="string")return n.modelToTable[D]||D;else if(D&&typeof D==="object"){if("model"in D)return n.modelToTable[D.model]||D.model;if("target"in D)return n.modelToTable[D.target]||D.target}}return null}}}function qa(){is.clear()}function ja(e){is.setMaxSize(e)}async function _f(){console.log("-- Clearing query cache..."),qa(),console.log("-- \u2713 Query cache cleared")}async function If(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function Lf(e={}){if(console.log("-- Configuring query cache..."),console.log(),e.size!==void 0){let t=Number(e.size);if(Number.isNaN(t)||t<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");ja(t),console.log(`-- \u2713 Cache max size set to: ${t}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}import os from"process";import{createInterface as Kf}from"readline";async function Wa(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let e=ie(),t=Kf({input:os.stdin,output:os.stdout,prompt:"qb> "}),n="",r=!1,s=`
113
+ `,[`User ${o}`,`user${o}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(o){throw console.error("-- Failed to setup test table:",o),o}let s=[];if(n.includes("select")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.selectFrom("bench_users").where({active:1}).limit(10).execute(),o.push(performance.now()-a)}s.push({operation:"SELECT with WHERE + LIMIT",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("select")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.selectFrom("bench_users").where({id:1}).first(),o.push(performance.now()-a)}s.push({operation:"SELECT by ID (first)",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("count")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.selectFrom("bench_users").count(),o.push(performance.now()-a)}s.push({operation:"COUNT",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("insert")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.insertInto("bench_users").values({name:`Bench User ${l}`,email:`bench${l}@example.com`,created_at:new Date().toISOString()}).execute(),o.push(performance.now()-a)}s.push({operation:"INSERT",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("update")){let o=[];for(let l=0;l<t;l++){let a=performance.now();await r.updateTable("bench_users").set({active:0}).where({id:1}).execute(),o.push(performance.now()-a)}s.push({operation:"UPDATE by ID",avgTime:o.reduce((l,a)=>l+a,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}if(n.includes("delete")){let o=[],l=[];for(let a=0;a<t;a++){let c=await r.insertInto("bench_users").values({name:"To Delete",email:`delete${a}@example.com`,created_at:new Date().toISOString()}).execute();l.push(c)}for(let a=0;a<t;a++){let c=performance.now();await r.deleteFrom("bench_users").where({id:l[a]}).execute(),o.push(performance.now()-c)}s.push({operation:"DELETE by ID",avgTime:o.reduce((a,c)=>a+c,0)/o.length,minTime:Math.min(...o),maxTime:Math.max(...o),iterations:t})}console.log("-- Benchmark Results"),console.log();let i=Math.max(...s.map((o)=>o.operation.length));console.log("Operation".padEnd(i+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(i+2+12+12+12+12));for(let o of s){let l=o.operation.padEnd(i+2),a=o.avgTime.toFixed(3).padStart(12),c=o.minTime.toFixed(3).padStart(12),u=o.maxTime.toFixed(3).padStart(12),m=(1000/o.avgTime).toFixed(0).padStart(12);console.log(`${l}${a}${c}${u}${m}`)}console.log();try{await te.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(o){console.error("-- Warning: Failed to cleanup test table:",o)}}Me();Ft();Me();Wt();function Df(e){return jt(_.relations?.singularizeStrategy)(e)}function en(e,t,n,r={}){let s=r.singularize??Df,o=e.relations?.[t]?.belongsToMany?.[n];if(o==null)return null;let l=typeof o==="object",a=l?o:null,c=l?a.model:o,u=e.modelToTable[c]||c,m,h;if(a?.table)m=a.table;else if(a?.through){if(h=a.through,m=e.modelToTable[a.through],!m)throw Error(`[query-builder] belongsToMany relation '${n}' on '${t}' references unknown through model '${a.through}'. Make sure '${a.through}' is registered via defineModels({...}).`)}else{let g=s(t),p=s(u);m=[g,p].sort().join("_")}let w=a?.foreignKey??`${s(t)}_id`,N=a?.relatedKey??`${s(u)}_id`,R={};if(a?.pivot?.columns)Object.assign(R,a.pivot.columns);if(h&&r.models){let g=r.models[h],p=g?.definition??g?.getDefinition?.()??g,E=p?.attributes??{};for(let[D,J]of Object.entries(E)){if(D===w||D===N||D===(p?.primaryKey??"id"))continue;R[D]={default:J?.default,nullable:J?.nullable,validation:J?.validation}}}let y=Boolean(a?.pivot?.timestamps),b=Object.keys(R);return{pivotTable:m,fkParent:w,fkRelated:N,pivotColumns:b,pivotColumnDefs:R,pivotModelName:h,timestamps:y,relatedModelName:c,relatedTable:u,hasConfig:l}}function*Bp(e,t={}){let n=e.relations;if(!n)return;for(let[r,s]of Object.entries(n)){let i=s?.belongsToMany;if(!i)continue;for(let o of Object.keys(i)){let l=en(e,r,o,t);if(l)yield{parentTable:r,relationKey:o,resolved:l}}}}Wt();ns();function wt(e){return typeof e==="object"&&e!==null&&"raw"in e&&typeof e.raw==="string"}function yi(e,t,n){if(Array.isArray(t)){let s=ve(t.length,n.length+1),i=Ge(e,t,!1,s);return n.push(...t),i}let r=`${e} = ${Z(n.length+1)}`;return n.push(t),r}function Jn(e){return typeof e==="object"&&e!==null&&"sql"in e&&typeof e.sql==="string"&&(!("parameters"in e)||Array.isArray(e.parameters))}function Hn(e,t){let n=e.parameters??[];if(_.dialect!=="postgres"||n.length===0)return{text:e.sql,parameters:n};let r=0,s=e.sql.replace(/\?/g,(i)=>{if(r>=n.length)return i;return Z(t+r++)});if(r!==n.length)throw TypeError(`[query-builder] SQL expression declares ${n.length} parameters but contains only ${r} placeholders`);return{text:s,parameters:n}}function jp(e,...t){if(typeof e==="string")return{raw:e};let n=e[0];for(let r=0;r<t.length;r++)n+=At(t[r])+e[r+1];return{raw:n}}function Ye(e){return ne(_.dialect)?`\`${e.replace(/`/g,"``")}\``:`"${e.replace(/"/g,'""')}"`}function rs(e,t=1){let n=Object.keys(e[0]??{}),r=[],s=t,i=e.map((o)=>`(${n.map((a)=>(r.push(o[a]),Z(s++))).join(", ")})`);return{colsSql:n.map(Ye).join(", "),valuesSql:i.join(", "),params:r,nextIndex:s}}function zn(e){return Boolean(e&&(e.onSlowQuery||e.slowQueryThresholdMs!=null&&e.slowQueryThresholdMs>=0))}function ot(e,t=_.dialect){if(!ne(t))return e;let n=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(e.trim());if(!n)return e;let[,r,s,i]=n,o=s?`\`${r}\`.\`${s}\``:`\`${r}\``;return i?`${o} AS \`${i}\``:o}function $f(e,t=_.dialect){if(!ne(t)||e===null||e===void 0)return e;if(typeof e==="string"){let n=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(e);if(!n)return e;let[,r,s]=n;return`${r} ${s.length===5?`${s}:00`:s}`}if(!(e instanceof Date)||Number.isNaN(e.getTime()))return e;return e.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function La(e){if(typeof e==="string")return ot(e);if(wt(e))return e.raw;if(e&&typeof e==="object"){let t=e;if(typeof t.raw==="function")return String(t.raw());if(typeof t.sql==="string")return t.sql;let n=String(e);if(n!=="[object Object]")return n}throw TypeError(`[query-builder] select(): unsupported column ${String(e)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Ef(e){let t=/\(|\)|\bORDER\s+BY\b/gi,n=0,r;while(r=t.exec(e))if(r[0]==="(")n++;else if(r[0]===")")n=Math.max(0,n-1);else if(n===0)return!0;return!1}var he={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},Ka=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function G(e,t){if(!he.IDENTIFIER.test(e)){let n=t?` in ${t}`:"";throw Error(`[query-builder] Invalid identifier${n}: '${e}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function Oe(e,t){if(typeof e!=="string")throw TypeError(`[query-builder] ${t}: operator must be a string, got ${typeof e}`);let n=e.toLowerCase();if(!Ka.has(n))throw TypeError(`[query-builder] ${t}: refusing to use '${e}' as a SQL operator \u2014 not in the allowed set (${[...Ka].join(", ")})`);return e}function it(e,t){if(typeof e!=="string"||e.length===0)throw TypeError(`[query-builder] ${t}: identifier must be a non-empty string, got ${typeof e}`);if(e.length>129)throw TypeError(`[query-builder] ${t}: identifier '${e}' too long`);let n=e.split(".");if(n.length>2)throw TypeError(`[query-builder] ${t}: identifier '${e}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let r of n)if(!/^[A-Z_][A-Z0-9_]*$/i.test(r))throw TypeError(`[query-builder] ${t}: identifier segment '${r}' contains characters outside [A-Za-z0-9_]`)}function nn(e,t){if(typeof e==="string")return xf(t),e;if(e===null||e===void 0)throw TypeError(`[query-builder] ${t}: fragment must be a SqlFragment, got ${e}`);if(wt(e))return e.raw;if(typeof e==="object"){let n=e;if(typeof n.raw==="string")return n.raw;if(typeof n.raw==="function"){let s=n.raw();if(typeof s==="string")return s}if(typeof n.sql==="string")return n.sql;let r=String(e);if(r!=="[object Object]"&&r!=="[object Promise]")return r}throw TypeError(`[query-builder] ${t}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}var Fa=new Set;function xf(e){if(Fa.has(e))return;Fa.add(e),console.warn(`[query-builder] ${e}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function Rf(e,t=_.dialect){return ne(t)?e.replace(/\\/g,"\\\\").replace(/'/g,"''"):e.replace(/'/g,"''")}function At(e){if(e===null)return"NULL";if(typeof e==="number"&&Number.isFinite(e))return String(e);if(typeof e==="boolean")return e?"1":"0";if(typeof e==="string")return`'${Rf(e)}'`;if(e instanceof Date)return`'${e.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof e}`)}function kf(e,t){let n=Array.isArray(e)?e:e?[e]:[],r=[];if(n.length)r.push(`PARTITION BY ${n.join(", ")}`);if(t&&t.length)r.push(`ORDER BY ${t.map(([s,i])=>`${s} ${i==="desc"?"DESC":"ASC"}`).join(", ")}`);return r.length?`OVER (${r.join(" ")})`:"OVER ()"}class qa{cache=new Map;maxSize=100;get(e){let t=this.cache.get(e);if(!t)return null;if(Date.now()>t.expiresAt)return this.cache.delete(e),null;return this.cache.delete(e),this.cache.set(e,t),t.data}set(e,t,n){if(this.cache.has(e))this.cache.delete(e);if(this.cache.size>=this.maxSize){let r=Date.now(),s=!1;for(let[i,o]of this.cache)if(r>o.expiresAt){if(this.cache.delete(i),s=!0,this.cache.size<this.maxSize)break}if(!s){let i=this.cache.keys().next().value;if(i!==void 0)this.cache.delete(i)}}this.cache.set(e,{data:t,expiresAt:Date.now()+n})}clear(){this.cache.clear()}setMaxSize(e){this.maxSize=Math.max(0,Math.floor(e));while(this.cache.size>this.maxSize){let t=this.cache.keys().next().value;if(t===void 0)break;this.cache.delete(t)}}}var is=new qa;function Cf(e){let t=String(e?.message||"").toLowerCase();return t.includes("deadlock")||t.includes("serialization failure")||t.includes("could not serialize access")||t.includes("deadlock found when trying to get lock")||t.includes("lock wait timeout exceeded")||t.includes("database is locked")||t.includes("busy")}function vf(e,t){if(!t||t.length===0)return!1;let n=e&&(e.code||e.sqlState||e.sqlstate);if(!n)return!1;return t.includes(n)}function Af(e){return new Promise((t)=>setTimeout(t,e))}var ss=new Map,Nf=500,Mf=[{key:"GROUP_BY",pattern:/GROUP\s+BY\b/iy},{key:"ORDER_BY",pattern:/ORDER\s+BY\b/iy},{key:"HAVING",pattern:/HAVING\b/iy},{key:"OFFSET",pattern:/OFFSET\b/iy},{key:"LIMIT",pattern:/LIMIT\b/iy},{key:"WHERE",pattern:/WHERE\b/iy}],Of=[{key:"tail",pattern:/GROUP\s+BY\b/iy},{key:"tail",pattern:/ORDER\s+BY\b/iy},{key:"tail",pattern:/HAVING\b/iy},{key:"tail",pattern:/LIMIT\b/iy},{key:"tail",pattern:/OFFSET\b/iy},{key:"tail",pattern:/WINDOW\b/iy},{key:"tail",pattern:/UNION\b/iy},{key:"tail",pattern:/INTERSECT\b/iy},{key:"tail",pattern:/EXCEPT\b/iy},{key:"tail",pattern:/FOR\s+UPDATE\b/iy},{key:"tail",pattern:/FOR\s+SHARE\b/iy},{key:"tail",pattern:/LOCK\s+IN\s+SHARE\s+MODE\b/iy}],Bf=[{key:"cut",pattern:/GROUP\s+BY\b/iy},{key:"cut",pattern:/ORDER\s+BY\b/iy},{key:"cut",pattern:/WHERE\b/iy},{key:"cut",pattern:/HAVING\b/iy},{key:"cut",pattern:/LIMIT\b/iy},{key:"cut",pattern:/OFFSET\b/iy},{key:"cut",pattern:/UNION\b/iy}];function Gn(e){let t=ss.get(e);if(t!==void 0)return t;let n=Pf(e);if(ss.size>=Nf)ss.clear();return ss.set(e,n),n}function Pf(e){let t=ts(e,Mf);if(t.length<=1)return e;let n=e.slice(0,t[0].start).trimEnd(),r={};for(let o=0;o<t.length;o++){let l=t[o].start,a=o+1<t.length?t[o+1].start:e.length,c=e.slice(l,a).trim();if(!r[t[o].key])r[t[o].key]=[];r[t[o].key].push(c)}let i=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((o)=>r[o]).map((o)=>r[o].join(" ")).join(" ");return i?`${n} ${i}`:n}function _f(e,t){let n=Math.max(1,t?.baseMs??50),r=Math.max(1,t?.factor??2),s=Math.max(n,t?.maxMs??2000),i=Math.min(s,n*r**Math.max(0,e-1));if(t?.jitter)i=Math.min(s,i*(0.9+Math.random()*0.2));return Math.floor(i)}function ie(e){let t=e?.sql??Kt(),n=e?.meta,r=e?.schema,s=(y,b)=>{let g=n?.temporalColumns?.[y];if(!g||g.length===0||!ne(_.dialect))return b;return b.map((p)=>{let E=null;for(let D of g){if(!(D in p))continue;let J=$f(p[D]);if(J!==p[D])E=E??{...p},E[D]=J}return E??p})};function i(y){if(typeof y==="number")return y;let b=String(y),g=7;for(let p=0;p<b.length;p++)g=g*31+b.charCodeAt(p)|0;return Math.abs(g)}function o(){if(!e?.hooks)return _.hooks;return{..._.hooks,...e.hooks}}let l=new Map;function a(y){if(Array.isArray(y)){let[D,J,B]=y;G(D,"where(column)");let W=String(D);switch(J){case"in":if(Array.isArray(B)){let v=ve(B.length);return t.unsafe(`${W} IN (${v})`,B)}return t.unsafe(`${W} IN (${Z(1)})`,[B]);case"not in":if(Array.isArray(B)){let v=ve(B.length);return t.unsafe(`${W} NOT IN (${v})`,B)}return t.unsafe(`${W} NOT IN (${Z(1)})`,[B]);case"like":return t.unsafe(`${W} LIKE ${Z(1)}`,[B]);case"is":case"is not":{if(B!==null&&B!==void 0)throw TypeError(`[query-builder] where(..., '${J}', ?): operator '${J}' only accepts NULL/undefined as value, got ${typeof B} (${String(B)})`);return t.unsafe(`${W} IS ${J==="is not"?"NOT ":""}NULL`)}case"!=":return t.unsafe(`${W} <> ${Z(1)}`,[B]);case"<":case">":case"<=":case">=":case"=":return t.unsafe(`${W} ${J} ${Z(1)}`,[B]);default:throw TypeError(`[query-builder] where(..., '${String(J)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in y)return y.raw;let b=Object.keys(y);if(b.length===0)return t.unsafe("");let g=[],p=[],E=1;for(let D of b){G(D,"where(object key)");let J=y[D];if(Array.isArray(J)){let B=ve(J.length,E);g.push(`${D} IN (${B})`),p.push(...J),E+=J.length}else g.push(`${D} = ${Z(E++)}`),p.push(J)}return t.unsafe(g.join(" AND "),p)}function c(y,b,g){if(!g)return b;let p=a(g);return t`${b} WHERE ${p}`}function u(y){let b=_.debug?.captureText;if(_.debug)_.debug.captureText=!0;let g=String(y);if(_.debug)_.debug.captureText=b;return g}function m(y){if(!y||typeof y!=="object")return;if(Array.isArray(y.values))return y.values;if(Array.isArray(y.parameters))return y.parameters;if(Array.isArray(y.params))return y.params;return}function h(y,b,g){let p=o(),E=p?.slowQueryThresholdMs,D=E!=null&&E>=0,J=Boolean(p?.onSlowQuery||D),B=p&&(p.onQueryStart||p.onQueryEnd||p.onQueryError||p.startSpan||J),W=g?.timeoutMs&&g.timeoutMs>0||g?.signal;if(!B&&!W)return y.execute();let v=u(y),x=m(y),C=Date.now(),k;try{if(p?.onQueryStart?.({sql:v,params:x,kind:b}),p?.startSpan)k=p.startSpan({sql:v,params:x,kind:b})}catch{}let P=!1,q=(U,Y)=>{if(P)return;P=!0;let I=Date.now()-C;try{if(U)p?.onQueryError?.({sql:v,params:x,error:U,durationMs:I,kind:b});else if(p?.onQueryEnd?.({sql:v,params:x,durationMs:I,rowCount:Y,kind:b}),D&&I>=E)if(p?.onSlowQuery)p.onSlowQuery({sql:v,params:x,durationMs:I,kind:b});else console.warn(`[query-builder] slow query (${I}ms >= ${E}ms): ${v}`)}catch{}try{k?.end(U)}catch{}},H=y.execute(),M=[H],V;if(g?.timeoutMs&&g.timeoutMs>0){let U=new Promise((Y,I)=>{V=setTimeout(()=>{try{y.cancel?.()}catch{}let Q=Error(`Query timed out after ${g.timeoutMs}ms`);Q.code="EBQBTIMEOUT",I(Q)},g.timeoutMs)});M.push(U)}if(g?.signal){if(g.signal.aborted){try{y.cancel?.()}catch{}let Y=Error("Query aborted");return Y.code="EBQBABORT",q(Y),Promise.reject(Y)}let U=()=>{try{y.cancel?.()}catch{}};g.signal.addEventListener("abort",U,{once:!0}),H.finally(()=>{g.signal?.removeEventListener("abort",U)})}return Promise.race(M).then((U)=>{clearTimeout(V);let Y=Array.isArray(U)?U.length:typeof U==="number"?U:void 0;return q(void 0,Y),U}).catch((U)=>{throw clearTimeout(V),q(U),U})}function w(y){if(typeof y==="number")return Number.isFinite(y)?y:0;if(typeof y==="bigint")return Number(y);if(!y||typeof y!=="object")return 0;let b=y;for(let g of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(b[g]!==void 0&&b[g]!==null)return w(b[g]);if(Array.isArray(y))return y.reduce((g,p)=>g+w(p),0);return 0}function N(y,b){let g=b??u(y);return{sql:g,toString:()=>g,execute:()=>y.execute(),values:()=>y.values(),raw:()=>y.raw()}}function R(y,b){let g=t,p=b&&b.length>0?`SELECT ${b.join(", ")} FROM ${String(y)}`:`SELECT * FROM ${String(y)}`,E=[],D=[],J=!1,B=!1,W=!1,v=null,x=()=>{if(v===null){let d=Gn(q());v=D.length>0?t.unsafe(d,D):t.unsafe(d)}return v},C=(d,f)=>{E.push({conn:d,sql:f}),v=null},k=(d,f)=>{C(d==="OR"?"OR":"AND",f)},P=(d)=>{let f=ts(d,Of,1);return f.length>0?f[0].start:-1},q=(d)=>{let f=tn(d?[...E,d]:E);if(!f)return p;if(J)return`${p} ${B?"AND":"WHERE"} ${f}`;let T=P(p);return T>=0?`${p.slice(0,T)}WHERE ${f} ${p.slice(T)}`:`${p} WHERE ${f}`},H=(d,f)=>{let T=R(y);f(T);let S=T.__whereState?.();if(!S||!S.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let A=D.length,O=A>0&&_.dialect==="postgres"?S.body.replace(/\$(\d+)/g,(K,F)=>`$${Number(F)+A}`):S.body;D.push(...S.params),C(d,`(${O})`)},M=(d,f,T,S,A,O)=>{if(typeof S==="string"&&A!==void 0){G(String(S),`${T}(column)`),Oe(A,`${T}(operator)`);let K=D.length+1;return D.push(O),C(f,`${String(S)} ${String(A)} ${Z(K)}`),d}if(Array.isArray(S)){let[K,F,z]=S,L=String(K);G(L,`${T}(column)`);let j=Oe(F,`${T}(operator)`);if(j==="in"||j==="not in"){let X=Array.isArray(z)?z:[z],ae=ve(X.length,D.length+1),Ae=Ge(ot(L),X,j==="not in",ae);D.push(...X),C(f,Ae)}else{let X=D.length+1;D.push(z),C(f,`${L} ${j} ${Z(X)}`)}return d}if(typeof S==="function")return H(f,S),d;if(S&&typeof S==="object"&&!("raw"in S)){let K=[];for(let F of Object.keys(S)){G(F,`${T}(column)`);let z=S[F];if(Array.isArray(z)){let L=ve(z.length,D.length+1);K.push(Ge(ot(F),z,!1,L)),D.push(...z)}else{let L=D.length+1;K.push(`${F} = ${Z(L)}`),D.push(z)}}if(K.length>0)C(f,K.length>1?`(${K.join(" AND ")})`:K[0]);return d}if(S&&typeof S.raw<"u")return C(f,S.raw),d;return d},V=(d,f)=>{if(E.length>0)p=q(),E.length=0;J=!0;let T=f.__rawState?.();if(T){let S=D.length,A=_.dialect==="postgres"?T.sql.replace(/\$(\d+)/g,(O,K)=>`$${Number(K)+S}`):T.sql;p+=` ${d} ${A}`,D.push(...T.params),B=f.__hasPredicate?.()??he.WHERE.test(A)}else{let S=String(f.toSQL());p+=` ${d} ${S}`,B=f.__hasPredicate?.()??he.WHERE.test(S)}v=null},U=(d)=>{let f=ts(p,Bf,1),T=f.length>0?f[0].start:-1;p=T>=0?`${p.slice(0,T)}${d} ${p.slice(T)}`:`${p} ${d}`,v=null},Y=new Set,I,Q,se=!1,oe=!1,fe=!1,at=new Map,nt=new Set,ln=60000,Se=(d)=>jt(_.relations.singularizeStrategy)(d),yt=(d)=>{if(!n)return null;return en(n,String(y),d,{singularize:Se,models:n.models})},Gt=(d)=>{if(!d||typeof d!=="object"||nt.size===0)return d;let f;for(let T of Object.keys(d))if(T.startsWith("pivot_")){if(!f)f={};f[T.slice(6)]=d[T],delete d[T]}if(f)d.pivot=f;return d},$t=(d)=>{if(nt.size===0||!d)return d;if(Array.isArray(d))for(let f=0;f<d.length;f++)Gt(d[f]);else Gt(d);return d},On=(d)=>{if(!n)return;if(Y.has(d.pivotTable))return;let f=String(y),T=n.primaryKeys[f]??"id";G(d.pivotTable,"wherePivot auto-join (pivot table)"),G(d.fkParent,"wherePivot auto-join (parent FK)"),G(f,"wherePivot auto-join (parent table)"),G(T,"wherePivot auto-join (parent PK)"),v=g`${x()} LEFT JOIN ${g(d.pivotTable)} ON ${g(`${d.pivotTable}.${d.fkParent}`)} = ${g(`${f}.${T}`)}`,p=`${p} LEFT JOIN ${d.pivotTable} ON ${d.pivotTable}.${d.fkParent} = ${f}.${T}`,Y.add(d.pivotTable)},Bn=(d)=>{if(he.SELECT_STAR.test(p))p=p.replace(he.SELECT_STAR,`SELECT *, ${d}`);else if(he.SELECT.test(p))p=p.replace(he.SELECT_FROM,`SELECT $1, ${d} FROM`);let f=String(x());if(he.SELECT_STAR.test(f)){let T=f.replace(he.SELECT_STAR,`SELECT *, ${d}`);v=t.unsafe(T)}else if(he.SELECT.test(f)){if(he.SELECT_FROM.exec(f)){let S=f.replace(he.SELECT_FROM,`SELECT $1, ${d} FROM`);v=t.unsafe(S)}}},ht=(d,f,T,S)=>{Bn(`${d} ${kf(T,S)} AS ${f}`)},ir=(d,f,T,S)=>{G(d,"relationship subquery (parent table)"),G(f,"relationship subquery (target table)"),G(T,"relationship subquery (primary key)");let A=`${d.endsWith("s")?d.slice(0,-1):d}_id`;G(A,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${f} WHERE ${f}.${A} = ${d}.${T}`;if(S){let F=S({where:(z,L,j)=>(G(z,"relationship subquery condition"),`${f}.${z} ${Oe(L,"whereHas callback")} ${At(j)}`)});if(F)O+=` AND ${F}`}return O},or=(d,f,T,S)=>{G(d,"relationship subquery (parent table)"),G(f,"relationship subquery (target table)"),G(T,"relationship subquery (primary key)");let A=`${f.endsWith("s")?f.slice(0,-1):f}_id`;G(A,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${f} WHERE ${f}.${T} = ${d}.${A}`;if(S){let F=S({where:(z,L,j)=>(G(z,"relationship subquery condition"),`${f}.${z} ${Oe(L,"whereHas callback")} ${At(j)}`)});if(F)O+=` AND ${F}`}return O},ar=(d,f,T,S,A,O)=>{G(d,"relationship subquery (parent table)"),G(f,"relationship subquery (target table)"),G(T,"relationship subquery (primary key)"),G(S,"relationship subquery (target primary key)");let K=O&&n?en(n,d,O,{singularize:Se,models:n.models}):null,F=Se(d),z=Se(f),L=K?.pivotTable??[F,z].sort().join("_"),j=K?.fkParent??`${F}_id`,X=K?.fkRelated??`${z}_id`;G(L,"relationship subquery (pivot table)"),G(j,"relationship subquery (foreign key A)"),G(X,"relationship subquery (foreign key B)");let ae=`SELECT 1 FROM ${L} JOIN ${f} ON ${f}.${S} = ${L}.${X} WHERE ${L}.${j} = ${d}.${T}`;if(A){let ee=A({where:(Ne,Ue,Je)=>(G(Ne,"relationship subquery condition"),`${f}.${Ne} ${Oe(Ue,"whereHas callback")} ${At(Je)}`)});if(ee)ae+=` AND ${ee}`}return ae},Oc=(d,f,T)=>{G(d,"withCount (parent table)"),G(f,"withCount (target table)"),G(T,"withCount (primary key)");let S=`${d.endsWith("s")?d.slice(0,-1):d}_id`;return G(S,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${f} WHERE ${f}.${S} = ${d}.${T})`},Bc=(d,f,T,S)=>{G(d,"withCount (parent table)"),G(f,"withCount (target table)"),G(T,"withCount (primary key)");let A=S&&n?en(n,d,S,{singularize:Se,models:n.models}):null,O=Se(d),K=Se(f),F=A?.pivotTable??[O,K].sort().join("_"),z=A?.fkParent??`${O}_id`;return G(F,"withCount (pivot table)"),G(z,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${F} WHERE ${F}.${z} = ${d}.${T})`},lr=(d,f,T)=>{if(!n)return;G(T,`with${d[0]}${d.slice(1).toLowerCase()} (column)`);let S=String(y),A=n.relations?.[S];if(!A)return;let O=Object.entries(A).find(([ee,Ne])=>Ne&&typeof Ne==="object"&&(f in Ne));if(!O)return;let[K,F]=O,z=F[f],L=typeof z==="string"?z:z?.model||z?.target||z,j=n.modelToTable[L]||L,X=n.primaryKeys[S]??"id";G(j,`with${d} (target table)`);let ae=`${d}(${j}.${T})`,Ae;if(K==="hasMany"||K==="hasOne"){let ee=`${S.endsWith("s")?S.slice(0,-1):S}_id`;G(ee,`with${d} (foreign key)`),Ae=`(SELECT ${ae} FROM ${j} WHERE ${j}.${ee} = ${S}.${X})`}else if(K==="belongsToMany"){let ee=n?en(n,S,f,{singularize:Se,models:n.models}):null,Ne=Se(S),Ue=Se(j),Je=ee?.pivotTable??[Ne,Ue].sort().join("_"),We=ee?.fkParent??`${Ne}_id`,le=ee?.fkRelated??`${Ue}_id`,Pn=n.primaryKeys[j]??"id";G(Je,`with${d} (pivot table)`),G(We,`with${d} (foreign key)`),G(le,`with${d} (related key)`),Ae=`(SELECT ${ae} FROM ${Je} JOIN ${j} ON ${j}.${Pn} = ${Je}.${le} WHERE ${Je}.${We} = ${S}.${X})`}else return;Bn(`${Ae} AS ${f}_${d.toLowerCase()}_${T}`)},Qi=()=>{if(at.size===0)return;let d=[];for(let[f,T]of at.entries()){let S=yt(f);if(!S)continue;for(let O of T)G(O,"withPivot");let A=T.map((O)=>`${S.pivotTable}.${O} AS pivot_${O}`);d.push(...A)}if(d.length>0){let f=d.join(", ");Bn(f)}};return new Proxy({distinct(){return p=p.replace(/^SELECT\s+/i,"SELECT DISTINCT "),v=null,this},distinctOn(...d){let f=d.map(String).join(", ");return p=p.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${f}) `),v=null,this},selectRaw(d){let f=nn(d,"selectRaw(fragment)"),T=p.indexOf(" FROM ");if(T!==-1)p=`${p.substring(0,T)}, ${f}${p.substring(T)}`;else p+=`, ${f}`;return v=null,this},rowNumber(d="row_number",f,T){let S=[];if(f){let F=Array.isArray(f)?f:[f];S.push(`PARTITION BY ${F.join(", ")}`)}if(T&&T.length)S.push(`ORDER BY ${T.map(([F,z])=>`${F} ${z==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${d}`,K=p.indexOf(" FROM ");if(K!==-1)p=`${p.substring(0,K)}, ${O}${p.substring(K)}`;else p+=`, ${O}`;return v=null,this},denseRank(d="dense_rank",f,T){let S=Array.isArray(f)?f:f?[f]:[],A=[];if(S.length)A.push(`PARTITION BY ${S.join(", ")}`);if(T&&T.length)A.push(`ORDER BY ${T.map(([z,L])=>`${z} ${L==="desc"?"DESC":"ASC"}`).join(", ")}`);let K=`DENSE_RANK() ${A.length?`OVER (${A.join(" ")})`:"OVER ()"} AS ${d}`,F=p.indexOf(" FROM ");if(F!==-1)p=`${p.substring(0,F)}, ${K}${p.substring(F)}`;else p+=`, ${K}`;return v=null,this},rank(d="rank",f,T){let S=Array.isArray(f)?f:f?[f]:[],A=[];if(S.length)A.push(`PARTITION BY ${S.join(", ")}`);if(T&&T.length)A.push(`ORDER BY ${T.map(([z,L])=>`${z} ${L==="desc"?"DESC":"ASC"}`).join(", ")}`);let K=`RANK() ${A.length?`OVER (${A.join(" ")})`:"OVER ()"} AS ${d}`,F=p.indexOf(" FROM ");if(F!==-1)p=`${p.substring(0,F)}, ${K}${p.substring(F)}`;else p+=`, ${K}`;return v=null,this},over(d,f,T={}){return ht(d,f,T.partitionBy,T.orderBy),this},lag(d,f={}){let T=[d,String(f.offset??1)];if(f.defaultValue!==void 0)T.push(String(f.defaultValue));return ht(`LAG(${T.join(", ")})`,f.alias??`${d}_lag`,f.partitionBy,f.orderBy),this},lead(d,f={}){let T=[d,String(f.offset??1)];if(f.defaultValue!==void 0)T.push(String(f.defaultValue));return ht(`LEAD(${T.join(", ")})`,f.alias??`${d}_lead`,f.partitionBy,f.orderBy),this},sumOver(d,f={}){return ht(`SUM(${d})`,f.alias??`${d}_sum`,f.partitionBy,f.orderBy),this},avgOver(d,f={}){return ht(`AVG(${d})`,f.alias??`${d}_avg`,f.partitionBy,f.orderBy),this},countOver(d="*",f={}){return ht(`COUNT(${d})`,f.alias??"count_over",f.partitionBy,f.orderBy),this},minOver(d,f={}){return ht(`MIN(${d})`,f.alias??`${d}_min`,f.partitionBy,f.orderBy),this},maxOver(d,f={}){return ht(`MAX(${d})`,f.alias??`${d}_max`,f.partitionBy,f.orderBy),this},firstValue(d,f={}){return ht(`FIRST_VALUE(${d})`,f.alias??`${d}_first`,f.partitionBy,f.orderBy),this},lastValue(d,f={}){return ht(`LAST_VALUE(${d})`,f.alias??`${d}_last`,f.partitionBy,f.orderBy),this},selectAll(){return this},select(d){if(!d)return this;let f=Array.isArray(d)?d:[d];if(f.length===0)return this;let T=f.map(La),S=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(p),A=S?S[1]:"",O=p.indexOf(" FROM ");if(O!==-1)p=`SELECT ${A}${T.join(", ")}${p.substring(O)}`;else p=`SELECT ${A}${T.join(", ")} FROM ${y}`;return v=null,this},addSelect(...d){if(!d.length)return this;let f=d.map(La),T=p.indexOf(" FROM ");if(T!==-1)p=`${p.substring(0,T)}, ${f.join(", ")}${p.substring(T)}`;else p+=`, ${f.join(", ")}`;return v=null,this},with(...d){if(!n||!d||d.length===0)return this;let f=[];for(let L of d){if(!L)continue;if(typeof L==="string")f.push({name:L});else if(typeof L==="object"&&!Array.isArray(L))for(let[j,X]of Object.entries(L))if(typeof X==="function")f.push({name:j,callback:X});else f.push({name:j})}if(f.length===0)return this;let T=_.relations.maxEagerLoad??50;if(f.length>T)throw Error(`[query-builder] Too many relationships to eager load (${f.length}). Maximum allowed: ${T}`);let S=String(y),A=new Set,O=new Set,K=new Map,F=(L)=>{let j=n.relations?.[L];if(!j)return[];return[...Object.keys(j.hasOne||{}),...Object.keys(j.hasMany||{}),...Object.keys(j.belongsTo||{}),...Object.keys(j.belongsToMany||{}),...Object.keys(j.hasOneThrough||{}),...Object.keys(j.hasManyThrough||{}),...Object.keys(j.morphOne||{}),...Object.keys(j.morphMany||{}),...Object.keys(j.morphToMany||{}),...Object.keys(j.morphedByMany||{})]},z=(L,j,X=0,ae)=>{let Ae=_.relations.maxDepth??10;if(X>=Ae)throw Error(`[query-builder] Maximum relationship depth (${Ae}) exceeded at '${j}'. Consider using separate queries or increasing maxDepth.`);let ee=n.relations?.[L];if(!ee)return L;let Ne=(ce)=>{if(_.softDeletes?.enabled&&_.softDeletes?.defaultFilter){let ue=_.softDeletes.column||"deleted_at";return` AND ${ce}.${ue} IS NULL`}return""},Ue=(ce)=>{if(!ae)return"";let ue=[],xe=(me,He,pt)=>{G(String(me),"with() constraint column");let cn=Oe(He,"with() constraint operator");ue.push(`${ce}.${String(me)} ${cn} ${At(pt)}`)},we=(me)=>()=>{throw Error(`[query-builder] with('${j}', ...): ${me} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},ke={where:(me,He,pt)=>{if(Array.isArray(me))xe(me[0],me[1],me[2]);else if(me&&typeof me==="object")for(let cn of Object.keys(me))xe(cn,"=",me[cn]);else if(He!==void 0&&pt!==void 0)xe(me,He,pt);else if(He!==void 0)xe(me,"=",He);return ke},whereIn:(me,He)=>(G(String(me),"with() constraint column"),ue.push(`${ce}.${String(me)} IN (${He.map(At).join(", ")})`),ke),whereNull:(me)=>(G(String(me),"with() constraint column"),ue.push(`${ce}.${String(me)} IS NULL`),ke),whereNotNull:(me)=>(G(String(me),"with() constraint column"),ue.push(`${ce}.${String(me)} IS NOT NULL`),ke),orderBy:we("orderBy()"),limit:we("limit()"),offset:we("offset()"),take:we("take()")};return ae(ke),ue.length?` AND ${ue.join(" AND ")}`:""},Je=()=>{let ce=(we)=>{let ke=we?.[j];return ke?n.modelToTable[ke]:void 0},ue=(we)=>{let ke=we?.[j],me=typeof ke==="string"?ke:ke?.model;return me?n.modelToTable[me]:void 0},xe=(we)=>{let ke=we?.[j];return ke?.target?n.modelToTable[ke.target]:void 0};return ce(ee?.hasOne)||ce(ee?.hasMany)||ce(ee?.belongsTo)||ue(ee?.belongsToMany)||xe(ee?.hasOneThrough)||xe(ee?.hasManyThrough)||ce(ee?.morphOne)||ce(ee?.morphMany)||ce(ee?.morphToMany)||ce(ee?.morphedByMany)},We=Je()??(n.modelToTable[j]||n.tableToModel[j]?n.modelToTable[j]??j:j),le=String(We);if(!We||!Je()&&!n.modelToTable[j]&&!n.tableToModel[j]){let ce=F(L);if(ce.length>0&&!ce.includes(j)){let ue=` Available relationships: ${ce.join(", ")}`;throw Error(`[query-builder] Relationship '${j}' not found on table '${L}'.${ue}`)}}if(_.relations.detectCycles!==!1){let ce=`${L}->${le}`;if(A.has(ce))throw Error(`[query-builder] Circular relationship detected: ${ce}. This would cause an infinite loop.`);A.add(ce)}if(!le||le===L)return L;let Pn=ee?.hasOneThrough?.[j]||ee?.hasManyThrough?.[j];if(Pn){let{through:ce,target:ue}=Pn,xe=n.modelToTable[ce]||ce,we=n.modelToTable[ue]||ue,ke=n.primaryKeys[L]??"id",me=n.primaryKeys[xe]??"id",He=`${Se(L)}_id`,pt=`${Se(xe)}_id`;return U(`LEFT JOIN ${xe} ON ${xe}.${He} = ${L}.${ke} LEFT JOIN ${we} ON ${we}.${pt} = ${xe}.${me}`),Y.add(xe),Y.add(we),we}if(Boolean(ee?.belongsToMany?.[j])){let ce=en(n,L,j,{singularize:Se,models:n.models}),ue=ce?.pivotTable??[Se(L),Se(le)].sort().join("_"),xe=n.primaryKeys[L]??"id",we=n.primaryKeys[le]??"id",ke=ce?.fkParent??`${Se(L)}_id`,me=ce?.fkRelated??`${Se(le)}_id`;return U(`LEFT JOIN ${ue} ON ${ue}.${ke} = ${L}.${xe} LEFT JOIN ${le} ON ${le}.${we} = ${ue}.${me}${Ue(le)}`),Y.add(ue),Y.add(le),le}if(Boolean(ee?.morphToMany?.[j])){let ce=j,ue=`${Se(le)}_${ce}`,xe=n.primaryKeys[L]??"id",we=n.primaryKeys[le]??"id",ke=`${ce}_type`,me=`${ce}_id`,He=`${Se(le)}_id`,pt=At(n.tableToModel[L]||L);return U(`LEFT JOIN ${ue} ON ${ue}.${me} = ${L}.${xe} AND ${ue}.${ke} = ${pt} LEFT JOIN ${le} ON ${le}.${we} = ${ue}.${He}`),Y.add(ue),Y.add(le),le}if(Boolean(ee?.morphedByMany?.[j])){let ce=ee.morphedByMany?.[j]||j,ue=n.modelToTable[ce]||ce,xe=Se(L),we=`${Se(ue)}_${xe}`,ke=n.primaryKeys[L]??"id",me=n.primaryKeys[ue]??"id",He=`${xe}_type`,pt=`${xe}_id`,cn=`${Se(ue)}_id`,Fc=At(n.tableToModel[ue]||ue);return U(`LEFT JOIN ${we} ON ${we}.${cn} = ${L}.${ke} LEFT JOIN ${ue} ON ${ue}.${me} = ${we}.${pt} AND ${we}.${He} = ${Fc}`),Y.add(we),Y.add(ue),ue}if(Boolean(ee?.belongsTo?.[j])){let ce=`${Se(le)}_id`,ue=n.primaryKeys[le]??"id";return U(`LEFT JOIN ${le} ON ${L}.${ce} = ${le}.${ue}${Ue(le)}`),Y.add(le),le}let Pc=Boolean(ee?.morphOne?.[j]),_c=Boolean(ee?.morphMany?.[j]);if(Pc||_c){let ce=`${j}_type`,ue=`${j}_id`,xe=n.primaryKeys[L]??"id",we=At(n.tableToModel[L]||L);return U(`LEFT JOIN ${le} ON ${le}.${ue} = ${L}.${xe} AND ${le}.${ce} = ${we}`),Y.add(le),le}let Ic=`${Se(L)}_id`,Lc=n.primaryKeys[L]??"id",Kc=`${Ne(le)}${Ue(le)}`;return U(`LEFT JOIN ${le} ON ${le}.${Ic} = ${L}.${Lc}${Kc}`),Y.add(le),le};for(let L of f){let j=L.name.trim();if(L.callback)K.set(j,L.callback);let X=j.split("."),ae=S,Ae=0;for(let ee of X){if(!ee||ee.trim().length===0)continue;let Ne=ee.trim(),Ue=K.get(Ne);ae=z(ae,Ne,Ae,Ue)||ae,Ae++}O.add(j)}if(at.size>0){let L=[];for(let[j,X]of at.entries()){let ae=yt(j);if(!ae)continue;let Ae=X.map((ee)=>`${ae.pivotTable}.${ee} AS pivot_${ee}`);L.push(...Ae)}if(L.length>0){let j=L.join(", ");Bn(j)}}return v=null,this},whereHas(d,f){if(!n)return this;let T=String(y),S=n.relations?.[T];if(!S)throw Error(`[query-builder] No relationships defined for table '${T}'`);let A=Object.entries(S).find(([X,ae])=>ae&&typeof ae==="object"&&(d in ae));if(!A)throw Error(`[query-builder] Relationship '${d}' not found on table '${T}'`);let[O,K]=A,F=K[d],z=typeof F==="string"?F:F?.model||F?.target||F,L=n.modelToTable[z]||z,j;if(O==="hasMany"||O==="hasOne"){let X=n.primaryKeys[T]??"id";j=ir(T,L,X,f)}else if(O==="belongsTo"){let X=n.primaryKeys[L]??"id";j=or(T,L,X,f)}else if(O==="belongsToMany"){let X=n.primaryKeys[T]??"id",ae=n.primaryKeys[L]??"id";j=ar(T,L,X,ae,f,d)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return k("WHERE",`EXISTS (${j})`),this},whereDoesntHave(d,f){if(!n)return this;let T=String(y),S=n.relations?.[T];if(!S)throw Error(`[query-builder] No relationships defined for table '${T}'`);let A=Object.entries(S).find(([X,ae])=>ae&&typeof ae==="object"&&(d in ae));if(!A)throw Error(`[query-builder] Relationship '${d}' not found on table '${T}'`);let[O,K]=A,F=K[d],z=typeof F==="string"?F:F?.model||F?.target||F,L=n.modelToTable[z]||z,j;if(O==="hasMany"||O==="hasOne"){let X=n.primaryKeys[T]??"id";j=ir(T,L,X,f)}else if(O==="belongsTo"){let X=n.primaryKeys[L]??"id";j=or(T,L,X,f)}else if(O==="belongsToMany"){let X=n.primaryKeys[T]??"id",ae=n.primaryKeys[L]??"id";j=ar(T,L,X,ae,f,d)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return k("WHERE",`NOT EXISTS (${j})`),this},has(d){if(!n)return this;let f=String(y),T=n.relations?.[f];if(!T)throw Error(`[query-builder] No relationships defined for table '${f}'`);let S=Object.entries(T).find(([j,X])=>X&&typeof X==="object"&&(d in X));if(!S)throw Error(`[query-builder] Relationship '${d}' not found on table '${f}'`);let[A,O]=S,K=O[d],F=typeof K==="string"?K:K?.model||K?.target||K,z=n.modelToTable[F]||F,L;if(A==="hasMany"||A==="hasOne"){let j=n.primaryKeys[f]??"id";L=ir(f,z,j)}else if(A==="belongsTo"){let j=n.primaryKeys[z]??"id";L=or(f,z,j)}else if(A==="belongsToMany"){let j=n.primaryKeys[f]??"id",X=n.primaryKeys[z]??"id";L=ar(f,z,j,X,void 0,d)}else throw Error(`[query-builder] Unsupported relationship type '${A}' for has`);return k("WHERE",`EXISTS (${L})`),this},doesntHave(d){if(!n)return this;let f=String(y),T=n.relations?.[f];if(!T)throw Error(`[query-builder] No relationships defined for table '${f}'`);let S=Object.entries(T).find(([j,X])=>X&&typeof X==="object"&&(d in X));if(!S)throw Error(`[query-builder] Relationship '${d}' not found on table '${f}'`);let[A,O]=S,K=O[d],F=typeof K==="string"?K:K?.model||K?.target||K,z=n.modelToTable[F]||F,L;if(A==="hasMany"||A==="hasOne"){let j=n.primaryKeys[f]??"id";L=ir(f,z,j)}else if(A==="belongsTo"){let j=n.primaryKeys[z]??"id";L=or(f,z,j)}else if(A==="belongsToMany"){let j=n.primaryKeys[f]??"id",X=n.primaryKeys[z]??"id";L=ar(f,z,j,X,void 0,d)}else throw Error(`[query-builder] Unsupported relationship type '${A}' for doesntHave`);return k("WHERE",`NOT EXISTS (${L})`),this},withCount(...d){if(!n||!d||d.length===0)return this;let f=String(y);for(let T of d){let S=n.relations?.[f];if(!S)continue;let A=Object.entries(S).find(([Ae,ee])=>ee&&typeof ee==="object"&&(T in ee));if(!A)continue;let[O,K]=A,F=K[T],z=typeof F==="string"?F:F?.model||F?.target||F,L=n.modelToTable[z]||z,j=n.primaryKeys[f]??"id",X;if(O==="hasMany"||O==="hasOne")X=Oc(f,L,j);else if(O==="belongsToMany")X=Bc(f,L,j,T);else continue;let ae=`${T}_count`;Bn(`${X} AS ${ae}`)}return this},withSum(d,f){return lr("SUM",d,f),this},withAvg(d,f){return lr("AVG",d,f),this},withMax(d,f){return lr("MAX",d,f),this},withMin(d,f){return lr("MIN",d,f),this},applyPivotColumns(){return Qi(),this},withPivot(d,...f){if(!n)return this;let T=String(y),S=yt(d);if(!S)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${T}'`);let A=f&&f.length>0?f:S.hasConfig?S.pivotColumns:[];if(A.length===0)return this;if(at.set(d,A),S.hasConfig)nt.add(d);return Qi(),this},wherePivot(d,f,T,S){if(!n)return this;let A=yt(d);if(!A)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);G(A.pivotTable,"wherePivot (pivot table)"),G(f,"wherePivot (column)"),On(A);let O=S===void 0?"=":String(T),K=S===void 0?T:S,F=D.length+1,z=`${A.pivotTable}.${f} ${O} ${Z(F)}`;if(D.push(K),C("AND",z),A.hasConfig)nt.add(d);return this},wherePivotIn(d,f,T){if(!n||!Array.isArray(T))return this;let S=yt(d);if(!S)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);G(S.pivotTable,"wherePivotIn (pivot table)"),G(f,"wherePivotIn (column)"),On(S);let A=ve(T.length,D.length+1),O=Ge(`${S.pivotTable}.${f}`,T,!1,A);if(D.push(...T),C("AND",O),S.hasConfig)nt.add(d);return this},wherePivotNotIn(d,f,T){if(!n||!Array.isArray(T)||T.length===0)return this;let S=yt(d);if(!S)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);G(S.pivotTable,"wherePivotNotIn (pivot table)"),G(f,"wherePivotNotIn (column)"),On(S);let A=ve(T.length,D.length+1),O=`${S.pivotTable}.${f} NOT IN (${A})`;if(D.push(...T),C("AND",O),S.hasConfig)nt.add(d);return this},wherePivotNull(d,f){if(!n)return this;let T=yt(d);if(!T)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);if(G(T.pivotTable,"wherePivotNull (pivot table)"),G(f,"wherePivotNull (column)"),On(T),C("AND",`${T.pivotTable}.${f} IS NULL`),T.hasConfig)nt.add(d);return this},wherePivotNotNull(d,f){if(!n)return this;let T=yt(d);if(!T)throw Error(`[query-builder] Relationship '${d}' is not a belongsToMany relationship on table '${String(y)}'`);if(G(T.pivotTable,"wherePivotNotNull (pivot table)"),G(f,"wherePivotNotNull (column)"),On(T),C("AND",`${T.pivotTable}.${f} IS NOT NULL`),T.hasConfig)nt.add(d);return this},where(d,f,T){if(typeof d==="string"&&f!==void 0){G(String(d),"where(column)"),Oe(f,"where(operator)");let S=String(f).toLowerCase();if(S==="in"||S==="not in"){let O=Array.isArray(T)?T:[T],K=ve(O.length,D.length+1),F=Ge(ot(String(d)),O,S==="not in",K);return D.push(...O),C("AND",F),this}let A=D.length+1;return D.push(T),C("AND",`${ot(String(d))} ${String(f)} ${Z(A)}`),this}if(Array.isArray(d)){let[S,A,O]=d,K=String(S);G(K,"where(column)");let F=Oe(A,"where(operator)");if(F==="in"||F==="not in"){let z=Array.isArray(O)?O:[O],L=ve(z.length,D.length+1),j=Ge(ot(K),z,F==="not in",L);D.push(...z),C("AND",j)}else{let z=D.length+1;D.push(O),C("AND",`${ot(K)} ${F} ${Z(z)}`)}return this}if(d&&typeof d==="object"&&!wt(d)){let S=d,A=Object.keys(S),O=[];for(let K of A){G(K,"where(column)");let F=S[K];if(Array.isArray(F)){let z=ve(F.length,D.length+1);O.push(Ge(ot(K),F,!1,z)),D.push(...F)}else{let z=D.length+1;O.push(`${ot(K)} = ${Z(z)}`),D.push(F)}}if(O.length>0)C("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(wt(d))return C("AND",d.raw),this;if(typeof d==="function")return H("AND",d),this;if(d===void 0||d===null)throw TypeError("where() was called with no condition.");if(typeof d==="string")throw TypeError(`where(${JSON.stringify(d)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof d}.`)},whereNull(d){return G(String(d),"whereNull(column)"),C("AND",`${String(d)} IS NULL`),this},whereNotNull(d){return G(String(d),"whereNotNull(column)"),C("AND",`${String(d)} IS NOT NULL`),this},orWhereNull(d){return G(String(d),"orWhereNull(column)"),C("OR",`${String(d)} IS NULL`),this},orWhereNotNull(d){return G(String(d),"orWhereNotNull(column)"),C("OR",`${String(d)} IS NOT NULL`),this},whereBetween(d,f,T){G(String(d),"whereBetween(column)");let S=D.length+1;return D.push(f,T),C("AND",`${String(d)} BETWEEN ${Z(S)} AND ${Z(S+1)}`),this},orWhereBetween(d,f,T){G(String(d),"orWhereBetween(column)");let S=D.length+1;return D.push(f,T),C("OR",`${String(d)} BETWEEN ${Z(S)} AND ${Z(S+1)}`),this},whereExists(d){return C("AND",`EXISTS (${d.toSQL()})`),this},orWhereExists(d){return C("OR",`EXISTS (${d.toSQL()})`),this},whereGroup(d){return H("AND",d),this},orWhereGroup(d){return H("OR",d),this},__whereState(){return{body:tn(E),params:[...D]}},whereJsonContains(d,f){G(String(d),"whereJsonContains(column)");let T=_.dialect,S=D.length+1;if(T==="postgres"){let O=typeof f==="number"||typeof f==="boolean"?`to_jsonb(${Z(S)})`:Z(S);if(_.sql?.jsonContainsMode==="function")C("AND",`jsonb_contains(${d}, ${O})`);else C("AND",`${d} @> ${O}`);D.push(f)}else if(ne(T))C("AND",`JSON_CONTAINS(${d}, ${Z(S)})`),D.push(JSON.stringify(f));else if(Array.isArray(f)){let A=f.map((O,K)=>`EXISTS (SELECT 1 FROM json_each(${d}) WHERE json_each.value = ${Z(S+K)})`);C("AND",`(${A.join(" AND ")})`);for(let O of f)D.push(O)}else if(f!==null&&typeof f==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else C("AND",`EXISTS (SELECT 1 FROM json_each(${d}) WHERE json_each.value = ${Z(S)})`),D.push(f);return this},whereJsonPath(d,f,T){if(Oe(f,"whereJsonPath(op)"),typeof d!=="string"||d.length===0||d.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof d==="string"?`'${d.slice(0,32)}...'`:typeof d}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(d))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${d}' \u2014 contains characters outside the allowed JSON-path set`);let S=_.dialect,A=D.length+1;if(S==="postgres")C("AND",`${d} ${f} ${Z(A)}`);else if(ne(S))C("AND",`JSON_EXTRACT(${d}) ${f} ${Z(A)}`);else C("AND",`json_extract(${d}) ${f} ${Z(A)}`);return D.push(T),this},whereLike(d,f,T=!1){let S=Z(D.length+1);return k("WHERE",`${T?String(d):`LOWER(${String(d)})`} LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},whereILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("WHERE",`${String(d)} ILIKE ${T}`);else k("WHERE",`LOWER(${String(d)}) LIKE LOWER(${T})`);return D.push(f),v=null,this},orWhereLike(d,f,T=!1){let S=Z(D.length+1);return k("OR",`${T?String(d):`LOWER(${String(d)})`} LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},orWhereILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("OR",`${String(d)} ILIKE ${T}`);else k("OR",`LOWER(${String(d)}) LIKE LOWER(${T})`);return D.push(f),v=null,this},whereNotLike(d,f,T=!1){let S=Z(D.length+1);return k("WHERE",`${T?String(d):`LOWER(${String(d)})`} NOT LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},whereNotILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("WHERE",`${String(d)} NOT ILIKE ${T}`);else k("WHERE",`LOWER(${String(d)}) NOT LIKE LOWER(${T})`);return D.push(f),v=null,this},orWhereNotLike(d,f,T=!1){let S=Z(D.length+1);return k("OR",`${T?String(d):`LOWER(${String(d)})`} NOT LIKE ${T?S:`LOWER(${S})`}`),D.push(f),v=null,this},orWhereNotILike(d,f){let T=Z(D.length+1);if(_.dialect==="postgres")k("OR",`${String(d)} NOT ILIKE ${T}`);else k("OR",`LOWER(${String(d)}) NOT LIKE LOWER(${T})`);return D.push(f),v=null,this},whereAny(d,f,T){if(d.length===0)return C("AND",`(${Ia})`),this;let S=D.length+1,A=d.map((O,K)=>`${O} ${f} ${Z(S+K)}`);for(let O=0;O<d.length;O++)D.push(T);return C("AND",`(${A.join(" OR ")})`),this},whereAll(d,f,T){if(d.length===0)return this;let S=D.length+1,A=d.map((O,K)=>`${O} ${f} ${Z(S+K)}`);for(let O=0;O<d.length;O++)D.push(T);return C("AND",`(${A.join(" AND ")})`),this},whereNone(d,f,T){if(d.length===0)return this;let S=D.length+1,A=d.map((O,K)=>`${O} ${f} ${Z(S+K)}`);for(let O=0;O<d.length;O++)D.push(T);return C("AND",`NOT (${A.join(" OR ")})`),this},whereNotBetween(d,f,T){G(String(d),"whereNotBetween(column)");let S=D.length+1;return D.push(f,T),C("AND",`${d} NOT BETWEEN ${Z(S)} AND ${Z(S+1)}`),this},whereDate(d,f,T){G(d,"whereDate(column)");let S=T instanceof Date?T.toISOString():typeof T==="string"?T:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof T}`)})(),A=D.length+1;return D.push(S),C("AND",`${d} ${f} ${Z(A)}`),this},whereRaw(d){return C("AND",nn(d,"whereRaw(fragment)")),this},orWhereRaw(d){return C("OR",nn(d,"orWhereRaw(fragment)")),this},whereColumn(d,f,T){return G(d,"whereColumn(left)"),G(T,"whereColumn(right)"),C("AND",`${d} ${f} ${T}`),this},orWhereColumn(d,f,T){return G(d,"orWhereColumn(left)"),G(T,"orWhereColumn(right)"),C("OR",`${d} ${f} ${T}`),this},whereIn(d,f){if(G(String(d),"whereIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!1,T);D.push(...f),C("AND",S)}else C("AND",`${d} IN (${String(f.toSQL())})`);return this},orWhereIn(d,f){if(G(String(d),"orWhereIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!1,T);D.push(...f),C("OR",S)}else C("OR",`${d} IN (${String(f.toSQL())})`);return this},whereNotIn(d,f){if(G(String(d),"whereNotIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!0,T);D.push(...f),C("AND",S)}else C("AND",`${d} NOT IN (${String(f.toSQL())})`);return this},orWhereNotIn(d,f){if(G(String(d),"orWhereNotIn(column)"),Array.isArray(f)){let T=ve(f.length,D.length+1),S=Ge(d,f,!0,T);D.push(...f),C("OR",S)}else C("OR",`${d} NOT IN (${String(f.toSQL())})`);return this},whereNested(d){let f=d.toSQL?String(d.toSQL()):String(d);return C("AND",`(${f})`),this},orWhereNested(d){let f=d.toSQL?String(d.toSQL()):String(d);return C("OR",`(${f})`),this},andWhere(d,f,T){return M(this,"AND","andWhere",d,f,T)},orWhere(d,f,T){return M(this,"OR","orWhere",d,f,T)},orderBy(d,f="asc"){let T=f==="asc"?"ASC":"DESC",S=ot(String(d));return p=he.ORDER_BY.test(p)?`${p}, ${S} ${T}`:`${p} ORDER BY ${S} ${T}`,v=null,this},orderByDesc(d){return p=he.ORDER_BY.test(p)?`${p}, ${d} DESC`:`${p} ORDER BY ${d} DESC`,v=null,this},inRandomOrder(){let d=_.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return p=he.ORDER_BY.test(p)?`${p}, ${d}`:`${p} ORDER BY ${d}`,v=null,this},reorder(d,f="asc"){return p=p.replace(/ORDER BY[\s\S]*$/i,""),p+=` ORDER BY ${d} ${f==="asc"?"ASC":"DESC"}`,v=null,this},latest(d){let f=d??_.timestamps.defaultOrderColumn;return p=he.ORDER_BY.test(p)?`${p}, ${f} DESC`:`${p} ORDER BY ${f} DESC`,v=null,this},oldest(d){let f=d??_.timestamps.defaultOrderColumn;return p=he.ORDER_BY.test(p)?`${p}, ${f} ASC`:`${p} ORDER BY ${f} ASC`,v=null,this},limit(d){if(!Number.isFinite(d)||d<0||!Number.isInteger(d))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${d}`);return p=he.LIMIT.test(p)?p.replace(he.LIMIT,` LIMIT ${d}`):`${p} LIMIT ${d}`,v=null,this},offset(d){if(!Number.isFinite(d)||d<0||!Number.isInteger(d))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${d}`);return p=he.OFFSET.test(p)?p.replace(he.OFFSET,` OFFSET ${d}`):`${p} OFFSET ${d}`,v=null,this},join(d,f,T,S){return G(d,"join(table)"),it(f,"join(onLeft)"),it(S,"join(onRight)"),Oe(T,"join(operator)"),U(`JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},joinSub(d,f,T,S,A){return G(f,"joinSub(alias)"),it(T,"joinSub(onLeft)"),it(A,"joinSub(onRight)"),Oe(S,"joinSub(operator)"),U(`JOIN (${String(d.toSQL())}) AS ${f} ON ${T} ${S} ${A}`),Y.add(f),this},innerJoin(d,f,T,S){return G(d,"innerJoin(table)"),it(f,"innerJoin(onLeft)"),it(S,"innerJoin(onRight)"),Oe(T,"innerJoin(operator)"),U(`INNER JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},leftJoin(d,f,T,S){return G(d,"leftJoin(table)"),it(f,"leftJoin(onLeft)"),it(S,"leftJoin(onRight)"),Oe(T,"leftJoin(operator)"),U(`LEFT JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},leftJoinSub(d,f,T,S,A){return G(f,"leftJoinSub(alias)"),it(T,"leftJoinSub(onLeft)"),it(A,"leftJoinSub(onRight)"),Oe(S,"leftJoinSub(operator)"),U(`LEFT JOIN (${String(d.toSQL())}) AS ${f} ON ${T} ${S} ${A}`),Y.add(f),this},rightJoin(d,f,T,S){return G(d,"rightJoin(table)"),it(f,"rightJoin(onLeft)"),it(S,"rightJoin(onRight)"),Oe(T,"rightJoin(operator)"),U(`RIGHT JOIN ${d} ON ${f} ${T} ${S}`),Y.add(d),this},crossJoin(d){return G(d,"crossJoin(table)"),U(`CROSS JOIN ${d}`),Y.add(d),this},crossJoinSub(d,f){return G(f,"crossJoinSub(alias)"),U(`CROSS JOIN (${String(d.toSQL())}) AS ${f}`),Y.add(f),this},selectAllRelations(){if(!r)return this;let d=String(y),f=Object.keys(r[d]?.columns??{}),T=[];if(f.length>0)T.push(g`${g(d)}.*`);for(let S of Y){let A=Object.keys(r[S]?.columns??{});for(let O of A){let K=_.aliasing.relationColumnAliasFormat==="camelCase"?`${S}_${O}`.replace(/_([a-z])/g,(F,z)=>z.toUpperCase()):_.aliasing.relationColumnAliasFormat==="table.dot.column"?`${S}.${O}`:`${S}_${O}`;T.push(g`${g(`${S}.${O}`)} AS ${g(K)}`)}}if(T.length>0){let S=f.length>0?`${d}.*`:"",A=[];for(let F of Y){let z=Object.keys(r[F]?.columns??{});for(let L of z){let j=_.aliasing.relationColumnAliasFormat==="camelCase"?`${F}_${L}`.replace(/_([a-z])/g,(X,ae)=>ae.toUpperCase()):_.aliasing.relationColumnAliasFormat==="table.dot.column"?`${F}.${L}`:`${F}_${L}`;A.push(`${F}.${L} AS ${j}`)}}let O=[S,...A].filter(Boolean).join(", "),K=p.indexOf(" FROM ");if(K!==-1)p=`SELECT ${O}${p.substring(K)}`;else p=`SELECT ${O} FROM ${d}`;v=null}return this},groupBy(...d){if(d.length)p=he.GROUP_BY.test(p)?`${p}, ${d.map((f)=>ot(String(f))).join(", ")}`:`${p} GROUP BY ${d.map((f)=>ot(String(f))).join(", ")}`,v=null;return this},groupByRaw(d){let f=nn(d,"groupByRaw(fragment)");return p=he.GROUP_BY.test(p)?`${p}, ${f}`:`${p} GROUP BY ${f}`,v=null,this},having(d){let f=W?"AND":"HAVING";if(Array.isArray(d)){let T=D.length+1;p=`${p} ${f} ${d[0]} ${d[1]} ${Z(T)}`,D.push(d[2]),W=!0,v=null}else if(d&&typeof d==="object"&&!("raw"in d)){let T=Object.keys(d),S=T.length;if(S){let A=D.length,O=Array.from({length:S});for(let K=0;K<S;K++){let F=T[K];O[K]=`${F} = ${Z(A+K+1)}`,D.push(d[F])}p=`${p} ${f} ${O.join(" AND ")}`,W=!0,v=null}}else if(d&&typeof d.raw<"u")p+=` ${f} ${d.raw}`,W=!0,v=null;return this},havingRaw(d){let f=nn(d,"havingRaw(fragment)");return p+=` ${W?"AND":"HAVING"} ${f}`,W=!0,v=null,this},orderByRaw(d){let f=nn(d,"orderByRaw(fragment)");return p=he.ORDER_BY.test(p)?`${p}, ${f}`:`${p} ORDER BY ${f}`,v=null,this},$call(d){return d(this),this},union(d){return V("UNION",d),this},unionAll(d){return V("UNION ALL",d),this},intersect(d){return V("INTERSECT",d),this},intersectAll(d){return V("INTERSECT ALL",d),this},except(d){return V("EXCEPT",d),this},exceptAll(d){return V("EXCEPT ALL",d),this},forPage(d,f){let T=Math.max(1,Math.floor(d)),S=Math.max(1,Math.floor(f));return p+=` LIMIT ${S} OFFSET ${(T-1)*S}`,v=null,this},toSQL(){let d=Gn(q());return{sql:d,toString:()=>d,execute:()=>x().execute(),values:()=>x().values(),raw:()=>x().raw()}},async value(d){let f=g`${x()} LIMIT 1`,T=await h(f,"select",{signal:Q,timeoutMs:I}),[S]=T;return S?.[d]},async pluck(d,f){let T=await h(x(),"select",{signal:Q,timeoutMs:I});if(f){let S={};for(let A of T){let O=String(A?.[f]);if(Object.prototype.hasOwnProperty.call(S,O))throw Error(`[query-builder] pluck(${d}, ${f}): duplicate key '${O}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);S[O]=A?.[d]}return S}return T.map((S)=>S?.[d])},async exists(){let d=g`SELECT EXISTS (${x()}) as e`,f=await h(d,"select",{signal:Q,timeoutMs:I}),[T]=f;return Boolean(T?.e)},async doesntExist(){return!await this.exists()},async paginate(d,f=1,T={}){if(typeof d==="object"&&d!==null){let X=d;f=X.page??1,T=X.tx?{tx:X.tx}:{},d=X.perPage??10}if(!Number.isFinite(d)||d<=0||!Number.isInteger(d))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${d}`);if(!Number.isFinite(f)||f<1||!Number.isInteger(f))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${f}`);if(T.tx){let X=Gn(q()),ae=[...D],Ae=await T.tx.unsafe(`SELECT COUNT(*) as c FROM (${X}) as sub`,ae),ee=Number(Ae?.[0]?.c??0),Ne=Math.max(1,Math.ceil(ee/d)),Ue=Math.max(1,Math.min(f,Ne)),Je=(Ue-1)*d;return{data:await T.tx.unsafe(`${X} LIMIT ${d} OFFSET ${Je}`,ae),meta:{perPage:d,page:Ue,total:ee,lastPage:Ne}}}let S=g`SELECT COUNT(*) as c FROM (${x()}) as sub`,A=await h(S,"select",{signal:Q,timeoutMs:I}),[O]=A,K=Number(O?.c??0),F=Math.max(1,Math.ceil(K/d)),z=Math.max(1,Math.min(f,F)),L=(z-1)*d;return{data:await h(g`${x()} LIMIT ${d} OFFSET ${L}`,"select",{signal:Q,timeoutMs:I}),meta:{perPage:d,page:z,total:K,lastPage:F}}},async simplePaginate(d,f=1){let T=Math.max(1,f),S=(T-1)*d,A=await h(g`${x()} LIMIT ${d+1} OFFSET ${S}`,"select",{signal:Q,timeoutMs:I}),O=A.length>d;return{data:O?A.slice(0,d):A,meta:{perPage:d,page:T,hasMore:O}}},async cursorPaginate(d,f,T="id",S="asc"){if(!Number.isInteger(d)||d<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${d}`);let A=(Array.isArray(T)?T:[T]).map(String);for(let We of A)G(We,"cursorPaginate(column)");let O=S==="asc"?">":"<",K=S==="asc"?"ASC":"DESC",F=[...D],z="";if(f!==void 0&&f!==null)if(Array.isArray(T)){let We=f.map((le)=>(F.push(le),Z(F.length)));z=`(${A.join(", ")}) ${O} (${We.join(", ")})`}else F.push(f),z=`${A[0]} ${O} ${Z(F.length)}`;let L=Gn(z?q({conn:"AND",sql:z}):q()),j=A.map((We)=>`${We} ${K}`).join(", ");if(Ef(L))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${j} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let X=F.length>0?t.unsafe(`${L} ORDER BY ${j} LIMIT ${d+1}`,F):t.unsafe(`${L} ORDER BY ${j} LIMIT ${d+1}`),ae=await h(X,"select",{signal:Q,timeoutMs:I}),Ae=ae.length>d,ee=ae.slice(0,d),Ne=ee[ee.length-1],Ue=Ae&&Ne?Array.isArray(T)?T.map((We)=>Ne[We]):Ne[T]:null,Je=ee.length?Array.isArray(T)?T.map((We)=>ee[0]?.[We]):ee[0]?.[T]:null;return{data:ee,meta:{perPage:d,nextCursor:Ue??null,prevCursor:Je}}},async chunk(d,f){let T=1;while(!0){let{data:S,meta:A}=await this.paginate(d,T);if(S.length===0)break;if(await f(S),T>=A.lastPage)break;T+=1}},async chunkById(d,f="id",T){let S;while(!0){let{data:A,meta:O}=await this.cursorPaginate(d,S,f,"asc");if(A.length===0)break;if(T)await T(A);if(S=O.nextCursor,!S)break}},async eachById(d,f="id",T){await this.chunkById(d,f,async(S)=>{for(let A of S)await T?.(A)})},withTimeout(d){return I=Math.max(1,Math.floor(d)),this},abort(d){return Q=d,this},withTrashed(){return se=!0,oe=!1,this},onlyTrashed(){se=!0,oe=!0;let d=_.softDeletes?.column||"deleted_at",f=(A,O)=>{let K=A.toUpperCase(),F=0;for(let z=0;z<A.length;z++){let L=A[z];if(L==="(")F++;else if(L===")")F--;else if(F===0&&K.substring(z,z+5)==="WHERE"&&(z===0||/\s/.test(A[z-1]??""))&&/\s/.test(A[z+5]??""))return`${A.substring(0,z)}WHERE ${O} AND ${A.substring(z+6)}`}return`${A} WHERE ${O}`},T=`${y}.${d} IS NOT NULL`;p=f(p,T);let S=String(x());return v=g([f(S,T)]),this},scope(d,f){let T=String(y),A=n?.scopes?.[T]?.[d];if(A)return A(this,f);return this},when(d,f,T){if(d)return f(this);if(T)return T(this);return this},tap(d){return d(this),this},dump(){return console.log(String(x())),this},dd(){throw console.log(String(x())),Error("Dump and Die")},cache(d=60000){return ln=d,fe=!0,this},async explain(){let d=g`EXPLAIN ${x()}`;return await h(d,"select",{signal:Q,timeoutMs:I})},simple(){return x().simple()},toText(){return q()},async get(){let d=o(),f=d&&(d.onQueryStart||d.onQueryEnd||d.onQueryError||d.startSpan||zn(d));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!f){let K=t._prepareStatement;if(K){let F=K(q());return $t(D.length>0?F.all(...D):F.all())}}let T=q();if(v=D.length>0?t.unsafe(T,D):t.unsafe(T),!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!f){let K=x()._stmt,F=x()._params;if(K)return $t(F&&F.length>0?K.all(...F):K.all());return $t(await x().execute())}if(!_.softDeletes?.enabled&&!fe&&!I&&!Q)return $t(await h(x(),"select"));let S=x();if(_.softDeletes?.enabled&&_.softDeletes.defaultFilter&&!se){let K=_.softDeletes.column,F=String(y);if((r?Boolean(r[F]?.columns?.[K]):!0)&&!he.DELETED_AT.test(q()))k("WHERE",`${String(K)} IS ${oe?"NOT ":""}NULL`),S=x()}let A=fe?`${String(S)}\x00${JSON.stringify(D)}`:"";if(fe){let K=is.get(A);if(K)return K}let O=await h(S,"select",{signal:Q,timeoutMs:I});if(fe)is.set(A,O,ln);return $t(O)},async executeTakeFirst(){let d=await h(x(),"select",{signal:Q,timeoutMs:I});return Gt(Array.isArray(d)?d[0]:d)},async executeTakeFirstOrThrow(){let d=await this.executeTakeFirst();if(!d)throw Error("Record not found");return d},async first(){let d=o(),f=d&&(d.onQueryStart||d.onQueryEnd||d.onQueryError||d.startSpan||zn(d));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!f){let A=t._prepareStatement;if(A){let O=q(),K=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,F=A(K),z=D.length>0?F.all(...D):F.all();return Gt(z[0])}}let T=await h(g`${x()} LIMIT 1`,"select",{signal:Q,timeoutMs:I}),[S]=T;return Gt(S)},async firstOrFail(){let d=await this.first();if(!d)throw Error("Record not found");return d},async find(d){let f=n?.primaryKeys[String(y)]??"id",T=await h(g`${x()} WHERE ${g(f)} = ${d} LIMIT 1`,"select",{signal:Q,timeoutMs:I}),[S]=T;return S},async findOrFail(d){let f=await this.find(d);if(!f)throw Error("Record not found");return f},async findMany(d){let f=n?.primaryKeys[String(y)]??"id";return await h(g`${x()} WHERE ${g(String(f))} IN ${g(d)}`,"select",{signal:Q,timeoutMs:I})},async*lazy(){let d,f=n?.primaryKeys[String(y)]??"id";while(!0){let S=await(d==null?g`${x()} ORDER BY ${g(String(f))} ASC LIMIT 100`:g`${x()} WHERE ${g(String(f))} > ${d} ORDER BY ${g(String(f))} ASC LIMIT 100`).execute();if(S.length===0)break;for(let A of S)yield A;if(d=S[S.length-1]?.[f],d==null)break}},async*lazyById(){let d=n?.primaryKeys[String(y)]??"id",f;while(!0){let S=await(f==null?g`${x()} ORDER BY ${g(String(d))} ASC LIMIT 100`:g`${x()} WHERE ${g(String(d))} > ${f} ORDER BY ${g(String(d))} ASC LIMIT 100`).execute();if(S.length===0)break;for(let A of S)yield A;if(f=S[S.length-1]?.[d],f==null)break}},pipe(d){return d(this)},async count(){let d=q(),f=d.indexOf(" FROM "),T=/ GROUP BY /i.test(d),S;if(T)S=`SELECT COUNT(*) as c FROM (${d}) AS _bqb_count_sub`;else if(f!==-1)S=`SELECT COUNT(*) as c${d.substring(f)}`;else S=`SELECT COUNT(*) as c FROM ${y}`;let A=o(),O=A&&(A.onQueryStart||A.onQueryEnd||A.onQueryError||A.startSpan||zn(A));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!O){let L=t._prepareStatement;if(L){let j=L(S),X=D.length>0?j.all(...D):j.all();return Number(X[0]?.c??0)}}let K=D.length>0?t.unsafe(S,D):t.unsafe(S),F=await h(K,"select",{signal:Q,timeoutMs:I}),[z]=F;return Number(z?.c??0)},async avg(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT AVG(${d}) as a${f.substring(T)}`:`SELECT AVG(${d}) as a FROM ${y}`,A=o(),O=A&&(A.onQueryStart||A.onQueryEnd||A.onQueryError||A.startSpan||zn(A));if(!_.softDeletes?.enabled&&!fe&&!I&&!Q&&!O){let L=t._prepareStatement;if(L){let j=L(S),X=D.length>0?j.all(...D):j.all();return Number(X[0]?.a??0)}}let K=D.length>0?t.unsafe(S,D):t.unsafe(S),F=await h(K,"select",{signal:Q,timeoutMs:I}),[z]=F;return Number(z?.a??0)},async sum(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT SUM(${d}) as s${f.substring(T)}`:`SELECT SUM(${d}) as s FROM ${y}`,A=D.length>0?t.unsafe(S,D):t.unsafe(S),O=await h(A,"select",{signal:Q,timeoutMs:I}),[K]=O;return Number(K?.s??0)},async max(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT MAX(${d}) as m${f.substring(T)}`:`SELECT MAX(${d}) as m FROM ${y}`,A=D.length>0?t.unsafe(S,D):t.unsafe(S),O=await h(A,"select",{signal:Q,timeoutMs:I}),[K]=O;return K?.m},async min(d){let f=q(),T=f.indexOf(" FROM "),S=T!==-1?`SELECT MIN(${d}) as m${f.substring(T)}`:`SELECT MIN(${d}) as m FROM ${y}`,A=D.length>0?t.unsafe(S,D):t.unsafe(S),O=await h(A,"select",{signal:Q,timeoutMs:I}),[K]=O;return K?.m},lockForUpdate(){return p+=" FOR UPDATE",v=null,this},sharedLock(){let d=_.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return p+=` ${d}`,v=null,this},withCTE(d,f){return G(d,"withCTE(name)"),p=`WITH ${d} AS (${String(f.toSQL())}) ${p}`,v=null,this},withRecursive(d,f){return G(d,"withRecursive(name)"),p=`WITH RECURSIVE ${d} AS (${String(f.toSQL())}) ${p}`,v=null,this},execute(){return h(x(),"select",{signal:Q,timeoutMs:I})},values(){return x().values()},toParams(){return[...D]},__rawState(){return{sql:Gn(q()),params:[...D]}},__hasPredicate(){return E.length>0||B},raw(){return x().raw()},get rows(){return},get row(){return},cancel(){try{x().cancel()}catch{}}},{get(d,f,T){let S=Reflect.get(d,f,T);if(S!==void 0)return S;if(typeof f==="string"&&(f.startsWith("where")||f.startsWith("orWhere")||f.startsWith("andWhere"))){let A=f.startsWith("orWhere"),O=f.startsWith("andWhere"),K=`${String(y)}|${f}`,F=l.get(K);if(F===void 0){let L=f.replace(/^(?:or|and)?where/i,"");if(!L)l.set(K,""),F="";else{let j=L.charAt(0).toLowerCase()+L.slice(1),X=L.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ae=r?Object.keys(r[String(y)]?.columns??{}):[];F=[X,j,j.toLowerCase()].find((Ae)=>ae.includes(Ae))??X,l.set(K,F)}}if(F==="")return()=>T;let z=F;return(L)=>{if(Array.isArray(L)){let j=ve(L.length,D.length+1);k(A?"OR":O?"AND":"WHERE",`${z} IN (${j})`),D.push(...L)}else{let j=Z(D.length+1);k(A?"OR":O?"AND":"WHERE",`${z} = ${j}`),D.push(L)}return T}}return Reflect.get(d,f,T)}})}return{configure(y){return Ra(y),this},id(y){if(!he.IDENTIFIER.test(y))throw Error(`[query-builder] Invalid identifier: '${y}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return t(String(y))},ids(...y){for(let b of y)if(!he.IDENTIFIER.test(b))throw Error(`[query-builder] Invalid identifier: '${b}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return t(y)},select(y,...b){return R(y,b)},selectFrom(y){return R(y)},selectFromSub(y,b){function g(x){return()=>{throw Error(`[query-builder] selectFromSub(...).${x}() is not supported. Apply ${x}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}G(String(b),"selectFromSub(alias)");let p=typeof y.__rawState==="function"?y.__rawState():null,E=y.toSQL(),D=p?.sql??(typeof E==="string"?E:E?.sql??String(E)),J=p?.params??(Array.isArray(E?.values)?E.values:[]),B=`SELECT * FROM (${D}) AS ${String(b)}`,W=(x,C,k,P)=>{let q=[...x],H=(V,U,Y)=>{G(V,"selectFromSub where(column)");let I=Oe(U,"selectFromSub where(operator)");if(I==="in"||I==="not in"){let se=Array.isArray(Y)?Y:[Y],oe=ve(se.length,q.length+1);return q.push(...se),`${V} ${I.toUpperCase()} (${oe})`}let Q=Z(q.length+1);return q.push(Y),`${V} ${I} ${Q}`},M;if(typeof C==="string"&&k!==void 0)M=H(C,k,P);else if(Array.isArray(C)&&C.length===3)M=H(C[0],C[1],C[2]);else if(C&&typeof C==="object"){let V=Object.entries(C).map(([U,Y])=>H(U,"=",Y));M=V.length>1?`(${V.join(" AND ")})`:V[0]}else return{clause:null,params:x};return{clause:M,params:q}};function v(x,C,k,P=""){let q=tn(C),H=q?`${x} WHERE ${q}${P}`:`${x}${P}`,M=()=>k.length>0?t.unsafe(H,k):t.unsafe(H),V=(I,Q,se,oe)=>{let fe=W(k,Q,se,oe);return fe.clause===null?v(x,C,k,P):v(x,[...C,{conn:I,sql:fe.clause}],fe.params,P)},U=(I,Q)=>{let se=[],oe=[...k],fe=(ln)=>(Se,yt,Gt)=>{let $t=W(oe,Se,yt,Gt);if($t.clause!==null)se.push({conn:ln,sql:$t.clause}),oe=$t.params;return at},at={where:fe("AND"),andWhere:fe("AND"),orWhere:fe("OR")};Q(at);let nt=tn(se);if(!nt)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return v(x,[...C,{conn:I,sql:`(${nt})`}],oe,P)},Y={distinct(){return v(x.replace(/^SELECT\s+/i,"SELECT DISTINCT "),C,k,P)},distinctOn(...I){let Q=I.map(String).join(", ");return v(x.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${Q}) `),C,k,P)},selectRaw(I){let Q=nn(I,"selectFromSub.selectRaw(fragment)"),se=x.indexOf(" FROM "),oe=se!==-1?`${x.slice(0,se)}, ${Q}${x.slice(se)}`:`${x}, ${Q}`;return v(oe,C,k,P)},$call(I){return I(this)??this},where(I,Q,se){return V("AND",I,Q,se)},andWhere(I,Q,se){return V("AND",I,Q,se)},orWhere(I,Q,se){return V("OR",I,Q,se)},whereGroup(I){return U("AND",I)},orWhereGroup(I){return U("OR",I)},orderBy(I,Q="asc"){G(String(I),"selectFromSub.orderBy(column)");let se=Q==="asc"?"ASC":"DESC",oe=he.ORDER_BY.test(P)?`${P}, ${I} ${se}`:`${P} ORDER BY ${I} ${se}`;return v(x,C,k,oe)},limit(I){if(!Number.isInteger(I)||I<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${I}`);let Q=he.LIMIT.test(P)?P.replace(he.LIMIT,` LIMIT ${I}`):`${P} LIMIT ${I}`;return v(x,C,k,Q)},offset(I){if(!Number.isInteger(I)||I<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${I}`);let Q=he.OFFSET.test(P)?P.replace(he.OFFSET,` OFFSET ${I}`):`${P} OFFSET ${I}`;return v(x,C,k,Q)},toSQL(){return N(M(),H)},async execute(){return h(M(),"select")},async executeTakeFirst(){let I=await h(M(),"select");return Array.isArray(I)?I[0]:I},async executeTakeFirstOrThrow(){let I=await h(M(),"select"),Q=Array.isArray(I)?I[0]:I;if(!Q)throw Error("Record not found");return Q},async get(){return h(M(),"select")},async first(){let I=await h(M(),"select");return Array.isArray(I)?I[0]:I},async firstOrFail(){let I=await h(M(),"select"),Q=Array.isArray(I)?I[0]:I;if(!Q)throw Error("No rows found");return Q},async count(){let I=k.length>0?t.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,k):t.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),Q=await h(I,"select");return Number(Q?.[0]?.c??0)},async exists(){let I=k.length>0?t.unsafe(`SELECT EXISTS(${H}) as e`,k):t.unsafe(`SELECT EXISTS(${H}) as e`),Q=await h(I,"select");return Boolean(Q?.[0]?.e)},async doesntExist(){return!await Y.exists()},values(){return M().values()},raw(){return M().raw()},cancel(){try{M().cancel()}catch{}},whereRaw:g("whereRaw"),whereColumn:g("whereColumn"),orWhereColumn:g("orWhereColumn"),whereIn:g("whereIn"),orWhereIn:g("orWhereIn"),whereNotIn:g("whereNotIn"),orWhereNotIn:g("orWhereNotIn"),whereLike:g("whereLike"),whereILike:g("whereILike"),orWhereLike:g("orWhereLike"),orWhereILike:g("orWhereILike"),whereNotLike:g("whereNotLike"),whereNotILike:g("whereNotILike"),orWhereNotLike:g("orWhereNotLike"),orWhereNotILike:g("orWhereNotILike"),whereAny:g("whereAny"),whereAll:g("whereAll"),whereNone:g("whereNone"),whereNested:g("whereNested"),orWhereNested:g("orWhereNested"),whereDate:g("whereDate"),whereBetween:g("whereBetween"),whereNotBetween:g("whereNotBetween"),whereJsonContains:g("whereJsonContains"),whereJsonPath:g("whereJsonPath"),whereNull:g("whereNull"),orWhereNull:g("orWhereNull"),whereNotNull:g("whereNotNull"),orWhereNotNull:g("orWhereNotNull"),whereExists:g("whereExists"),orWhereExists:g("orWhereExists"),orWhereBetween:g("orWhereBetween"),orWhereRaw:g("orWhereRaw"),whereJsonDoesntContain:g("whereJsonDoesntContain"),whereJsonContainsKey:g("whereJsonContainsKey"),whereJsonDoesntContainKey:g("whereJsonDoesntContainKey"),whereJsonLength:g("whereJsonLength"),join:g("join"),joinSub:g("joinSub"),innerJoin:g("innerJoin"),leftJoin:g("leftJoin"),leftJoinSub:g("leftJoinSub"),rightJoin:g("rightJoin"),crossJoin:g("crossJoin"),crossJoinSub:g("crossJoinSub"),groupBy:g("groupBy"),groupByRaw:g("groupByRaw"),having:g("having"),havingRaw:g("havingRaw"),addSelect:g("addSelect"),select:g("select"),selectAll:g("selectAll"),orderByDesc:g("orderByDesc"),inRandomOrder:g("inRandomOrder"),reorder:g("reorder"),orderByRaw:g("orderByRaw"),union:g("union"),unionAll:g("unionAll"),forPage:g("forPage"),selectAllRelations:g("selectAllRelations"),with:g("with"),value:g("value"),pluck:g("pluck"),cursorPaginate:g("cursorPaginate"),paginate:g("paginate"),simplePaginate:g("simplePaginate"),chunk:g("chunk"),chunkById:g("chunkById"),eachById:g("eachById"),avg:g("avg"),sum:g("sum"),max:g("max"),min:g("min"),find:g("find"),findOrFail:g("findOrFail"),findMany:g("findMany"),latest:g("latest"),oldest:g("oldest"),lazy:g("lazy"),lazyById:g("lazyById"),pipe:(I)=>I(Y),when:g("when"),tap:()=>Y,dump:()=>Y,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>M().simple(),toText:()=>H,toParams:()=>[...k],withTimeout:()=>Y,abort:()=>Y,lockForUpdate:()=>Y,sharedLock:()=>Y,withCTE:()=>Y,withRecursive:()=>Y,cache:()=>Y,clone:()=>Y,withTrashed:()=>Y,onlyTrashed:()=>Y,scope:()=>Y,get rows(){return[]},get row(){return}};return Y}return v(B,[],J)},insertInto(y){let b,g="",p=[],E=[],D=!1,J=()=>W?[]:{changes:0,lastInsertRowid:0},B=()=>{let k=async()=>{return},P=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>B(),andWhere:()=>B(),orWhere:()=>B(),orderBy:()=>B(),limit:()=>B(),offset:()=>B(),toSQL:()=>N(null,""),execute:async()=>[],get:async()=>[],first:k,executeTakeFirst:k,firstOrFail:P,executeTakeFirstOrThrow:P}},W=_.dialect==="postgres",v=(k)=>{let q=k.flat(2).map(String).filter(Boolean),H=q.length>0&&!q.includes("*")?q.map((U)=>x(U)).join(", "):"*",M=async()=>{let U=await h(t.unsafe(g,p),"insert"),Y=Number(U?.lastInsertRowid??0),I=Math.max(1,Number(U?.affectedRows??1)),Q=E.filter((fe)=>fe!==void 0&&fe!==null),se=Y>0?t.unsafe(`SELECT ${H} FROM ${x(String(y))} WHERE ${x("id")} >= ? AND ${x("id")} < ? ORDER BY ${x("id")} ASC`,[Y,Y+I]):Q.length>0?t.unsafe(`SELECT ${H} FROM ${x(String(y))} WHERE ${x("id")} IN (${Q.map(()=>"?").join(", ")}) ORDER BY ${x("id")} ASC`,Q):null;if(!se)return[];let oe=await se.execute();return Array.isArray(oe)?oe:[]},V=async()=>(await M())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>N(t.unsafe(g,p),g),execute:M,get:M,first:V,executeTakeFirst:V,async firstOrFail(){let U=await V();if(!U)throw Error("Insert with RETURNING returned no rows");return U},async executeTakeFirstOrThrow(){let U=await V();if(!U)throw Error("Insert with RETURNING returned no rows");return U}}},x=W?(k)=>`"${String(k).replace(/"/g,'""')}"`:ne(_.dialect)?(k)=>`\`${String(k).replace(/`/g,"``")}\``:(k)=>`"${String(k).replace(/"/g,'""')}"`,C=W?(k)=>`$${k+1}`:(k)=>"?";return{values(k){let P=s(String(y),Array.isArray(k)?k:[k]),q=P.length;if(E=P.map((I)=>I?.id),q===0)return D=!0,b=null,g="",p.length=0,this;D=!1;let H=P[0],M=Object.keys(H),V=M.length,U=q*V;p.length=U;let Y=W?M.map((I)=>x(I)).join(","):M.join(",");if(q===1)if(!W){let I=x(M[0]),Q="?";p[0]=H[M[0]];for(let se=1;se<V;se++)I+=`,${x(M[se])}`,Q+=",?",p[se]=H[M[se]];g=`INSERT INTO ${x(y)}(${I})VALUES(${Q})`}else{g=`INSERT INTO ${x(y)}(${Y})VALUES(`;for(let I=0;I<V;I++){if(I>0)g+=",";g+=C(I),p[I]=H[M[I]]}g+=")"}else{let I=M.map((se)=>x(se)).join(",");g=`INSERT INTO ${x(y)}(${I})VALUES`;let Q=0;for(let se=0;se<q;se++){let oe=P[se];if(se===0)g+="(";else g+="),(";for(let fe=0;fe<V;fe++){if(fe>0)g+=",";g+=C(Q),p[Q++]=oe[M[fe]]}}g+=")"}if(!t._prepareStatement)b=t.unsafe(g,p);return this},returning(...k){if(D)return B();if(ne(_.dialect))return v(k);let P=`${g} RETURNING ${k.join(", ")}`,q=t.unsafe(P,p),H=async()=>{let M=await h(q,"insert");return Array.isArray(M)?M[0]:M};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>N(q,P),execute:()=>h(q,"insert"),get:()=>h(q,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let M=await H();if(!M)throw Error("Insert with RETURNING returned no rows");return M},async executeTakeFirstOrThrow(){let M=await H();if(!M)throw Error("Insert with RETURNING returned no rows");return M}}},toSQL(){if(D)return N(null,"");if(!b)b=t.unsafe(g,p);return N(b,g)},execute(){if(D)return Promise.resolve(J());let k=o();if(!(k&&(k.onQueryStart||k.onQueryEnd||k.onQueryError||k.startSpan||k.beforeCreate||k.afterCreate||zn(k)))){let q=t._prepareStatement;if(q){let H=q(g);return p.length>0?H.run(...p):H.run()}}if(!b)b=t.unsafe(g,p);return h(b,"insert")},async executeTakeFirst(){if(D)return J();if(!b)b=t.unsafe(g,p);return await h(b,"insert")},async executeTakeFirstOrThrow(){if(D)throw Error("Insert failed");if(!b)b=t.unsafe(g,p);let k=await h(b,"insert");if(!k)throw Error("Insert failed");return k},returningAll(){if(D)return B();let k=`${g} RETURNING *`,P=t.unsafe(k,p),q=async()=>{let H=await h(P,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>N(P,k),execute:()=>h(P,"insert"),get:()=>h(P,"insert"),first:q,executeTakeFirst:q,async firstOrFail(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(y){let b,g=[],p=(B)=>{let W=String(B);if(ne(_.dialect))return`\`${W.replace(/`/g,"``")}\``;return`"${W.replace(/"/g,'""')}"`},E=`UPDATE ${p(String(y))}`,D=!1,J=(B)=>{E=`${E} ${D?"AND":"WHERE"} ${B}`,D=!0};return{set(B){let W=s(String(y),[B])[0],v=Object.keys(W),x=v.length,C=Array.from({length:x});for(let k=0;k<x;k++){let P=v[k],q=W[P];if(wt(q))C[k]=`${p(P)} = ${q.raw}`;else if(Jn(q)){let H=Hn(q,g.length+1);C[k]=`${p(P)} = ${H.text}`,g.push(...H.parameters)}else C[k]=`${p(P)} = ${Z(g.length+1)}`,g.push(q)}return E=`${E} SET ${C.join(", ")}`,b=t.unsafe(E,g),this},where(B,W,v){if(W!==void 0&&(typeof B==="string"||wt(B)||Jn(B))){let x=Oe(W,"updateTable.where"),C;if(typeof B==="string")C=p(B);else if(wt(B))C=B.raw;else{let P=Hn(B,g.length+1);C=P.text,g.push(...P.parameters)}if(x.toLowerCase()==="in"||x.toLowerCase()==="not in"){let P=Array.isArray(v)?v:[v],q=ve(P.length,g.length+1);return J(`${C} ${x.toUpperCase()} (${q})`),g.push(...P),b=t.unsafe(E,g),this}let k=g.length+1;return J(`${C} ${x} ${Z(k)}`),g.push(v),b=t.unsafe(E,g),this}if(Array.isArray(B)){let[x,C,k]=B,P=Oe(C,"updateTable.where");if(P.toLowerCase()==="in"||P.toLowerCase()==="not in"){let H=Array.isArray(k)?k:[k],M=ve(H.length,g.length+1);return J(`${p(String(x))} ${P.toUpperCase()} (${M})`),g.push(...H),b=t.unsafe(E,g),this}let q=g.length+1;return J(`${p(String(x))} ${P} ${Z(q)}`),g.push(k),b=t.unsafe(E,g),this}if(wt(B))return J(B.raw),b=t.unsafe(E,g),this;if(Jn(B)){let x=Hn(B,g.length+1);return J(x.text),g.push(...x.parameters),b=t.unsafe(E,g),this}if(B&&typeof B==="object"){let x=Object.keys(B);if(x.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let C=x.map((k)=>yi(p(k),B[k],g));return J(C.join(" AND ")),b=t.unsafe(E,g),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${B===null?"null":typeof B}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(B){return J(`${p(String(B))} IS NULL`),b=t.unsafe(E,g),this},whereNotNull(B){return J(`${p(String(B))} IS NOT NULL`),b=t.unsafe(E,g),this},returning(...B){let W=this,v=()=>`${E} RETURNING ${B.join(", ")}`,x=()=>g.length>0?t.unsafe(v(),g):t.unsafe(v()),C=async()=>{let M=/\sWHERE\s/i.test(E),V=M?E.slice(E.search(/\sWHERE\s/i)+1):"",U=g.slice(g.length-(V.match(/\?|\$\d+/g)?.length??0)),Y=p("id"),I=await(U.length>0?t.unsafe(`SELECT ${Y} FROM ${p(String(y))}${M?` ${V}`:""}`,U):t.unsafe(`SELECT ${Y} FROM ${p(String(y))}${M?` ${V}`:""}`)).execute().catch(()=>[]),Q=(Array.isArray(I)?I:[]).map((fe)=>fe?.id).filter((fe)=>fe!==void 0&&fe!==null);if(await h(g.length>0?t.unsafe(E,g):t.unsafe(E),"update"),Q.length===0)return[];let se=`SELECT ${B.join(", ")} FROM ${p(String(y))} WHERE ${Y} IN (${Q.map(()=>"?").join(", ")})`,oe=await t.unsafe(se,Q).execute();return Array.isArray(oe)?oe:[]},k=()=>ne(_.dialect)?C():h(x(),"update"),P=async()=>{let M=await k();return Array.isArray(M)?M[0]:M},q=(M)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${M}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},H={where:(...M)=>(W.where(...M),H),andWhere:(...M)=>(W.where(...M),H),whereNull:(...M)=>(W.whereNull(...M),H),whereNotNull:(...M)=>(W.whereNotNull(...M),H),orWhere:q("orWhere"),orderBy:q("orderBy"),limit:q("limit"),offset:q("offset"),toSQL:()=>N(x(),v()),execute:k,get:k,first:P,executeTakeFirst:P,async firstOrFail(){let M=await P();if(!M)throw Error("Update with RETURNING returned no rows");return M},async executeTakeFirstOrThrow(){let M=await P();if(!M)throw Error("Update with RETURNING returned no rows");return M}};return H},toSQL(){if(!b)b=g.length>0?t.unsafe(E,g):t.unsafe(E);return N(b,E)},async execute(){let B=await h(b,"update");return w(B)},async executeTakeFirst(){return{numUpdatedRows:w(await h(b,"update"))}},async executeTakeFirstOrThrow(){let B=w(await h(b,"update"));if(B===0)throw Error("No rows updated");return{numUpdatedRows:B}},returningAll(){let B=()=>`${E} RETURNING *`,W=()=>g.length>0?t.unsafe(B(),g):t.unsafe(B());return{toSQL:()=>N(W(),B()),execute:()=>h(W(),"update"),async executeTakeFirst(){let v=await h(W(),"update");return Array.isArray(v)?v[0]:v},async executeTakeFirstOrThrow(){let v=await h(W(),"update"),x=Array.isArray(v)?v[0]:v;if(!x)throw Error("Update with RETURNING failed");return x}}}}},deleteFrom(y){let b=(x)=>{let C=String(x);if(ne(_.dialect))return`\`${C.replace(/`/g,"``")}\``;return`"${C.replace(/"/g,'""')}"`},p=`DELETE FROM ${b(String(y))}`,E=null,D=[],J=null,B=!1,W=(x)=>{p+=` ${B?"AND":"WHERE"} ${x}`,B=!0},v=()=>{if(E===null)E=D.length>0?t.unsafe(p,D):t.unsafe(p);return E};return{where(x,C,k){if(J=x,typeof x==="string"&&C!==void 0){let P=Oe(C,"deleteFrom.where");if(P.toLowerCase()==="in"||P.toLowerCase()==="not in"){let H=Array.isArray(k)?k:[k],M=ve(H.length,D.length+1);return W(`${b(x)} ${P.toUpperCase()} (${M})`),D.push(...H),E=null,this}let q=D.length+1;return W(`${b(x)} ${P} ${Z(q)}`),D.push(k),E=null,this}if(Array.isArray(x)){let[P,q,H]=x,M=Oe(q,"deleteFrom.where");if(M.toLowerCase()==="in"||M.toLowerCase()==="not in"){let U=Array.isArray(H)?H:[H],Y=ve(U.length,D.length+1);return W(`${b(String(P))} ${M.toUpperCase()} (${Y})`),D.push(...U),E=null,this}let V=D.length+1;return W(`${b(String(P))} ${M} ${Z(V)}`),D.push(H),E=null,this}if(wt(x))return W(x.raw),E=null,this;if(Jn(x)){let P=Hn(x,D.length+1);return W(P.text),D.push(...P.parameters),E=null,this}if(x&&typeof x==="object"){let P=Object.keys(x);if(P.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let q=P.map((H)=>yi(b(H),x[H],D));return W(q.join(" AND ")),E=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${x===null?"null":typeof x}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(x){return W(`${b(String(x))} IS NULL`),E=null,this},whereNotNull(x){return W(`${b(String(x))} IS NOT NULL`),E=null,this},returning(...x){let C=this,k=()=>`${p} RETURNING ${x.join(", ")}`,P=()=>D.length>0?t.unsafe(k(),D):t.unsafe(k()),q=async()=>{await o()?.beforeDelete?.({table:String(y),where:J});let U=ne(_.dialect)?await(async()=>{let Y=p.slice(p.search(/\sFROM\s/i)+1),I=`SELECT ${x.join(", ")} ${Y}`,Q=await(D.length>0?t.unsafe(I,D):t.unsafe(I)).execute();return await h(D.length>0?t.unsafe(p,D):t.unsafe(p),"delete"),Array.isArray(Q)?Q:[]})():await h(P(),"delete");try{await o()?.afterDelete?.({table:String(y),where:J,result:U})}catch{}return U},H=async()=>{let U=await q();return Array.isArray(U)?U[0]:U},M=(U)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${U}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},V={where:(...U)=>(C.where(...U),V),andWhere:(...U)=>(C.where(...U),V),whereNull:(...U)=>(C.whereNull(...U),V),whereNotNull:(...U)=>(C.whereNotNull(...U),V),orWhere:M("orWhere"),orderBy:M("orderBy"),limit:M("limit"),offset:M("offset"),toSQL:()=>N(P(),k()),execute:()=>q(),get:()=>q(),first:H,executeTakeFirst:H,async firstOrFail(){let U=await H();if(!U)throw Error("Delete with RETURNING returned no rows");return U},async executeTakeFirstOrThrow(){let U=await H();if(!U)throw Error("Delete with RETURNING returned no rows");return U}};return V},toSQL(){return N(v(),p)},async execute(){try{await o()?.beforeDelete?.({table:String(y),where:J})}catch(C){throw C}let x=w(await h(v(),"delete"));try{await o()?.afterDelete?.({table:String(y),where:J,result:x})}catch{}return x},async executeTakeFirst(){return{numDeletedRows:w(await h(v(),"delete"))}},async executeTakeFirstOrThrow(){let x=w(await h(v(),"delete"));if(x===0)throw Error("No rows deleted");return{numDeletedRows:x}},returningAll(){let x=()=>`${p} RETURNING *`,C=()=>D.length>0?t.unsafe(x(),D):t.unsafe(x());return{toSQL:()=>N(C(),x()),execute:()=>h(C(),"delete"),async executeTakeFirst(){let k=await h(C(),"delete");return Array.isArray(k)?k[0]:k},async executeTakeFirstOrThrow(){let k=await h(C(),"delete"),P=Array.isArray(k)?k[0]:k;if(!P)throw Error("Delete with RETURNING failed");return P}}}}},table(y){let b=this;return{insert(g){return b.insertInto(y).values(g)},update(g){return b.updateTable(y).set(g)},delete(){return b.deleteFrom(y)},select(...g){if(g.length===0)return b.selectFrom(y);return b.select(y,...g)}}},sql:t,raw(y,...b){return t(y,...b)},simple(y,...b){return t(y,...b).simple()},async advisoryLock(y){if(_.dialect==="postgres"){let b=i(y),g=t`SELECT pg_advisory_lock(${b})`;await h(g,"raw");return}if(ne(_.dialect)){let b=`bqb:${String(y)}`,g=t`SELECT GET_LOCK(${b}, -1) AS ok`;await h(g,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(y){if(_.dialect==="postgres"){let b=i(y),g=t`SELECT pg_try_advisory_lock(${b}) as ok`,p=await h(g,"raw");return Boolean(p?.[0]?.ok)}if(ne(_.dialect)){let b=`bqb:${String(y)}`,g=t`SELECT GET_LOCK(${b}, 0) AS ok`,p=await h(g,"raw");return Number(p?.[0]?.ok)===1}return!1},async advisoryUnlock(y){if(_.dialect==="postgres"){let b=i(y),g=t`SELECT pg_advisory_unlock(${b}) as ok`,p=await h(g,"raw");return Boolean(p?.[0]?.ok)}if(ne(_.dialect)){let b=`bqb:${String(y)}`,g=t`SELECT RELEASE_LOCK(${b}) AS ok`,p=await h(g,"raw");return Number(p?.[0]?.ok)===1}return!1},unsafe(y,b){return t.unsafe(y,b)},file(y,b){return t.file(y,b)},async reserve(){let y=await te.reserve(),b=ie({sql:y,meta:n,schema:r,hooks:e?.hooks});return b.release=()=>y.release(),b},async close(y){await te.close(y)},async listen(y,b){},async unlisten(y){},async notify(y,b){},async copyTo(y,b){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(y,b,g){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let y=t`SELECT 1`;return await h(y,"select"),!0}catch{return!1}},async waitForReady(y){let b=Math.max(1,y?.attempts??10),g=Math.max(10,y?.delayMs??100);for(let p=0;p<b;p++){if(await this.ping())return;await new Promise((E)=>setTimeout(E,g))}throw Error("Database not ready after waiting")},async transaction(y,b){let p={...e?.txDefaults,...b},E=e?.sql??te,D=e?.inTransaction===!0,J=D&&typeof E?.savepoint==="function"?"savepoint":"begin",B=async(x)=>{p.logger?.({type:"start",attempt:x});let C=Date.now();return await E[J](async(k)=>{let P=ie({sql:k,meta:n,schema:r,hooks:e?.hooks,inTransaction:!0});if(p?.isolation&&!D){let M=p.isolation,V=M==="read committed"?"READ COMMITTED":M==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(_.dialect==="postgres")await k.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(ne(_.dialect))await k.unsafe(`SET TRANSACTION ISOLATION LEVEL ${V}`);else if(M!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${M}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(p?.readOnly)if(_.dialect==="postgres")await k.unsafe("SET TRANSACTION READ ONLY");else if(ne(_.dialect))await k.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let q=await y(P),H=Date.now()-C;return p.logger?.({type:"commit",attempt:x,durationMs:H}),q})},W=Math.max(0,p?.retries??0),v=0;for(;;)try{let x=await B(v+1);return p?.afterCommit?.(),x}catch(x){let C=Cf(x)||vf(x,p.sqlStates);if(v<W&&C){v++,p?.onRetry?.(v,x);let k=_f(v,p.backoff);if(k>0)await Af(k);continue}try{p.onRollback?.(x)}catch{}try{p.afterRollback?.()}catch{}throw x}},async savepoint(y){if(e?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let b=t;if(!b||typeof b.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await b.savepoint(async(g)=>{let p=ie({sql:g,meta:n,schema:r,hooks:e?.hooks,inTransaction:!0});return await y(p)})},async beginDistributed(y,b){return await(e?.sql??te).beginDistributed(y,async(E)=>{let D=ie({sql:E,meta:n,schema:r,hooks:e?.hooks});return await b(D)})},async commitDistributed(y){await te.commitDistributed(y)},async rollbackDistributed(y){await te.rollbackDistributed(y)},setTransactionDefaults(y){e={...e,txDefaults:{...e?.txDefaults,...y}}},transactional(y,b){return(...g)=>this.transaction((p)=>y(p,...g),b)},async insertOrIgnore(y,b){let g=Array.isArray(b)?b:[b];if(!g.length)return;let{colsSql:p,valuesSql:E,params:D}=rs(g),J=Ye(String(y)),B=ne(_.dialect)?`INSERT IGNORE INTO ${J} (${p}) VALUES ${E}`:`INSERT INTO ${J} (${p}) VALUES ${E} ON CONFLICT DO NOTHING`;return t.unsafe(B,D).execute()},async insertGetId(y,b,g="id"){let{colsSql:p,valuesSql:E,params:D}=rs([b]),J=Ye(String(y));if(ne(_.dialect)){await t.unsafe(`INSERT INTO ${J} (${p}) VALUES ${E}`,D).execute();let[W]=await t.unsafe("SELECT LAST_INSERT_ID() as id").execute();return W?.id}if(_.dialect==="sqlite"){let W=await t.unsafe(`INSERT INTO ${J} (${p}) VALUES ${E}`,D).execute();if(W?.lastInsertRowid!=null)return W.lastInsertRowid;let[v]=await t.unsafe("SELECT last_insert_rowid() as id").execute();return v?.id}let[B]=await t.unsafe(`INSERT INTO ${J} (${p}) VALUES ${E} RETURNING ${Ye(String(g))} as id`,D).execute();return B?.id},async updateOrInsert(y,b,g){let p=Ye(String(y)),E=Object.keys(b),D=1,J=E.map((k)=>`${Ye(k)} = ${Z(D++)}`).join(" AND "),B=E.map((k)=>b[k]);if((await t.unsafe(`SELECT 1 FROM ${p} WHERE ${J} LIMIT 1`,B).execute()).length){let k=Object.keys(g),P=1,q=k.map((V)=>`${Ye(V)} = ${Z(P++)}`).join(", "),H=E.map((V)=>`${Ye(V)} = ${Z(P++)}`).join(" AND "),M=[...k.map((V)=>g[V]),...E.map((V)=>b[V])];return await t.unsafe(`UPDATE ${p} SET ${q} WHERE ${H}`,M).execute(),!0}let{colsSql:v,valuesSql:x,params:C}=rs([{...b,...g}]);return await t.unsafe(`INSERT INTO ${p} (${v}) VALUES ${x}`,C).execute(),!0},async upsert(y,b,g,p){let E=g.map((q)=>String(q)),D=(p??[]).map((q)=>String(q)),J=b;if(!J.length)return;let{colsSql:B,valuesSql:W,params:v}=rs(J),x=Ye(String(y)),C=`INSERT INTO ${x} (${B}) VALUES ${W}`;if(ne(_.dialect)){if(D.length===0)return t.unsafe(`INSERT IGNORE INTO ${x} (${B}) VALUES ${W}`,v).execute();let q=D.map((H)=>`${Ye(H)} = VALUES(${Ye(H)})`).join(", ");return t.unsafe(`${C} ON DUPLICATE KEY UPDATE ${q}`,v).execute()}let k=E.map(Ye).join(", ");if(D.length===0)return t.unsafe(`${C} ON CONFLICT (${k}) DO NOTHING`,v).execute();let P=D.map((q)=>`${Ye(q)} = EXCLUDED.${Ye(q)}`).join(", ");return t.unsafe(`${C} ON CONFLICT (${k}) DO UPDATE SET ${P}`,v).execute()},async save(y,b){let g=n?.primaryKeys[String(y)]??"id",p=b[g];if(p!=null)if(await this.selectFrom(y).find(p)){await this.updateTable(y).set(b).where({[g]:p}).execute();let D=await this.selectFrom(y).find(p);if(!D)throw Error("save() failed to retrieve updated row");return D}else return await this.create(y,b);return await this.create(y,b)},async remove(y,b){return await this.deleteFrom(y).where({id:b}).execute()},async find(y,b){return await this.selectFrom(y).find(b)},async findOrFail(y,b){return await this.selectFrom(y).findOrFail(b)},async findMany(y,b){return await this.selectFrom(y).findMany(b)},async latest(y,b){return await this.selectFrom(y).latest(b).first()},async oldest(y,b){return await this.selectFrom(y).oldest(b).first()},skip(y,b){return this.selectFrom(y).offset(b)},async rawQuery(y){let b=Date.now();try{o()?.onQueryStart?.({sql:y,kind:"raw"});let g=await t.unsafe(y);return o()?.onQueryEnd?.({sql:y,durationMs:Date.now()-b,kind:"raw"}),g}catch(g){throw o()?.onQueryError?.({sql:y,error:g,durationMs:Date.now()-b,kind:"raw"}),g}},async create(y,b){let g=n?.primaryKeys[String(y)]??"id";try{await o()?.beforeCreate?.({table:String(y),data:b})}catch(p){throw p}if(_.dialect==="postgres"){let p=t`INSERT INTO ${t(String(y))} ${t(b)} RETURNING ${t(String(g))} as id`,[E]=await p.execute();if(!E?.id)throw console.error(`create() failed to get insert ID for table ${String(y)}`),console.error("Inserted values:",b),Error(`create() failed to get insert ID for table ${String(y)}`);let D=await this.selectFrom(y).find(E.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(y)} with id ${E.id}`),console.error("Inserted values:",b),Error(`create() failed to retrieve inserted row for table ${String(y)} with id ${E.id}`);try{await o()?.afterCreate?.({table:String(y),data:b,result:D})}catch{}return D}else{let p=await this.insertGetId(y,b,g);if(p==null)throw Error(`create() failed to get insert ID for table ${String(y)}`);let E=await this.selectFrom(y).find(p);if(!E)throw console.error(`create() failed to retrieve inserted row for table ${String(y)} with id ${p}`),console.error("Inserted values:",b),Error(`create() failed to retrieve inserted row for table ${String(y)} with id ${p}`);try{await o()?.afterCreate?.({table:String(y),data:b,result:E})}catch{}return E}},async createMany(y,b){if(!b?.length)return;let g=b[0],p=Object.keys(g),E=p.length,D=b.length,J=Array.from({length:D*E}),B=ne(_.dialect)?(x)=>`\`${String(x).replace(/`/g,"``")}\``:(x)=>`"${String(x).replace(/"/g,'""')}"`,W=`INSERT INTO ${B(String(y))}(${p.map(B).join(",")})VALUES`,v=0;for(let x=0;x<D;x++){if(x>0)W+=",";W+="(";let C=b[x];for(let k=0;k<E;k++){if(k>0)W+=",";W+=Z(v+1),J[v++]=C[p[k]]}W+=")"}return t.unsafe(W,J).execute()},async insertMany(y,b){if(!b?.length)return;let g=b[0],p=Object.keys(g),E=p.length,D=b.length,J=D*E,B=Array(J),W=_.dialect==="postgres",v;if(!W){let k=Array(E);for(let P=0;P<E;P++)k[P]="?";v=`(${k.join(",")})`}else v="";let x=Array(D+2);x[0]=`INSERT INTO ${y}(${p.join(",")})VALUES`;let C=0;if(!W){for(let k=0;k<D;k++){let P=b[k];x[k+1]=v;for(let q=0;q<E;q++)B[C++]=P[p[q]]}return t.unsafe(x[0]+x.slice(1,D+1).join(","),B).execute()}for(let k=0;k<D;k++){let P=b[k],q=Array(E);for(let H=0;H<E;H++)q[H]=`$${C+1}`,B[C++]=P[p[H]];x[k+1]=`(${q.join(",")})`}return t.unsafe(x[0]+x.slice(1,D+1).join(","),B).execute()},async updateMany(y,b,g){let p=Object.keys(g),E=p.length;if(E===0)return 0;let D=[],J=Array.from({length:E});for(let W=0;W<E;W++)J[W]=`${p[W]}=${Z(W+1)}`,D.push(g[p[W]]);let B=`UPDATE ${y} SET ${J.join(",")}`;if(Array.isArray(b)){let W=Oe(String(b[1]),"updateMany");B+=` WHERE ${b[0]} ${W} ${Z(D.length+1)}`,D.push(b[2])}else if(wt(b))B+=` WHERE ${b.raw}`;else if(Jn(b)){let W=Hn(b,D.length+1);B+=` WHERE ${W.text}`,D.push(...W.parameters)}else if(b&&typeof b==="object"&&Object.keys(b).length>0){let W=Object.keys(b).map((v)=>yi(v,b[v],D));B+=` WHERE ${W.join(" AND ")}`}else if(b&&typeof b==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${b===null?"null":typeof b}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return t.unsafe(B,D).execute()},async deleteMany(y,b){if(!Array.isArray(b)||b.length===0)return 0;let g=n?.primaryKeys[String(y)]??"id",p=b.length;if(_.dialect==="postgres"){let D=Array(p);for(let J=0;J<p;J++)D[J]=`$${J+1}`;return t.unsafe(`DELETE FROM ${y} WHERE ${g} IN (${D.join(",")})`,b).execute()}let E=Array(p);for(let D=0;D<p;D++)E[D]="?";return t.unsafe(`DELETE FROM ${y} WHERE ${g} IN (${E.join(",")})`,b).execute()},async firstOrCreate(y,b,g){let p=await this.selectFrom(y).where(b).first();if(p)return p;return await this.create(y,{...b,...g})},async updateOrCreate(y,b,g){let p=await this.selectFrom(y).where(b).first();if(p){await this.updateTable(y).set(g).where(b).execute();let E=n?.primaryKeys[String(y)]??"id",D=p[E],J=D!=null?await this.selectFrom(y).find(D):await this.selectFrom(y).where(b).first();if(!J)throw Error("updateOrCreate() failed to retrieve updated row");return J}return await this.create(y,{...b,...g})},async count(y,b){let g=b?t(String(b)):t`*`,p=t`SELECT COUNT(${g}) as c FROM ${t(String(y))}`,[E]=await p.execute();return Number(E?.c??0)},async sum(y,b){let g=t`SELECT SUM(${t(String(b))}) as s FROM ${t(String(y))}`,[p]=await g.execute();return Number(p?.s??0)},async avg(y,b){let g=t`SELECT AVG(${t(String(b))}) as a FROM ${t(String(y))}`,[p]=await g.execute();return Number(p?.a??0)},async min(y,b){let g=t`SELECT MIN(${t(String(b))}) as m FROM ${t(String(y))}`,[p]=await g.execute();return p?.m},async max(y,b){let g=t`SELECT MAX(${t(String(b))}) as m FROM ${t(String(y))}`,[p]=await g.execute();return p?.m},getRelationships(y){if(!n?.relations)return{};let b=n.relations[y];if(!b)return{};let g={};for(let[p,E]of Object.entries(b))if(E&&typeof E==="object"&&Object.keys(E).length>0)g[p]=E;return g},hasRelationship(y,b){if(!n?.relations)return!1;let g=n.relations[y];if(!g)return!1;return Object.values(g).some((p)=>p&&typeof p==="object"&&(b in p))},getRelationshipType(y,b){if(!n?.relations)return null;let g=n.relations[y];if(!g)return null;for(let[p,E]of Object.entries(g))if(E&&typeof E==="object"&&b in E)return p;return null},getRelationshipTarget(y,b){if(!n?.relations)return null;let g=n.relations[y];if(!g)return null;for(let[p,E]of Object.entries(g))if(E&&typeof E==="object"&&b in E){let D=E[b];if(typeof D==="string")return n.modelToTable[D]||D;else if(D&&typeof D==="object"){if("model"in D)return n.modelToTable[D.model]||D.model;if("target"in D)return n.modelToTable[D.target]||D.target}}return null}}}function ja(){is.clear()}function Wa(e){is.setMaxSize(e)}async function If(){console.log("-- Clearing query cache..."),ja(),console.log("-- \u2713 Query cache cleared")}async function Lf(){console.log("-- Query Cache Information"),console.log(),console.log("The query cache is an LRU (Least Recently Used) cache with TTL support."),console.log(),console.log("Configuration:"),console.log(" - Default max size: 100 entries"),console.log(" - Default TTL: 60 seconds (60000ms)"),console.log(" - Eviction: LRU when cache is full"),console.log(),console.log("Usage:"),console.log(' qb.selectFrom("users").cache().get() // Cache for 60s'),console.log(' qb.selectFrom("users").cache(5000).get() // Cache for 5s'),console.log(),console.log("Configuration:"),console.log(" clearQueryCache() // Clear all cached queries"),console.log(" setQueryCacheMaxSize(500) // Set max cache size"),console.log(),console.log("Commands:"),console.log(" qb cache:clear // Clear the cache"),console.log(" qb cache:config --size 500 // Configure cache size")}async function Kf(e={}){if(console.log("-- Configuring query cache..."),console.log(),e.size!==void 0){let t=Number(e.size);if(Number.isNaN(t)||t<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");Wa(t),console.log(`-- \u2713 Cache max size set to: ${t}`)}else console.log("-- No configuration changes specified"),console.log("-- Available options:"),console.log("-- --size <n> Set maximum cache size (default: 100)"),console.log(),console.log("-- Example: qb cache:config --size 500")}import os from"process";import{createInterface as Ff}from"readline";async function Ua(){console.log("-- Query Builder Interactive Console"),console.log("-- Type .help for available commands"),console.log("-- Type .exit or press Ctrl+C to quit"),console.log();let e=ie(),t=Ff({input:os.stdin,output:os.stdout,prompt:"qb> "}),n="",r=!1,s=`
114
114
  Available Commands:
115
115
  .help Show this help message
116
116
  .exit Exit the console
@@ -139,11 +139,11 @@ Tips:
139
139
  `;return}if(a)await i(a)};t.on("line",async(l)=>{await o(l),t.prompt()}),t.on("SIGINT",()=>{if(r)console.log(`
140
140
  -- Multi-line input cancelled`),n="",r=!1,t.prompt();else console.log(`
141
141
  -- Type .exit to quit`),t.prompt()}),t.on("close",()=>{console.log(`
142
- Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{existsSync as qf,readFileSync as jf,writeFileSync as Gn}from"fs";async function Wf(e,t={}){let n=t.format||"json",r=t.output||`${e}.${n}`,s=t.limit;if(console.log(`-- Exporting data from table: ${e}`),console.log(`-- Format: ${n}`),console.log(`-- Output: ${r}`),s)console.log(`-- Limit: ${s} rows`);console.log();try{let o=ie().selectFrom(e);if(s)o=o.limit(s);let l=await o.execute();if(console.log(`-- Retrieved ${l.length} rows`),n==="json")Gn(r,JSON.stringify(l,null,2)),console.log(`-- \u2713 Exported to JSON: ${r}`);else if(n==="csv"){if(l.length===0){Gn(r,""),console.log(`-- \u2713 Exported to CSV: ${r} (empty)`);return}let a=Object.keys(l[0]),c=[a.join(",")];for(let u of l){let m=a.map((h)=>{let w=u[h];if(w===null||w===void 0)return"";let N=String(w);if(N.includes(",")||N.includes('"')||N.includes(`
143
- `))return`"${N.replace(/"/g,'""')}"`;return N});c.push(m.join(","))}Gn(r,c.join(`
144
- `)),console.log(`-- \u2713 Exported to CSV: ${r}`)}else if(n==="sql"){let a=[];for(let c of l){let u=Object.keys(c),m=u.map((h)=>{let w=c[h];if(w===null||w===void 0)return"NULL";if(typeof w==="number")return String(w);return`'${String(w).replace(/'/g,"''")}'`});a.push(`INSERT INTO ${e} (${u.join(", ")}) VALUES (${m.join(", ")});`)}Gn(r,a.join(`
145
- `)),console.log(`-- \u2713 Exported to SQL: ${r}`)}}catch(i){throw console.error(`-- Failed to export data from ${e}:`,i),i}}async function Uf(e,t,n={}){if(!qf(t))throw console.error(`-- File not found: ${t}`),Error(`File not found: ${t}`);let r=n.format||(t.endsWith(".json")?"json":"csv"),s=n.truncate??!1;console.log(`-- Importing data into table: ${e}`),console.log(`-- Format: ${r}`),console.log(`-- File: ${t}`),console.log(`-- Truncate: ${s}`),console.log();try{let i=ie();if(s)await i.deleteFrom(e).execute(),console.log("-- Table truncated");let o=jf(t,"utf8"),l=[];if(r==="json"){if(l=JSON.parse(o),!Array.isArray(l))throw TypeError("JSON file must contain an array of objects")}else if(r==="csv"){let u=o.split(`
146
- `).filter((h)=>h.trim());if(u.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let m=u[0].split(",").map((h)=>h.trim());for(let h=1;h<u.length;h++){let w=u[h].split(",").map((R)=>R.trim()),N={};for(let R=0;R<m.length;R++){let y=w[R];if(y.startsWith('"')&&y.endsWith('"'))y=y.slice(1,-1).replace(/""/g,'"');if(y==="")y=null;else if(!Number.isNaN(Number(y)))y=Number(y);N[m[R]]=y}l.push(N)}}if(l.length===0){console.log("-- No data to import");return}let a=100,c=0;for(let u=0;u<l.length;u+=a){let m=l.slice(u,u+a);await i.insertInto(e).values(m).execute(),c+=m.length,console.log(`-- Imported ${c}/${l.length} rows...`)}console.log(`-- \u2713 Successfully imported ${l.length} rows`)}catch(i){throw console.error(`-- Failed to import data into ${e}:`,i),i}}async function Qf(e={}){let t=_.dialect||"postgres",n=e.output||`dump-${Date.now()}.sql`,r=e.tables?.split(",").map((s)=>s.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${t}`),console.log(`-- Output: ${n}`),r)console.log(`-- Tables: ${r.join(", ")}`);console.log();try{let s=ie(),i=[];if(t==="sqlite")i=(await s.unsafe(`
142
+ Goodbye!`),os.exit(0)}),t.prompt()}async function qf(){return Ua()}Me();import{existsSync as jf,readFileSync as Wf,writeFileSync as Yn}from"fs";async function Uf(e,t={}){let n=t.format||"json",r=t.output||`${e}.${n}`,s=t.limit;if(console.log(`-- Exporting data from table: ${e}`),console.log(`-- Format: ${n}`),console.log(`-- Output: ${r}`),s)console.log(`-- Limit: ${s} rows`);console.log();try{let o=ie().selectFrom(e);if(s)o=o.limit(s);let l=await o.execute();if(console.log(`-- Retrieved ${l.length} rows`),n==="json")Yn(r,JSON.stringify(l,null,2)),console.log(`-- \u2713 Exported to JSON: ${r}`);else if(n==="csv"){if(l.length===0){Yn(r,""),console.log(`-- \u2713 Exported to CSV: ${r} (empty)`);return}let a=Object.keys(l[0]),c=[a.join(",")];for(let u of l){let m=a.map((h)=>{let w=u[h];if(w===null||w===void 0)return"";let N=String(w);if(N.includes(",")||N.includes('"')||N.includes(`
143
+ `))return`"${N.replace(/"/g,'""')}"`;return N});c.push(m.join(","))}Yn(r,c.join(`
144
+ `)),console.log(`-- \u2713 Exported to CSV: ${r}`)}else if(n==="sql"){let a=[];for(let c of l){let u=Object.keys(c),m=u.map((h)=>{let w=c[h];if(w===null||w===void 0)return"NULL";if(typeof w==="number")return String(w);return`'${String(w).replace(/'/g,"''")}'`});a.push(`INSERT INTO ${e} (${u.join(", ")}) VALUES (${m.join(", ")});`)}Yn(r,a.join(`
145
+ `)),console.log(`-- \u2713 Exported to SQL: ${r}`)}}catch(i){throw console.error(`-- Failed to export data from ${e}:`,i),i}}async function Qf(e,t,n={}){if(!jf(t))throw console.error(`-- File not found: ${t}`),Error(`File not found: ${t}`);let r=n.format||(t.endsWith(".json")?"json":"csv"),s=n.truncate??!1;console.log(`-- Importing data into table: ${e}`),console.log(`-- Format: ${r}`),console.log(`-- File: ${t}`),console.log(`-- Truncate: ${s}`),console.log();try{let i=ie();if(s)await i.deleteFrom(e).execute(),console.log("-- Table truncated");let o=Wf(t,"utf8"),l=[];if(r==="json"){if(l=JSON.parse(o),!Array.isArray(l))throw TypeError("JSON file must contain an array of objects")}else if(r==="csv"){let u=o.split(`
146
+ `).filter((h)=>h.trim());if(u.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let m=u[0].split(",").map((h)=>h.trim());for(let h=1;h<u.length;h++){let w=u[h].split(",").map((R)=>R.trim()),N={};for(let R=0;R<m.length;R++){let y=w[R];if(y.startsWith('"')&&y.endsWith('"'))y=y.slice(1,-1).replace(/""/g,'"');if(y==="")y=null;else if(!Number.isNaN(Number(y)))y=Number(y);N[m[R]]=y}l.push(N)}}if(l.length===0){console.log("-- No data to import");return}let a=100,c=0;for(let u=0;u<l.length;u+=a){let m=l.slice(u,u+a);await i.insertInto(e).values(m).execute(),c+=m.length,console.log(`-- Imported ${c}/${l.length} rows...`)}console.log(`-- \u2713 Successfully imported ${l.length} rows`)}catch(i){throw console.error(`-- Failed to import data into ${e}:`,i),i}}async function Vf(e={}){let t=_.dialect||"postgres",n=e.output||`dump-${Date.now()}.sql`,r=e.tables?.split(",").map((s)=>s.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${t}`),console.log(`-- Output: ${n}`),r)console.log(`-- Tables: ${r.join(", ")}`);console.log();try{let s=ie(),i=[];if(t==="sqlite")i=(await s.unsafe(`
147
147
  SELECT name FROM sqlite_master
148
148
  WHERE type = 'table'
149
149
  AND name NOT LIKE 'sqlite_%'
@@ -160,8 +160,8 @@ Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{e
160
160
  WHERE table_schema = DATABASE()
161
161
  AND table_type = 'BASE TABLE'
162
162
  ORDER BY table_name
163
- `)).map((a)=>a.table_name);if(r)i=i.filter((l)=>r.includes(l));if(i.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${i.length} table(s)`);let o=[];o.push("-- Database dump"),o.push(`-- Generated at: ${new Date().toISOString()}`),o.push(`-- Dialect: ${t}`),o.push("");for(let l of i){console.log(`-- Dumping table: ${l}`);let a=await s.selectFrom(l).execute();o.push(`-- Table: ${l}`),o.push(`-- Rows: ${a.length}`),o.push("");for(let c of a){let u=Object.keys(c),m=u.map((h)=>{let w=c[h];if(w===null||w===void 0)return"NULL";if(typeof w==="number")return String(w);return`'${String(w).replace(/'/g,"''")}'`});o.push(`INSERT INTO ${l} (${u.join(", ")}) VALUES (${m.join(", ")});`)}o.push("")}Gn(n,o.join(`
164
- `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${n}`)}catch(s){throw console.error("-- Failed to dump database:",s),s}}Me();async function Ua(){let e=_.dialect||"postgres",t=_.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${e}`),console.log(`-- Database: ${t}`),console.log();try{let n=ie(),r=[],s=[];if(e==="postgres")s=(await n.unsafe(`
163
+ `)).map((a)=>a.table_name);if(r)i=i.filter((l)=>r.includes(l));if(i.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${i.length} table(s)`);let o=[];o.push("-- Database dump"),o.push(`-- Generated at: ${new Date().toISOString()}`),o.push(`-- Dialect: ${t}`),o.push("");for(let l of i){console.log(`-- Dumping table: ${l}`);let a=await s.selectFrom(l).execute();o.push(`-- Table: ${l}`),o.push(`-- Rows: ${a.length}`),o.push("");for(let c of a){let u=Object.keys(c),m=u.map((h)=>{let w=c[h];if(w===null||w===void 0)return"NULL";if(typeof w==="number")return String(w);return`'${String(w).replace(/'/g,"''")}'`});o.push(`INSERT INTO ${l} (${u.join(", ")}) VALUES (${m.join(", ")});`)}o.push("")}Yn(n,o.join(`
164
+ `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${n}`)}catch(s){throw console.error("-- Failed to dump database:",s),s}}Me();async function Qa(){let e=_.dialect||"postgres",t=_.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${e}`),console.log(`-- Database: ${t}`),console.log();try{let n=ie(),r=[],s=[];if(e==="postgres")s=(await n.unsafe(`
165
165
  SELECT table_name
166
166
  FROM information_schema.tables
167
167
  WHERE table_schema = 'public'
@@ -197,11 +197,11 @@ Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{e
197
197
  FROM information_schema.statistics
198
198
  WHERE table_name = ?
199
199
  AND table_schema = DATABASE()
200
- `,[o]);u=Number(h[0]?.count||0)}else if(e==="sqlite")c=(await n.unsafe(`PRAGMA table_info(${o})`)).length,u=(await n.unsafe(`PRAGMA index_list(${o})`)).length;r.push({name:o,rowCount:a,columns:c,indexes:u})}catch(l){console.error(`-- Error getting info for table ${o}:`,l)}let i=r.reduce((o,l)=>o+l.rowCount,0);if(console.log(`-- Total Tables: ${r.length}`),console.log(`-- Total Rows: ${i.toLocaleString()}`),console.log(),r.length>0){console.log("Tables:"),console.log();let o=Math.max(...r.map((c)=>c.name.length)),l=o+2,a="Table".padEnd(l)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(a),console.log("-".repeat(a.length));for(let c of r){let u=c.name.padEnd(o+2),m=c.rowCount.toLocaleString().padStart(12),h=(c.columns||0).toString().padStart(10),w=(c.indexes||0).toString().padStart(10);console.log(`${u}${m}${h}${w}`)}}else console.log("-- No tables found");return{dialect:e,database:t,tables:r,totalTables:r.length,totalRows:i}}catch(n){throw console.error("-- Failed to get database info:",n),n}}async function Vf(){return Ua()}Me();Kt();async function Qa(e={}){let t=Vr(e.dialect),n=e.aggressive||!1;if(e.verbose)console.log(`Optimizing ${t} database${n?" (aggressive mode)":""}...`);try{if(t==="postgres"){if(e.tables&&e.tables.length>0)for(let r of e.tables){if(e.verbose)console.log(`Analyzing table: ${r}`);if(n)await te`VACUUM FULL ANALYZE ${te(r)}`;else await te`VACUUM ANALYZE ${te(r)}`}else{if(e.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(n)await te`VACUUM FULL`,await te`ANALYZE`;else await te`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(ne(t)){if(e.tables&&e.tables.length>0)for(let r of e.tables){if(e.verbose)console.log(`Optimizing table: ${r}`);await te`OPTIMIZE TABLE ${te(r)}`,await te`ANALYZE TABLE ${te(r)}`}else{let r=zr(),s=await te`
200
+ `,[o]);u=Number(h[0]?.count||0)}else if(e==="sqlite")c=(await n.unsafe(`PRAGMA table_info(${o})`)).length,u=(await n.unsafe(`PRAGMA index_list(${o})`)).length;r.push({name:o,rowCount:a,columns:c,indexes:u})}catch(l){console.error(`-- Error getting info for table ${o}:`,l)}let i=r.reduce((o,l)=>o+l.rowCount,0);if(console.log(`-- Total Tables: ${r.length}`),console.log(`-- Total Rows: ${i.toLocaleString()}`),console.log(),r.length>0){console.log("Tables:"),console.log();let o=Math.max(...r.map((c)=>c.name.length)),l=o+2,a="Table".padEnd(l)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(a),console.log("-".repeat(a.length));for(let c of r){let u=c.name.padEnd(o+2),m=c.rowCount.toLocaleString().padStart(12),h=(c.columns||0).toString().padStart(10),w=(c.indexes||0).toString().padStart(10);console.log(`${u}${m}${h}${w}`)}}else console.log("-- No tables found");return{dialect:e,database:t,tables:r,totalTables:r.length,totalRows:i}}catch(n){throw console.error("-- Failed to get database info:",n),n}}async function Jf(){return Qa()}Me();Ft();async function Va(e={}){let t=Vr(e.dialect),n=e.aggressive||!1;if(e.verbose)console.log(`Optimizing ${t} database${n?" (aggressive mode)":""}...`);try{if(t==="postgres"){if(e.tables&&e.tables.length>0)for(let r of e.tables){if(e.verbose)console.log(`Analyzing table: ${r}`);if(n)await te`VACUUM FULL ANALYZE ${te(r)}`;else await te`VACUUM ANALYZE ${te(r)}`}else{if(e.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(n)await te`VACUUM FULL`,await te`ANALYZE`;else await te`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(ne(t)){if(e.tables&&e.tables.length>0)for(let r of e.tables){if(e.verbose)console.log(`Optimizing table: ${r}`);await te`OPTIMIZE TABLE ${te(r)}`,await te`ANALYZE TABLE ${te(r)}`}else{let r=zr(),s=await te`
201
201
  SELECT table_name
202
202
  FROM information_schema.tables
203
203
  WHERE table_schema = ${r}
204
- `;for(let i of s){let o=i.table_name||i.TABLE_NAME;if(e.verbose)console.log(`Optimizing table: ${o}`);await te`OPTIMIZE TABLE ${te(o)}`,await te`ANALYZE TABLE ${te(o)}`}}console.log("\u2713 MySQL optimization complete")}else if(t==="sqlite"){if(e.verbose)console.log("Running VACUUM on SQLite database...");if(await te`VACUUM`,e.tables&&e.tables.length>0)for(let r of e.tables){if(e.verbose)console.log(`Analyzing table: ${r}`);await te`ANALYZE ${te(r)}`}else await te`ANALYZE`;if(n){if(e.verbose)console.log("Running aggressive SQLite optimizations...");await te`PRAGMA optimize`,await te`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${t}`)}catch(r){throw console.error("Error optimizing database:",r.message),r}}Me();Kt();async function Va(e={}){let t=Vr(e.dialect);if(e.verbose)console.log(`Wiping all tables from ${t} database...`);try{let n=[];if(t==="postgres")n=(await te`
204
+ `;for(let i of s){let o=i.table_name||i.TABLE_NAME;if(e.verbose)console.log(`Optimizing table: ${o}`);await te`OPTIMIZE TABLE ${te(o)}`,await te`ANALYZE TABLE ${te(o)}`}}console.log("\u2713 MySQL optimization complete")}else if(t==="sqlite"){if(e.verbose)console.log("Running VACUUM on SQLite database...");if(await te`VACUUM`,e.tables&&e.tables.length>0)for(let r of e.tables){if(e.verbose)console.log(`Analyzing table: ${r}`);await te`ANALYZE ${te(r)}`}else await te`ANALYZE`;if(n){if(e.verbose)console.log("Running aggressive SQLite optimizations...");await te`PRAGMA optimize`,await te`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${t}`)}catch(r){throw console.error("Error optimizing database:",r.message),r}}Me();Ft();async function Ja(e={}){let t=Vr(e.dialect);if(e.verbose)console.log(`Wiping all tables from ${t} database...`);try{let n=[];if(t==="postgres")n=(await te`
205
205
  SELECT tablename
206
206
  FROM pg_tables
207
207
  WHERE schemaname = 'public'
@@ -214,7 +214,7 @@ Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{e
214
214
  FROM sqlite_master
215
215
  WHERE type = 'table'
216
216
  AND name NOT LIKE 'sqlite_%'
217
- `).map((s)=>s.name);if(n.length===0){console.log("No tables found to drop.");return}if(e.verbose)console.log(`Found ${n.length} tables: ${n.join(", ")}`);if(t==="postgres")for(let r of n){if(e.verbose)console.log(`Dropping table: ${r}`);await te`DROP TABLE IF EXISTS ${te(r)} CASCADE`}else if(ne(t)){await te`SET FOREIGN_KEY_CHECKS = 0`;for(let r of n){if(e.verbose)console.log(`Dropping table: ${r}`);await te`DROP TABLE IF EXISTS ${te(r)}`}await te`SET FOREIGN_KEY_CHECKS = 1`}else if(t==="sqlite"){await te`PRAGMA foreign_keys = OFF`;for(let r of n){if(e.verbose)console.log(`Dropping table: ${r}`);await te`DROP TABLE IF EXISTS ${te(r)}`}await te`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${n.length} tables`)}catch(n){throw console.error("Error wiping database:",n.message),n}}async function Jf(e){let r=await(ie().raw([e]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(r,null,2)),r}async function Hf(e,t={}){let n=ie(),r=t.params?JSON.parse(t.params):void 0,s=await n.file(e,r);return console.log(JSON.stringify(s)),s}Me();async function Ja(e,t={}){let n=_.dialect||"postgres",r=t.verbose??!0;if(r)console.log(`-- Inspecting table: ${e}`),console.log(`-- Dialect: ${n}`),console.log();try{let s=ie(),i=[],o=[],l=await s.unsafe(`SELECT COUNT(*) as count FROM ${e}`),a=Number(l[0]?.count||0);if(n==="postgres"){let c=await s.unsafe(`
217
+ `).map((s)=>s.name);if(n.length===0){console.log("No tables found to drop.");return}if(e.verbose)console.log(`Found ${n.length} tables: ${n.join(", ")}`);if(t==="postgres")for(let r of n){if(e.verbose)console.log(`Dropping table: ${r}`);await te`DROP TABLE IF EXISTS ${te(r)} CASCADE`}else if(ne(t)){await te`SET FOREIGN_KEY_CHECKS = 0`;for(let r of n){if(e.verbose)console.log(`Dropping table: ${r}`);await te`DROP TABLE IF EXISTS ${te(r)}`}await te`SET FOREIGN_KEY_CHECKS = 1`}else if(t==="sqlite"){await te`PRAGMA foreign_keys = OFF`;for(let r of n){if(e.verbose)console.log(`Dropping table: ${r}`);await te`DROP TABLE IF EXISTS ${te(r)}`}await te`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${n.length} tables`)}catch(n){throw console.error("Error wiping database:",n.message),n}}async function Hf(e){let r=await(ie().raw([e]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(r,null,2)),r}async function zf(e,t={}){let n=ie(),r=t.params?JSON.parse(t.params):void 0,s=await n.file(e,r);return console.log(JSON.stringify(s)),s}Me();async function Ha(e,t={}){let n=_.dialect||"postgres",r=t.verbose??!0;if(r)console.log(`-- Inspecting table: ${e}`),console.log(`-- Dialect: ${n}`),console.log();try{let s=ie(),i=[],o=[],l=await s.unsafe(`SELECT COUNT(*) as count FROM ${e}`),a=Number(l[0]?.count||0);if(n==="postgres"){let c=await s.unsafe(`
218
218
  SELECT
219
219
  c.column_name,
220
220
  c.data_type,
@@ -269,7 +269,7 @@ Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{e
269
269
  ORDER BY ORDINAL_POSITION
270
270
  `,[e]);for(let h of c)i.push({name:h.column_name,type:h.data_type,nullable:h.is_nullable==="YES",default:h.column_default,isPrimaryKey:h.column_key==="PRI",isForeignKey:h.column_key==="MUL"});let u=await s.unsafe(`
271
271
  SHOW INDEXES FROM ${e}
272
- `),m=new Map;for(let h of u){let w=h.Key_name;if(!m.has(w))m.set(w,{columns:[],unique:h.Non_unique===0});m.get(w).columns.push(h.Column_name)}for(let[h,w]of m)o.push({name:h,columns:w.columns,unique:w.unique})}else if(n==="sqlite"){let c=await s.unsafe(`PRAGMA table_info(${e})`);for(let m of c)i.push({name:m.name,type:m.type,nullable:m.notnull===0,default:m.dflt_value,isPrimaryKey:m.pk===1});let u=await s.unsafe(`PRAGMA index_list(${e})`);for(let m of u){let h=await s.unsafe(`PRAGMA index_info(${m.name})`);o.push({name:m.name,columns:h.map((w)=>w.name),unique:m.unique===1})}}if(r){console.log(`Table: ${e}`),console.log(`Rows: ${a.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let c=Math.max(...i.map((N)=>N.name.length),10),u=Math.max(...i.map((N)=>N.type.length),10),m=c+2,h=u+2,w=`${"Name".padEnd(m)+"Type".padEnd(h)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(w),console.log("-".repeat(w.length));for(let N of i){let R=N.name.padEnd(m),y=N.type.padEnd(h),b=(N.nullable?"YES":"NO").padEnd(10),g=String(N.default||"").padEnd(20),p=[N.isPrimaryKey?"PK":"",N.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${R}${y}${b}${g}${p}`)}if(console.log(),o.length>0){console.log("Indexes:"),console.log();for(let N of o){let R=N.unique?" (UNIQUE)":"";console.log(` - ${N.name}${R}: [${N.columns.join(", ")}]`)}console.log()}}return{tableName:e,rowCount:a,columns:i,indexes:o}}catch(s){throw console.error(`-- Failed to inspect table ${e}:`,s),s}}async function zf(e,t={}){return Ja(e,t)}async function Gf(e,t={}){let n=await mt({modelsDir:e}),r=as(n);return console.log(JSON.stringify(r,null,2)),{models:n,schema:r}}Me();function Ha(e){let t=e.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(t))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(t))return"number";if(/timestamp|datetime|date|time/.test(t))return"datetime";if(/json/.test(t))return"json";return"string"}function Yf(e){if(/ies$/i.test(e))return e.replace(/ies$/i,"y");if(/ses$/i.test(e))return e.replace(/es$/i,"");if(/s$/i.test(e)&&!/ss$/i.test(e))return e.replace(/s$/i,"");return e}function Xf(e){return e.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function mi(e){return Xf(Yf(e))}async function za(e,t){if(t==="postgres")return(await e.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((s)=>s.table_name);if(ne(t))return(await e.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((s)=>s.table_name??s.TABLE_NAME);return(await e.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((r)=>r.name)}async function Zf(e,t,n){if(t==="sqlite")return(await e.unsafe(`PRAGMA table_info(${n})`)).map((i)=>({name:i.name,sqlType:String(i.type||""),nullable:Number(i.notnull)===0,isPrimaryKey:Number(i.pk)>0}));if(t==="postgres")return(await e.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
272
+ `),m=new Map;for(let h of u){let w=h.Key_name;if(!m.has(w))m.set(w,{columns:[],unique:h.Non_unique===0});m.get(w).columns.push(h.Column_name)}for(let[h,w]of m)o.push({name:h,columns:w.columns,unique:w.unique})}else if(n==="sqlite"){let c=await s.unsafe(`PRAGMA table_info(${e})`);for(let m of c)i.push({name:m.name,type:m.type,nullable:m.notnull===0,default:m.dflt_value,isPrimaryKey:m.pk===1});let u=await s.unsafe(`PRAGMA index_list(${e})`);for(let m of u){let h=await s.unsafe(`PRAGMA index_info(${m.name})`);o.push({name:m.name,columns:h.map((w)=>w.name),unique:m.unique===1})}}if(r){console.log(`Table: ${e}`),console.log(`Rows: ${a.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let c=Math.max(...i.map((N)=>N.name.length),10),u=Math.max(...i.map((N)=>N.type.length),10),m=c+2,h=u+2,w=`${"Name".padEnd(m)+"Type".padEnd(h)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(w),console.log("-".repeat(w.length));for(let N of i){let R=N.name.padEnd(m),y=N.type.padEnd(h),b=(N.nullable?"YES":"NO").padEnd(10),g=String(N.default||"").padEnd(20),p=[N.isPrimaryKey?"PK":"",N.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${R}${y}${b}${g}${p}`)}if(console.log(),o.length>0){console.log("Indexes:"),console.log();for(let N of o){let R=N.unique?" (UNIQUE)":"";console.log(` - ${N.name}${R}: [${N.columns.join(", ")}]`)}console.log()}}return{tableName:e,rowCount:a,columns:i,indexes:o}}catch(s){throw console.error(`-- Failed to inspect table ${e}:`,s),s}}async function Gf(e,t={}){return Ha(e,t)}async function Yf(e,t={}){let n=await mt({modelsDir:e}),r=as(n);return console.log(JSON.stringify(r,null,2)),{models:n,schema:r}}Me();function za(e){let t=e.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(t))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(t))return"number";if(/timestamp|datetime|date|time/.test(t))return"datetime";if(/json/.test(t))return"json";return"string"}function Xf(e){if(/ies$/i.test(e))return e.replace(/ies$/i,"y");if(/ses$/i.test(e))return e.replace(/es$/i,"");if(/s$/i.test(e)&&!/ss$/i.test(e))return e.replace(/s$/i,"");return e}function Zf(e){return e.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function hi(e){return Zf(Xf(e))}async function Ga(e,t){if(t==="postgres")return(await e.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((s)=>s.table_name);if(ne(t))return(await e.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((s)=>s.table_name??s.TABLE_NAME);return(await e.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((r)=>r.name)}async function em(e,t,n){if(t==="sqlite")return(await e.unsafe(`PRAGMA table_info(${n})`)).map((i)=>({name:i.name,sqlType:String(i.type||""),nullable:Number(i.notnull)===0,isPrimaryKey:Number(i.pk)>0}));if(t==="postgres")return(await e.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
273
273
  (SELECT COUNT(*) FROM information_schema.table_constraints tc
274
274
  JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
275
275
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
@@ -278,7 +278,7 @@ Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{e
278
278
  ORDER BY c.ordinal_position`,[n])).map((i)=>({name:i.column_name,sqlType:String(i.data_type||""),nullable:String(i.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(i.is_pk)>0}));return(await e.unsafe(`SELECT column_name, data_type, is_nullable, column_key
279
279
  FROM information_schema.columns
280
280
  WHERE table_name = ? AND table_schema = DATABASE()
281
- ORDER BY ordinal_position`,[n])).map((s)=>({name:s.column_name??s.COLUMN_NAME,sqlType:String(s.data_type??s.DATA_TYPE??""),nullable:String(s.is_nullable??s.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(s.column_key??s.COLUMN_KEY).toUpperCase()==="PRI"}))}function Ga(e,t){let n=mi(e),r=t.find((i)=>i.isPrimaryKey)?.name??"id",s=t.map((i)=>{let o=[`type: '${Ha(i.sqlType)}'`];if(!i.nullable&&!i.isPrimaryKey)o.push("required: true");return` ${i.name}: { ${o.join(", ")} },`}).join(`
281
+ ORDER BY ordinal_position`,[n])).map((s)=>({name:s.column_name??s.COLUMN_NAME,sqlType:String(s.data_type??s.DATA_TYPE??""),nullable:String(s.is_nullable??s.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(s.column_key??s.COLUMN_KEY).toUpperCase()==="PRI"}))}function Ya(e,t){let n=hi(e),r=t.find((i)=>i.isPrimaryKey)?.name??"id",s=t.map((i)=>{let o=[`type: '${za(i.sqlType)}'`];if(!i.nullable&&!i.isPrimaryKey)o.push("required: true");return` ${i.name}: { ${o.join(", ")} },`}).join(`
282
282
  `);return`export const ${n} = defineModel({
283
283
  name: '${n}',
284
284
  table: '${e}',
@@ -287,12 +287,12 @@ Goodbye!`),os.exit(0)}),t.prompt()}async function Ff(){return Wa()}Me();import{e
287
287
  ${s}
288
288
  },
289
289
  })
290
- `}async function gi(e={}){let t=_.dialect||"postgres",n=ie(),r=e.tables?.length?e.tables:await za(n,t),s=[];for(let i of r){let o=await Zf(n,t,i);if(!o.length)continue;s.push({table:i,modelName:mi(i),primaryKey:o.find((l)=>l.isPrimaryKey)?.name??"id",columns:o,source:Ga(i,o)})}return s}function yi(e,t,n){if(n?.enumValues&&n.enumValues.length>0)return"enum";let r=String(e||"").toLowerCase().trim(),s=r.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(ne(t)&&/^tinyint\(1\)/.test(r))return"boolean";if(/^bool/.test(s))return"boolean";if(s==="int8"||s==="bigint"||s==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(s))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(s)){let i=r.match(/\((\d+)\)/),o=i?Number(i[1]):void 0;if(ne(t))return"string";return o!==void 0&&o>255?"text":"string"}if(/text|clob/.test(s))return"text";if(s==="float8"||/^double/.test(s))return"double";if(/^(?:real|float4|float)/.test(s))return"float";if(/^(?:numeric|decimal|money)/.test(s))return"decimal";if(s==="date")return"date";if(s==="timestamptz"||/\bwith time zone\b/.test(r))return"timestamptz";if(/^(?:timestamp|datetime)/.test(s))return"datetime";if(/^time/.test(s))return"string";if(/json/.test(s))return"json";if(/^enum/.test(s))return"enum";return"string"}function em(e,t,n){return yi(String(t||e||""),"mysql",{enumValues:n})}function tm(e){let t=String(e||"").trim().match(/^varchar\((\d+)\)/i);if(!t)return;let n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}function En(e){let t=String(e??"").toLowerCase().trim();if(t==="cascade"||t==="restrict"||t==="set null")return t;return}async function nm(e,t){let n=await e.unsafe(`PRAGMA table_info(${JSON.stringify(t)})`),r=await e.unsafe(`PRAGMA index_list(${JSON.stringify(t)})`),s=await e.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(t)})`),i=await e.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[t]),o=String(i?.[0]?.sql??""),l=new Map;for(let m of s)l.set(String(m.from),{table:String(m.table),column:String(m.to??"id"),onDelete:En(m.on_delete),onUpdate:En(m.on_update)});let a=[],c=new Set;for(let m of r){let h=String(m.origin??""),w=String(m.name??"");if(h==="pk"||w.startsWith("sqlite_autoindex_"))continue;let R=(await e.unsafe(`PRAGMA index_info(${JSON.stringify(w)})`)).map((b)=>String(b.name)).filter(Boolean);if(R.length===0)continue;let y=Number(m.unique)===1;if(y&&R.length===1)c.add(R[0]);a.push({name:w,columns:R,type:y?"unique":"index"})}let u=n.map((m)=>{let h=String(m.name),w=rm(o,h),N=Number(m.pk)>0,R=m.dflt_value,y=R!==null&&R!==void 0;return{name:h,type:yi(String(m.type??""),"sqlite",{enumValues:w}),isPrimaryKey:N,isUnique:c.has(h),isNullable:N?!1:Number(m.notnull)===0,hasDefault:y,defaultValue:y?hi(R):void 0,enumValues:w,references:l.get(h)}});return{table:t,columns:u,indexes:a}}function rm(e,t){if(!e)return;let n=new RegExp(`(?:"${t}"|\`${t}\`|\\b${t}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),r=e.match(n);if(!r)return;let s=r[1].split(",").map((i)=>i.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((i)=>i.length>0);return s.length>0?s:void 0}function hi(e){if(typeof e==="number"||typeof e==="boolean")return e;return String(e)}async function Ya(e){let t=await e.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
290
+ `}async function pi(e={}){let t=_.dialect||"postgres",n=ie(),r=e.tables?.length?e.tables:await Ga(n,t),s=[];for(let i of r){let o=await em(n,t,i);if(!o.length)continue;s.push({table:i,modelName:hi(i),primaryKey:o.find((l)=>l.isPrimaryKey)?.name??"id",columns:o,source:Ya(i,o)})}return s}function bi(e,t,n){if(n?.enumValues&&n.enumValues.length>0)return"enum";let r=String(e||"").toLowerCase().trim(),s=r.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(ne(t)&&/^tinyint\(1\)/.test(r))return"boolean";if(/^bool/.test(s))return"boolean";if(s==="int8"||s==="bigint"||s==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(s))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(s)){let i=r.match(/\((\d+)\)/),o=i?Number(i[1]):void 0;if(ne(t))return"string";return o!==void 0&&o>255?"text":"string"}if(/text|clob/.test(s))return"text";if(s==="float8"||/^double/.test(s))return"double";if(/^(?:real|float4|float)/.test(s))return"float";if(/^(?:numeric|decimal|money)/.test(s))return"decimal";if(s==="date")return"date";if(s==="timestamptz"||/\bwith time zone\b/.test(r))return"timestamptz";if(/^(?:timestamp|datetime)/.test(s))return"datetime";if(/^time/.test(s))return"string";if(/json/.test(s))return"json";if(/^enum/.test(s))return"enum";return"string"}function tm(e,t,n){return bi(String(t||e||""),"mysql",{enumValues:n})}function nm(e){let t=String(e||"").trim().match(/^varchar\((\d+)\)/i);if(!t)return;let n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}function En(e){let t=String(e??"").toLowerCase().trim();if(t==="cascade"||t==="restrict"||t==="set null")return t;return}async function rm(e,t){let n=await e.unsafe(`PRAGMA table_info(${JSON.stringify(t)})`),r=await e.unsafe(`PRAGMA index_list(${JSON.stringify(t)})`),s=await e.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(t)})`),i=await e.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[t]),o=String(i?.[0]?.sql??""),l=new Map;for(let m of s)l.set(String(m.from),{table:String(m.table),column:String(m.to??"id"),onDelete:En(m.on_delete),onUpdate:En(m.on_update)});let a=[],c=new Set;for(let m of r){let h=String(m.origin??""),w=String(m.name??"");if(h==="pk"||w.startsWith("sqlite_autoindex_"))continue;let R=(await e.unsafe(`PRAGMA index_info(${JSON.stringify(w)})`)).map((b)=>String(b.name)).filter(Boolean);if(R.length===0)continue;let y=Number(m.unique)===1;if(y&&R.length===1)c.add(R[0]);a.push({name:w,columns:R,type:y?"unique":"index"})}let u=n.map((m)=>{let h=String(m.name),w=sm(o,h),N=Number(m.pk)>0,R=m.dflt_value,y=R!==null&&R!==void 0;return{name:h,type:bi(String(m.type??""),"sqlite",{enumValues:w}),isPrimaryKey:N,isUnique:c.has(h),isNullable:N?!1:Number(m.notnull)===0,hasDefault:y,defaultValue:y?Ti(R):void 0,enumValues:w,references:l.get(h)}});return{table:t,columns:u,indexes:a}}function sm(e,t){if(!e)return;let n=new RegExp(`(?:"${t}"|\`${t}\`|\\b${t}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),r=e.match(n);if(!r)return;let s=r[1].split(",").map((i)=>i.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((i)=>i.length>0);return s.length>0?s:void 0}function Ti(e){if(typeof e==="number"||typeof e==="boolean")return e;return String(e)}async function Xa(e){let t=await e.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
291
291
  FROM pg_type t
292
292
  JOIN pg_enum e ON e.enumtypid = t.oid
293
293
  JOIN pg_namespace n ON n.oid = t.typnamespace
294
294
  WHERE n.nspname = 'public'
295
- ORDER BY t.typname, e.enumsortorder`),n=new Map;for(let r of t){let s=String(r.type_name),i=n.get(s);if(i)i.push(String(r.label));else n.set(s,[String(r.label)])}return n}function sm(e,t,n){let r=n.get(t),s=yi(String(e||t||""),"postgres",{enumValues:r});return r?{type:s,enumValues:r,enumTypeName:t}:{type:s}}async function im(e,t,n){let r=n??await Ya(e),s=await e.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
295
+ ORDER BY t.typname, e.enumsortorder`),n=new Map;for(let r of t){let s=String(r.type_name),i=n.get(s);if(i)i.push(String(r.label));else n.set(s,[String(r.label)])}return n}function im(e,t,n){let r=n.get(t),s=bi(String(e||t||""),"postgres",{enumValues:r});return r?{type:s,enumValues:r,enumTypeName:t}:{type:s}}async function om(e,t,n){let r=n??await Xa(e),s=await e.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
296
296
  (SELECT COUNT(*) FROM information_schema.table_constraints tc
297
297
  JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
298
298
  WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
@@ -312,7 +312,7 @@ ${s}
312
312
  JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
313
313
  JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
314
314
  JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
315
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[t]),l=new Map,a=new Map;for(let h of o){let w=String(h.constraint_name);a.set(w,(a.get(w)??0)+1)}for(let h of o){let w=String(h.column_name),N=l.get(w),R=String(h.constraint_name),y=a.get(R)===1?[...new Set([...N?.constraintNames??[],R])]:N?.constraintNames;l.set(w,N?{...N,constraintNames:y}:{table:String(h.ref_table),column:String(h.ref_column??"id"),onDelete:En(h.delete_rule),onUpdate:En(h.update_rule),constraintNames:y})}let{indexes:c,uniqueColumns:u}=Xa(t,i.map((h)=>({indexName:String(h.index_name),isUnique:h.is_unique===!0||h.is_unique==="t",isPrimary:h.is_primary===!0||h.is_primary==="t",column:String(h.column_name),where:h.where_clause?String(h.where_clause):void 0}))),m=s.map((h)=>{let w=String(h.column_name),N=Number(h.is_pk)>0,R=h.column_default==null?null:String(h.column_default),y=R!=null&&/nextval\(/i.test(R),b=R!=null&&!y;return{name:w,...sm(String(h.data_type??""),h.udt_name==null?"":String(h.udt_name),r),isPrimaryKey:N,isUnique:u.has(w),isNullable:N?!1:String(h.is_nullable).toUpperCase()==="YES",hasDefault:b,defaultValue:b?hi(R):void 0,references:l.get(w)}});return{table:t,columns:m,indexes:c}}async function om(e,t){let n=await e.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
315
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[t]),l=new Map,a=new Map;for(let h of o){let w=String(h.constraint_name);a.set(w,(a.get(w)??0)+1)}for(let h of o){let w=String(h.column_name),N=l.get(w),R=String(h.constraint_name),y=a.get(R)===1?[...new Set([...N?.constraintNames??[],R])]:N?.constraintNames;l.set(w,N?{...N,constraintNames:y}:{table:String(h.ref_table),column:String(h.ref_column??"id"),onDelete:En(h.delete_rule),onUpdate:En(h.update_rule),constraintNames:y})}let{indexes:c,uniqueColumns:u}=Za(t,i.map((h)=>({indexName:String(h.index_name),isUnique:h.is_unique===!0||h.is_unique==="t",isPrimary:h.is_primary===!0||h.is_primary==="t",column:String(h.column_name),where:h.where_clause?String(h.where_clause):void 0}))),m=s.map((h)=>{let w=String(h.column_name),N=Number(h.is_pk)>0,R=h.column_default==null?null:String(h.column_default),y=R!=null&&/nextval\(/i.test(R),b=R!=null&&!y;return{name:w,...im(String(h.data_type??""),h.udt_name==null?"":String(h.udt_name),r),isPrimaryKey:N,isUnique:u.has(w),isNullable:N?!1:String(h.is_nullable).toUpperCase()==="YES",hasDefault:b,defaultValue:b?Ti(R):void 0,references:l.get(w)}});return{table:t,columns:m,indexes:c}}async function am(e,t){let n=await e.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
316
316
  FROM information_schema.columns
317
317
  WHERE table_name = ? AND table_schema = DATABASE()
318
318
  ORDER BY ordinal_position`,[t]),r=await e.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
@@ -323,7 +323,7 @@ ${s}
323
323
  FROM information_schema.key_column_usage kcu
324
324
  JOIN information_schema.referential_constraints rc
325
325
  ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
326
- WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[t]),i=new Map,o=new Map;for(let u of s){let m=String(u.constraint_name??u.CONSTRAINT_NAME);o.set(m,(o.get(m)??0)+1)}for(let u of s){let m=String(u.column_name??u.COLUMN_NAME),h=i.get(m),w=String(u.constraint_name??u.CONSTRAINT_NAME),N=o.get(w)===1?[...new Set([...h?.constraintNames??[],w])]:h?.constraintNames;i.set(m,h?{...h,constraintNames:N}:{table:String(u.ref_table??u.REF_TABLE),column:String(u.ref_column??u.REF_COLUMN??"id"),onDelete:En(u.delete_rule??u.DELETE_RULE),onUpdate:En(u.update_rule??u.UPDATE_RULE),constraintNames:N})}let{indexes:l,uniqueColumns:a}=Xa(t,r.map((u)=>({indexName:String(u.index_name??u.INDEX_NAME),isUnique:Number(u.non_unique??u.NON_UNIQUE)===0,isPrimary:String(u.index_name??u.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(u.column_name??u.COLUMN_NAME)}))),c=n.map((u)=>{let m=String(u.column_name??u.COLUMN_NAME),h=String(u.column_type??u.COLUMN_TYPE??""),w=am(h),R=String(u.column_key??u.COLUMN_KEY??"").toUpperCase()==="PRI",y=u.column_default??u.COLUMN_DEFAULT,b=y!=null;return{name:m,type:em(u.data_type??u.DATA_TYPE,h,w),isPrimaryKey:R,isUnique:a.has(m),isNullable:R?!1:String(u.is_nullable??u.IS_NULLABLE).toUpperCase()==="YES",hasDefault:b,defaultValue:b?hi(y):void 0,enumValues:w,maxLength:tm(h),references:i.get(m)}});return{table:t,columns:c,indexes:l}}function am(e){let t=e.match(/^enum\((.*)\)$/i);if(!t)return;return t[1].split(",").map((n)=>n.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((n)=>n.length>0)}function Xa(e,t){let n=new Map;for(let i of t){if(i.isPrimary)continue;let o=n.get(i.indexName)??{isUnique:i.isUnique,isPrimary:i.isPrimary,columns:[],where:i.where};o.columns.push(i.column),n.set(i.indexName,o)}let r=[],s=new Set;for(let[i,o]of n){if(o.columns.length===0)continue;if(o.isUnique&&o.columns.length===1)s.add(o.columns[0]);r.push({name:i,columns:o.columns,type:o.isUnique?"unique":"index",where:o.where})}return{indexes:r,uniqueColumns:s}}async function Za(e,t={}){let n=e||_.dialect||"postgres",r=ie(),i=((t.tables?.length)?t.tables:await za(r,n)).filter((a)=>a!=="migrations"),o=n==="postgres"?await Ya(r):void 0,l=[];for(let a of i){let c;if(n==="sqlite")c=await nm(r,a);else if(n==="postgres")c=await im(r,a,o);else c=await om(r,a);if(c.columns.length>0)l.push(c)}return{dialect:n,tables:l}}import{existsSync as pi,mkdirSync as lm,writeFileSync as cm}from"fs";import{dirname as el,join as bi}from"path";import tl from"process";function um(e){let t=e;while(t!==el(t)){if(pi(bi(t,"package.json")))return t;t=el(t)}return tl.cwd()}async function dm(e,t={}){let n=um(tl.cwd()),r=t.dir||bi(n,"app/Models");if(!pi(r))lm(r,{recursive:!0}),console.log(`-- Created models directory: ${r}`);let s=e.charAt(0).toUpperCase()+e.slice(1),i=t.table||`${e.toLowerCase()}s`,o=`${s}.ts`,l=bi(r,o);if(pi(l))throw console.error(`-- Model already exists: ${l}`),Error(`Model already exists: ${l}`);let c=t.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
326
+ WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[t]),i=new Map,o=new Map;for(let u of s){let m=String(u.constraint_name??u.CONSTRAINT_NAME);o.set(m,(o.get(m)??0)+1)}for(let u of s){let m=String(u.column_name??u.COLUMN_NAME),h=i.get(m),w=String(u.constraint_name??u.CONSTRAINT_NAME),N=o.get(w)===1?[...new Set([...h?.constraintNames??[],w])]:h?.constraintNames;i.set(m,h?{...h,constraintNames:N}:{table:String(u.ref_table??u.REF_TABLE),column:String(u.ref_column??u.REF_COLUMN??"id"),onDelete:En(u.delete_rule??u.DELETE_RULE),onUpdate:En(u.update_rule??u.UPDATE_RULE),constraintNames:N})}let{indexes:l,uniqueColumns:a}=Za(t,r.map((u)=>({indexName:String(u.index_name??u.INDEX_NAME),isUnique:Number(u.non_unique??u.NON_UNIQUE)===0,isPrimary:String(u.index_name??u.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(u.column_name??u.COLUMN_NAME)}))),c=n.map((u)=>{let m=String(u.column_name??u.COLUMN_NAME),h=String(u.column_type??u.COLUMN_TYPE??""),w=lm(h),R=String(u.column_key??u.COLUMN_KEY??"").toUpperCase()==="PRI",y=u.column_default??u.COLUMN_DEFAULT,b=y!=null;return{name:m,type:tm(u.data_type??u.DATA_TYPE,h,w),isPrimaryKey:R,isUnique:a.has(m),isNullable:R?!1:String(u.is_nullable??u.IS_NULLABLE).toUpperCase()==="YES",hasDefault:b,defaultValue:b?Ti(y):void 0,enumValues:w,maxLength:nm(h),references:i.get(m)}});return{table:t,columns:c,indexes:l}}function lm(e){let t=e.match(/^enum\((.*)\)$/i);if(!t)return;return t[1].split(",").map((n)=>n.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((n)=>n.length>0)}function Za(e,t){let n=new Map;for(let i of t){if(i.isPrimary)continue;let o=n.get(i.indexName)??{isUnique:i.isUnique,isPrimary:i.isPrimary,columns:[],where:i.where};o.columns.push(i.column),n.set(i.indexName,o)}let r=[],s=new Set;for(let[i,o]of n){if(o.columns.length===0)continue;if(o.isUnique&&o.columns.length===1)s.add(o.columns[0]);r.push({name:i,columns:o.columns,type:o.isUnique?"unique":"index",where:o.where})}return{indexes:r,uniqueColumns:s}}async function el(e,t={}){let n=e||_.dialect||"postgres",r=ie(),i=((t.tables?.length)?t.tables:await Ga(r,n)).filter((a)=>a!=="migrations"),o=n==="postgres"?await Xa(r):void 0,l=[];for(let a of i){let c;if(n==="sqlite")c=await rm(r,a);else if(n==="postgres")c=await om(r,a,o);else c=await am(r,a);if(c.columns.length>0)l.push(c)}return{dialect:n,tables:l}}import{existsSync as wi,mkdirSync as cm,writeFileSync as um}from"fs";import{dirname as tl,join as Di}from"path";import nl from"process";function dm(e){let t=e;while(t!==tl(t)){if(wi(Di(t,"package.json")))return t;t=tl(t)}return nl.cwd()}async function fm(e,t={}){let n=dm(nl.cwd()),r=t.dir||Di(n,"app/Models");if(!wi(r))cm(r,{recursive:!0}),console.log(`-- Created models directory: ${r}`);let s=e.charAt(0).toUpperCase()+e.slice(1),i=t.table||`${e.toLowerCase()}s`,o=`${s}.ts`,l=Di(r,o);if(wi(l))throw console.error(`-- Model already exists: ${l}`),Error(`Model already exists: ${l}`);let c=t.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
327
327
  updated_at: { validation: { rule: v.date() } },`:"",u=`import { v } from '@stacksjs/ts-validation'
328
328
  import { defineModel } from 'bun-query-builder'
329
329
 
@@ -343,22 +343,22 @@ ${c}
343
343
  })
344
344
 
345
345
  export default model
346
- `;cm(l,u),console.log(`-- \u2713 Created model: ${l}`),console.log(`-- Table: ${i}`)}async function fm(e,t={}){return Ti(e,t)}Me();import{existsSync as il,readFileSync as ym,unlinkSync as hm}from"fs";import{join as pm}from"path";import{existsSync as mm}from"fs";import{dirname as nl,isAbsolute as gm,join as sl}from"path";import rl from"process";function wi(e=rl.cwd()){let t=e;while(t!==nl(t)){if(mm(sl(t,"package.json")))return t;t=nl(t)}return rl.cwd()}function At(e,t="database/migrations"){let n=t||"database/migrations";return gm(n)?n:sl(e??wi(),n)}function bm(e){let t=[],n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r){if(n+=i,i===r)if(e[s+1]===r)n+=e[s+1],s++;else r=null;continue}if(i==="'"||i==='"'||i==="`"){r=i,n+=i;continue}if(i==="-"&&e[s+1]==="-"){let o=e.indexOf(`
347
- `,s);s=o===-1?e.length:o;continue}if(i==="/"&&e[s+1]==="*"){let o=e.indexOf("*/",s+2);s=o===-1?e.length:o+1;continue}if(i===";"){if(n.trim())t.push(n.trim());n="";continue}n+=i}if(n.trim())t.push(n.trim());return t}function Tm(e,t=_.dialect){let n=(i)=>ne(t)?`\`${i}\``:`"${i}"`,r=[],s=[];for(let i of bm(e)){let o;if(o=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(i))r.push(`DROP TABLE IF EXISTS ${n(o[1])}`);else if(o=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(i))if(t==="sqlite")s.push(i);else if(ne(t)&&/\bFOREIGN\s+KEY\b/i.test(o[3]??""))r.push(`ALTER TABLE ${n(o[1])} DROP FOREIGN KEY ${n(o[2])}`);else r.push(`ALTER TABLE ${n(o[1])} DROP CONSTRAINT ${n(o[2])}`);else if(o=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(i)){let l=o[2]??o[3]??o[4];if(o[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(o[4]))s.push(i);else r.push(`ALTER TABLE ${n(o[1])} DROP COLUMN ${n(l)}`)}else if(o=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(i))r.push(ne(t)&&o[2]?`DROP INDEX ${n(o[1])} ON ${n(o[2])}`:`DROP INDEX IF EXISTS ${n(o[1])}`);else s.push(i)}return{down:r.reverse(),skipped:s}}async function wm(e={}){let t=e.steps||1,n=e.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${t}`),console.log();try{let r=ie(),s=[];try{s=await r.unsafe(`
346
+ `;um(l,u),console.log(`-- \u2713 Created model: ${l}`),console.log(`-- Table: ${i}`)}async function mm(e,t={}){return Si(e,t)}Me();import{existsSync as ol,readFileSync as hm,unlinkSync as pm}from"fs";import{join as bm}from"path";import{existsSync as gm}from"fs";import{dirname as rl,isAbsolute as ym,join as il}from"path";import sl from"process";function $i(e=sl.cwd()){let t=e;while(t!==rl(t)){if(gm(il(t,"package.json")))return t;t=rl(t)}return sl.cwd()}function Nt(e,t="database/migrations"){let n=t||"database/migrations";return ym(n)?n:il(e??$i(),n)}function Tm(e){let t=[],n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r){if(n+=i,i===r)if(e[s+1]===r)n+=e[s+1],s++;else r=null;continue}if(i==="'"||i==='"'||i==="`"){r=i,n+=i;continue}if(i==="-"&&e[s+1]==="-"){let o=e.indexOf(`
347
+ `,s);s=o===-1?e.length:o;continue}if(i==="/"&&e[s+1]==="*"){let o=e.indexOf("*/",s+2);s=o===-1?e.length:o+1;continue}if(i===";"){if(n.trim())t.push(n.trim());n="";continue}n+=i}if(n.trim())t.push(n.trim());return t}function wm(e,t=_.dialect){let n=(i)=>ne(t)?`\`${i}\``:`"${i}"`,r=[],s=[];for(let i of Tm(e)){let o;if(o=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(i))r.push(`DROP TABLE IF EXISTS ${n(o[1])}`);else if(o=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(i))if(t==="sqlite")s.push(i);else if(ne(t)&&/\bFOREIGN\s+KEY\b/i.test(o[3]??""))r.push(`ALTER TABLE ${n(o[1])} DROP FOREIGN KEY ${n(o[2])}`);else r.push(`ALTER TABLE ${n(o[1])} DROP CONSTRAINT ${n(o[2])}`);else if(o=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(i)){let l=o[2]??o[3]??o[4];if(o[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(o[4]))s.push(i);else r.push(`ALTER TABLE ${n(o[1])} DROP COLUMN ${n(l)}`)}else if(o=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(i))r.push(ne(t)&&o[2]?`DROP INDEX ${n(o[1])} ON ${n(o[2])}`:`DROP INDEX IF EXISTS ${n(o[1])}`);else s.push(i)}return{down:r.reverse(),skipped:s}}async function Dm(e={}){let t=e.steps||1,n=e.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${t}`),console.log();try{let r=ie(),s=[];try{s=await r.unsafe(`
348
348
  SELECT migration, executed_at
349
349
  FROM migrations
350
350
  ORDER BY executed_at DESC, migration DESC
351
- `)}catch(a){console.log("-- Migrations table not found. Nothing to rollback.",a);return}if(s.length===0){console.log("-- No migrations to rollback");return}let i=s.slice(0,t);console.log(`-- Found ${s.length} executed migrations`),console.log(`-- Rolling back ${i.length} migration(s):`),console.log();for(let a of i)console.log(` - ${a.migration}`);console.log();let o=At(void 0,_.migrationDir),l=!1;for(let a of i)try{let c=pm(o,a.migration);if(n&&il(c)){let m=ym(c,"utf8"),{down:h,skipped:w}=Tm(m);for(let N of h)await r.unsafe(N),console.log(`-- \u21A9 ${N}`),l=!0;if(w.length>0)console.log(`-- \u26A0\uFE0F ${w.length} statement(s) in ${a.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let u=`DELETE FROM migrations WHERE migration = ${Z(1)}`;if(await r.unsafe(u,[a.migration]),console.log(`-- \u2713 Removed migration record: ${a.migration}`),e.deleteFiles&&il(c))hm(c),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${a.migration}`)}catch(c){throw console.error(`-- \u2717 Failed to rollback migration ${a.migration}:`,c),c}if(console.log(),n)console.log(l?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(r){throw console.error("-- Rollback failed:",r),r}}Me();import{existsSync as Dm,readdirSync as Sm}from"fs";async function ol(){let e=_.dialect||"postgres",t=Tt(e),n=At(void 0,_.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${e}`),console.log(`-- SQL directory: ${n}`),console.log(),!Dm(n))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let s=Sm(n).filter((i)=>i.endsWith(".sql")).sort();if(s.length===0)return console.log("-- No migration files found"),[];try{let i=ie(),o=[];try{o=await i.unsafe(t.getExecutedMigrationsQuery())}catch(m){console.log("-- Migrations table not found. All migrations are pending.",m),console.log()}let l=new Map(o.map((m)=>[m.migration,m.executed_at])),a=s.map((m)=>({file:m,status:l.has(m)?"executed":"pending",executedAt:l.get(m)})),c=a.filter((m)=>m.status==="executed"),u=a.filter((m)=>m.status==="pending");if(console.log(`-- Total migrations: ${s.length}`),console.log(`-- Executed: ${c.length}`),console.log(`-- Pending: ${u.length}`),console.log(),c.length>0){console.log("\u2713 Executed Migrations:");for(let m of c)console.log(` - ${m.file} ${m.executedAt?`(${new Date(m.executedAt).toLocaleString()})`:""}`);console.log()}if(u.length>0){console.log("\u25CB Pending Migrations:");for(let m of u)console.log(` - ${m.file}`);console.log()}return a}catch(i){throw console.error("-- Failed to get migration status:",i),i}}async function $m(){return ol()}import{readdirSync as Em}from"fs";import{extname as Di,join as al}from"path";import xm from"process";async function ll(e,t={}){let n=t.dir||al(xm.cwd(),"app/Models");try{let r=Em(n),s=r.find((u)=>u.replace(Di(u),"").toLowerCase()===e.toLowerCase());if(!s){console.error(`Model "${e}" not found in ${n}`),console.log(`Available models: ${r.filter((u)=>[".ts",".js"].includes(Di(u))).map((u)=>u.replace(Di(u),"")).join(", ")}`);return}let o=await import(al(n,s)),l=o.default||o[Object.keys(o)[0]];if(!l||!l.name){console.error(`Invalid model file: ${s}`);return}let a={name:l.name,table:l.table||`${l.name.toLowerCase()}s`,primaryKey:l.primaryKey||"id",attributes:l.attributes||{},relations:l.relations,scopes:l.scopes,indexes:l.indexes,timestamps:l.timestamps!==!1,softDeletes:l.softDeletes===!0},c=[];if(l.beforeCreate)c.push("beforeCreate");if(l.afterCreate)c.push("afterCreate");if(l.beforeUpdate)c.push("beforeUpdate");if(l.afterUpdate)c.push("afterUpdate");if(l.beforeDelete)c.push("beforeDelete");if(l.afterDelete)c.push("afterDelete");if(c.length>0)a.hooks=c;if(t.json)return console.log(JSON.stringify(a,null,2)),a;console.log(`
351
+ `)}catch(a){console.log("-- Migrations table not found. Nothing to rollback.",a);return}if(s.length===0){console.log("-- No migrations to rollback");return}let i=s.slice(0,t);console.log(`-- Found ${s.length} executed migrations`),console.log(`-- Rolling back ${i.length} migration(s):`),console.log();for(let a of i)console.log(` - ${a.migration}`);console.log();let o=Nt(void 0,_.migrationDir),l=!1;for(let a of i)try{let c=bm(o,a.migration);if(n&&ol(c)){let m=hm(c,"utf8"),{down:h,skipped:w}=wm(m);for(let N of h)await r.unsafe(N),console.log(`-- \u21A9 ${N}`),l=!0;if(w.length>0)console.log(`-- \u26A0\uFE0F ${w.length} statement(s) in ${a.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let u=`DELETE FROM migrations WHERE migration = ${Z(1)}`;if(await r.unsafe(u,[a.migration]),console.log(`-- \u2713 Removed migration record: ${a.migration}`),e.deleteFiles&&ol(c))pm(c),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${a.migration}`)}catch(c){throw console.error(`-- \u2717 Failed to rollback migration ${a.migration}:`,c),c}if(console.log(),n)console.log(l?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(r){throw console.error("-- Rollback failed:",r),r}}Me();import{existsSync as Sm,readdirSync as $m}from"fs";async function al(){let e=_.dialect||"postgres",t=Tt(e),n=Nt(void 0,_.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${e}`),console.log(`-- SQL directory: ${n}`),console.log(),!Sm(n))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let s=$m(n).filter((i)=>i.endsWith(".sql")).sort();if(s.length===0)return console.log("-- No migration files found"),[];try{let i=ie(),o=[];try{o=await i.unsafe(t.getExecutedMigrationsQuery())}catch(m){console.log("-- Migrations table not found. All migrations are pending.",m),console.log()}let l=new Map(o.map((m)=>[m.migration,m.executed_at])),a=s.map((m)=>({file:m,status:l.has(m)?"executed":"pending",executedAt:l.get(m)})),c=a.filter((m)=>m.status==="executed"),u=a.filter((m)=>m.status==="pending");if(console.log(`-- Total migrations: ${s.length}`),console.log(`-- Executed: ${c.length}`),console.log(`-- Pending: ${u.length}`),console.log(),c.length>0){console.log("\u2713 Executed Migrations:");for(let m of c)console.log(` - ${m.file} ${m.executedAt?`(${new Date(m.executedAt).toLocaleString()})`:""}`);console.log()}if(u.length>0){console.log("\u25CB Pending Migrations:");for(let m of u)console.log(` - ${m.file}`);console.log()}return a}catch(i){throw console.error("-- Failed to get migration status:",i),i}}async function Em(){return al()}import{readdirSync as xm}from"fs";import{extname as Ei,join as ll}from"path";import Rm from"process";async function cl(e,t={}){let n=t.dir||ll(Rm.cwd(),"app/Models");try{let r=xm(n),s=r.find((u)=>u.replace(Ei(u),"").toLowerCase()===e.toLowerCase());if(!s){console.error(`Model "${e}" not found in ${n}`),console.log(`Available models: ${r.filter((u)=>[".ts",".js"].includes(Ei(u))).map((u)=>u.replace(Ei(u),"")).join(", ")}`);return}let o=await import(ll(n,s)),l=o.default||o[Object.keys(o)[0]];if(!l||!l.name){console.error(`Invalid model file: ${s}`);return}let a={name:l.name,table:l.table||`${l.name.toLowerCase()}s`,primaryKey:l.primaryKey||"id",attributes:l.attributes||{},relations:l.relations,scopes:l.scopes,indexes:l.indexes,timestamps:l.timestamps!==!1,softDeletes:l.softDeletes===!0},c=[];if(l.beforeCreate)c.push("beforeCreate");if(l.afterCreate)c.push("afterCreate");if(l.beforeUpdate)c.push("beforeUpdate");if(l.afterUpdate)c.push("afterUpdate");if(l.beforeDelete)c.push("beforeDelete");if(l.afterDelete)c.push("afterDelete");if(c.length>0)a.hooks=c;if(t.json)return console.log(JSON.stringify(a,null,2)),a;console.log(`
352
352
  \uD83D\uDCE6 Model: ${a.name}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Table: ${a.table}`),console.log(`Primary Key: ${a.primaryKey}`),console.log(`Timestamps: ${a.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${a.softDeletes?"\u2713":"\u2717"}`),console.log(`
353
353
  \uD83D\uDCCB Attributes (${Object.keys(a.attributes).length}):`);for(let[u,m]of Object.entries(a.attributes)){let h=m.type||"string",w=m.required?"(required)":"",N=m.unique?"(unique)":"",R=m.default!==void 0?`= ${JSON.stringify(m.default)}`:"";console.log(` \u2022 ${u}: ${h} ${w} ${N} ${R}`.trim())}if(a.relations&&Object.keys(a.relations).length>0){console.log(`
354
354
  \uD83D\uDD17 Relations (${Object.keys(a.relations).length}):`);for(let[u,m]of Object.entries(a.relations)){let h=m.type||"unknown",w=m.model||m.table||"unknown";console.log(` \u2022 ${u}: ${h} \u2192 ${w}`)}}if(a.scopes&&Object.keys(a.scopes).length>0){console.log(`
355
355
  \uD83D\uDD0D Scopes (${Object.keys(a.scopes).length}):`);for(let u of Object.keys(a.scopes))console.log(` \u2022 ${u}()`)}if(a.hooks&&a.hooks.length>0){console.log(`
356
356
  \uD83E\uDE9D Hooks (${a.hooks.length}):`);for(let u of a.hooks)console.log(` \u2022 ${u}`)}if(a.indexes&&a.indexes.length>0){console.log(`
357
- \uD83D\uDCC7 Indexes (${a.indexes.length}):`);for(let u of a.indexes){let m=Array.isArray(u.columns)?u.columns.join(", "):u.columns,h=u.unique?"(unique)":"";console.log(` \u2022 ${u.name||"unnamed"}: [${m}] ${h}`.trim())}}return console.log(),a}catch(r){throw console.error(`Error loading model "${e}":`,r.message),r}}async function Rm(){let t=await ie().ping();return console.log(t?"OK":"NOT READY"),t}Kt();import{readdirSync as km,readFileSync as cl,statSync as Cm}from"fs";import{extname as ul,join as vm}from"path";async function dl(e,t={}){let n=[];try{let r=Cm(e),s=[];if(r.isDirectory())s=km(e).filter((a)=>ul(a)===".sql").map((a)=>vm(e,a));else if(r.isFile()&&ul(e)===".sql")s=[e];else return console.error("Path must be a .sql file or directory containing .sql files"),n;if(s.length===0)return console.log("No .sql files found"),n;if(t.verbose)console.log(`Analyzing ${s.length} SQL file(s)...
358
- `);for(let l of s)try{let a=cl(l,"utf8").trim();if(!a){if(t.verbose)console.log(`\u2298 ${l}: empty file`);continue}if(t.verbose)console.log(`\uD83D\uDCC4 ${l}`),console.log(` Query: ${a.substring(0,60)}${a.length>60?"...":""}`);let c=await te`EXPLAIN ${te.unsafe(a)}`;if(n.push({file:l,query:a,plan:Array.isArray(c)?c:[c]}),t.verbose&&!t.json){if(console.log(" Plan:"),Array.isArray(c))for(let u of c)if(typeof u==="string")console.log(` ${u}`);else if(u["QUERY PLAN"])console.log(` ${u["QUERY PLAN"]}`);else if(u.plan)console.log(` ${JSON.stringify(u.plan)}`);else console.log(` ${JSON.stringify(u)}`);console.log()}}catch(a){if(n.push({file:l,query:cl(l,"utf8").trim(),plan:[],error:a.message}),t.verbose)console.log(` \u2717 Error: ${a.message}
359
- `)}let i=n.filter((l)=>!l.error).length,o=n.filter((l)=>l.error).length;if(t.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${i} successful, ${o} failed`);if(t.json)console.log(JSON.stringify(n,null,2));return n}catch(r){throw console.error("Error explaining queries:",r.message),r}}import{writeFileSync as Am}from"fs";import{join as Nm}from"path";import Mm from"process";async function fl(e={}){let t=e.dir||Nm(Mm.cwd(),"app/Models"),n=e.format||"mermaid";try{let r=await mt({modelsDir:t});if(!r||Object.keys(r).length===0)return console.error("No models found"),"";let s="";if(n==="mermaid")s=Om(r);else if(n==="dot")s=Bm(r);else return console.error(`Unsupported format: ${n}`),"";if(e.output)Am(e.output,s,"utf8"),console.log(`\u2713 Diagram written to: ${e.output}`);else console.log(s);return s}catch(r){throw console.error("Error generating diagram:",r.message),r}}function Om(e){let t=["erDiagram"];for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.attributes||{};t.push(` ${s} {`);for(let[o,l]of Object.entries(i)){let a=l.type||"string",c=r.primaryKey===o?"PK":"",u=l.unique?"UK":"",m=[c,u].filter(Boolean).join(","),h=m?` "${m}"`:"";t.push(` ${a} ${o}${h}`)}t.push(" }")}for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.relations||{};for(let[o,l]of Object.entries(i)){let{type:a,model:c}=l,u=e[c]?.table||`${c?.toLowerCase()}s`||"unknown",m="";if(a==="hasOne")m="||--||";else if(a==="hasMany")m="||--o{";else if(a==="belongsTo")m="}o--||";else if(a==="belongsToMany"||a==="manyToMany")m="}o--o{";else m="||--||";t.push(` ${s} ${m} ${u} : "${o}"`)}}return t.join(`
360
- `)}function Bm(e){let t=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.attributes||{},o=[];for(let[a,c]of Object.entries(i)){let u=c.type||"string",m=r.primaryKey===a?" (PK)":"",h=c.unique?" (UK)":"";o.push(`${a}: ${u}${m}${h}`)}let l=`${o.join("\\l")}\\l`;t.push(` ${s} [label="{${s}|${l}}"];`)}t.push("");for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.relations||{};for(let[o,l]of Object.entries(i)){let{type:a,model:c}=l,u=e[c]?.table||`${c?.toLowerCase()}s`||"unknown",m="";if(a==="hasOne")m="arrowhead=none, arrowtail=normal";else if(a==="hasMany")m="arrowhead=crow, arrowtail=none";else if(a==="belongsTo")m="arrowhead=normal, arrowtail=none";else if(a==="belongsToMany"||a==="manyToMany")m="arrowhead=crow, arrowtail=crow";t.push(` ${s} -> ${u} [label="${o}", ${m}];`)}}return t.push("}"),t.join(`
361
- `)}import{existsSync as ls,mkdirSync as Pm,readdirSync as _m,writeFileSync as Im}from"fs";import{dirname as ml,join as Wt}from"path";import Yn from"process";function cs(e){let t=e;while(t!==ml(t)){if(ls(Wt(t,"package.json")))return t;t=ml(t)}return Yn.cwd()}async function gl(e){if(!ls(e))return console.log(`-- Seeders directory not found: ${e}`),[];let n=_m(e).sort((s,i)=>s.localeCompare(i)).filter((s)=>(s.endsWith(".ts")||s.endsWith(".js"))&&s!=="index.ts"&&s!=="index.js"),r=[];for(let s of n){let i=Wt(e,s);try{let o=await import(i),l=o.default||o[Object.keys(o)[0]];if(l&&typeof l==="function"){let a=new l;if(a&&typeof a.run==="function")r.push({name:s.replace(/\.(ts|js)$/,""),className:String(l.name||""),instance:a})}}catch(o){console.error(`-- Failed to load seeder ${s}:`,o)}}return r.sort((s,i)=>s.instance.order-i.instance.order),r}async function yl(e={}){let t=cs(Yn.cwd()),n=e.seedersDir||Wt(t,"database/seeders"),r=e.verbose??!0;if(r)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${n}`);let s=await gl(n);if(s.length===0){console.log("-- No seeders found");return}if(r)console.log(`-- Found ${s.length} seeder(s)`);let i=ie();for(let{name:o,instance:l}of s)try{if(r)console.log(`-- Seeding: ${o}`);if(await l.run(i),r)console.log(`-- \u2713 Seeded: ${o}`)}catch(a){throw console.error(`-- \u2717 Failed to seed ${o}:`,a),a}if(r)console.log("-- All seeders completed successfully")}async function Lm(e,t={}){let n=cs(Yn.cwd()),r=Wt(n,"database/seeders"),s=t.verbose??!0;if(s)console.log(`-- Running seeder: ${e}`);let i=await gl(r),o=i.find((a)=>a.className===e)??i.find((a)=>a.name===e);if(!o){let a=i.map((c)=>c.className||c.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${e}. Available: ${a}`),Error(`Seeder not found: ${e}. Available: ${a}`)}let l=ie();try{if(await o.instance.run(l),s)console.log(`-- \u2713 Seeder completed: ${e}`)}catch(a){throw console.error(`-- \u2717 Seeder failed: ${e}`,a),a}}async function Km(e){let t=cs(Yn.cwd()),n=Wt(t,"database/seeders");if(!ls(n))Pm(n,{recursive:!0}),console.log(`-- Created seeders directory: ${n}`);let s=`${e.replace(/Seeder$/i,"")}Seeder`,i=`${s}.ts`,o=Wt(n,i);if(ls(o))throw console.error(`-- Seeder already exists: ${o}`),Error(`Seeder already exists: ${o}`);let l=`import type { QueryBuilder } from 'bun-query-builder'
357
+ \uD83D\uDCC7 Indexes (${a.indexes.length}):`);for(let u of a.indexes){let m=Array.isArray(u.columns)?u.columns.join(", "):u.columns,h=u.unique?"(unique)":"";console.log(` \u2022 ${u.name||"unnamed"}: [${m}] ${h}`.trim())}}return console.log(),a}catch(r){throw console.error(`Error loading model "${e}":`,r.message),r}}async function km(){let t=await ie().ping();return console.log(t?"OK":"NOT READY"),t}Ft();import{readdirSync as Cm,readFileSync as ul,statSync as vm}from"fs";import{extname as dl,join as Am}from"path";async function fl(e,t={}){let n=[];try{let r=vm(e),s=[];if(r.isDirectory())s=Cm(e).filter((a)=>dl(a)===".sql").map((a)=>Am(e,a));else if(r.isFile()&&dl(e)===".sql")s=[e];else return console.error("Path must be a .sql file or directory containing .sql files"),n;if(s.length===0)return console.log("No .sql files found"),n;if(t.verbose)console.log(`Analyzing ${s.length} SQL file(s)...
358
+ `);for(let l of s)try{let a=ul(l,"utf8").trim();if(!a){if(t.verbose)console.log(`\u2298 ${l}: empty file`);continue}if(t.verbose)console.log(`\uD83D\uDCC4 ${l}`),console.log(` Query: ${a.substring(0,60)}${a.length>60?"...":""}`);let c=await te`EXPLAIN ${te.unsafe(a)}`;if(n.push({file:l,query:a,plan:Array.isArray(c)?c:[c]}),t.verbose&&!t.json){if(console.log(" Plan:"),Array.isArray(c))for(let u of c)if(typeof u==="string")console.log(` ${u}`);else if(u["QUERY PLAN"])console.log(` ${u["QUERY PLAN"]}`);else if(u.plan)console.log(` ${JSON.stringify(u.plan)}`);else console.log(` ${JSON.stringify(u)}`);console.log()}}catch(a){if(n.push({file:l,query:ul(l,"utf8").trim(),plan:[],error:a.message}),t.verbose)console.log(` \u2717 Error: ${a.message}
359
+ `)}let i=n.filter((l)=>!l.error).length,o=n.filter((l)=>l.error).length;if(t.verbose)console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`Summary: ${i} successful, ${o} failed`);if(t.json)console.log(JSON.stringify(n,null,2));return n}catch(r){throw console.error("Error explaining queries:",r.message),r}}import{writeFileSync as Nm}from"fs";import{join as Mm}from"path";import Om from"process";async function ml(e={}){let t=e.dir||Mm(Om.cwd(),"app/Models"),n=e.format||"mermaid";try{let r=await mt({modelsDir:t});if(!r||Object.keys(r).length===0)return console.error("No models found"),"";let s="";if(n==="mermaid")s=Bm(r);else if(n==="dot")s=Pm(r);else return console.error(`Unsupported format: ${n}`),"";if(e.output)Nm(e.output,s,"utf8"),console.log(`\u2713 Diagram written to: ${e.output}`);else console.log(s);return s}catch(r){throw console.error("Error generating diagram:",r.message),r}}function Bm(e){let t=["erDiagram"];for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.attributes||{};t.push(` ${s} {`);for(let[o,l]of Object.entries(i)){let a=l.type||"string",c=r.primaryKey===o?"PK":"",u=l.unique?"UK":"",m=[c,u].filter(Boolean).join(","),h=m?` "${m}"`:"";t.push(` ${a} ${o}${h}`)}t.push(" }")}for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.relations||{};for(let[o,l]of Object.entries(i)){let{type:a,model:c}=l,u=e[c]?.table||`${c?.toLowerCase()}s`||"unknown",m="";if(a==="hasOne")m="||--||";else if(a==="hasMany")m="||--o{";else if(a==="belongsTo")m="}o--||";else if(a==="belongsToMany"||a==="manyToMany")m="}o--o{";else m="||--||";t.push(` ${s} ${m} ${u} : "${o}"`)}}return t.join(`
360
+ `)}function Pm(e){let t=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.attributes||{},o=[];for(let[a,c]of Object.entries(i)){let u=c.type||"string",m=r.primaryKey===a?" (PK)":"",h=c.unique?" (UK)":"";o.push(`${a}: ${u}${m}${h}`)}let l=`${o.join("\\l")}\\l`;t.push(` ${s} [label="{${s}|${l}}"];`)}t.push("");for(let[n,r]of Object.entries(e)){let s=r.table||`${n.toLowerCase()}s`,i=r.relations||{};for(let[o,l]of Object.entries(i)){let{type:a,model:c}=l,u=e[c]?.table||`${c?.toLowerCase()}s`||"unknown",m="";if(a==="hasOne")m="arrowhead=none, arrowtail=normal";else if(a==="hasMany")m="arrowhead=crow, arrowtail=none";else if(a==="belongsTo")m="arrowhead=normal, arrowtail=none";else if(a==="belongsToMany"||a==="manyToMany")m="arrowhead=crow, arrowtail=crow";t.push(` ${s} -> ${u} [label="${o}", ${m}];`)}}return t.push("}"),t.join(`
361
+ `)}import{existsSync as ls,mkdirSync as _m,readdirSync as Im,writeFileSync as Lm}from"fs";import{dirname as gl,join as Ut}from"path";import Xn from"process";function cs(e){let t=e;while(t!==gl(t)){if(ls(Ut(t,"package.json")))return t;t=gl(t)}return Xn.cwd()}async function yl(e){if(!ls(e))return console.log(`-- Seeders directory not found: ${e}`),[];let n=Im(e).sort((s,i)=>s.localeCompare(i)).filter((s)=>(s.endsWith(".ts")||s.endsWith(".js"))&&s!=="index.ts"&&s!=="index.js"),r=[];for(let s of n){let i=Ut(e,s);try{let o=await import(i),l=o.default||o[Object.keys(o)[0]];if(l&&typeof l==="function"){let a=new l;if(a&&typeof a.run==="function")r.push({name:s.replace(/\.(ts|js)$/,""),className:String(l.name||""),instance:a})}}catch(o){console.error(`-- Failed to load seeder ${s}:`,o)}}return r.sort((s,i)=>s.instance.order-i.instance.order),r}async function hl(e={}){let t=cs(Xn.cwd()),n=e.seedersDir||Ut(t,"database/seeders"),r=e.verbose??!0;if(r)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${n}`);let s=await yl(n);if(s.length===0){console.log("-- No seeders found");return}if(r)console.log(`-- Found ${s.length} seeder(s)`);let i=ie();for(let{name:o,instance:l}of s)try{if(r)console.log(`-- Seeding: ${o}`);if(await l.run(i),r)console.log(`-- \u2713 Seeded: ${o}`)}catch(a){throw console.error(`-- \u2717 Failed to seed ${o}:`,a),a}if(r)console.log("-- All seeders completed successfully")}async function Km(e,t={}){let n=cs(Xn.cwd()),r=Ut(n,"database/seeders"),s=t.verbose??!0;if(s)console.log(`-- Running seeder: ${e}`);let i=await yl(r),o=i.find((a)=>a.className===e)??i.find((a)=>a.name===e);if(!o){let a=i.map((c)=>c.className||c.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${e}. Available: ${a}`),Error(`Seeder not found: ${e}. Available: ${a}`)}let l=ie();try{if(await o.instance.run(l),s)console.log(`-- \u2713 Seeder completed: ${e}`)}catch(a){throw console.error(`-- \u2717 Seeder failed: ${e}`,a),a}}async function Fm(e){let t=cs(Xn.cwd()),n=Ut(t,"database/seeders");if(!ls(n))_m(n,{recursive:!0}),console.log(`-- Created seeders directory: ${n}`);let s=`${e.replace(/Seeder$/i,"")}Seeder`,i=`${s}.ts`,o=Ut(n,i);if(ls(o))throw console.error(`-- Seeder already exists: ${o}`),Error(`Seeder already exists: ${o}`);let l=`import type { QueryBuilder } from 'bun-query-builder'
362
362
  import { Seeder } from 'bun-query-builder'
363
363
  import { faker } from '@stacksjs/ts-faker'
364
364
 
@@ -403,7 +403,7 @@ export default class ${s} extends Seeder {
403
403
  return 100
404
404
  }
405
405
  }
406
- `;Im(o,l),console.log(`-- \u2713 Created seeder: ${o}`)}async function Fm(e={}){let t=cs(Yn.cwd()),n=e.modelsDir||Wt(t,"app/Models"),r=e.seedersDir||Wt(t,"database/seeders"),s=e.verbose??!0;try{let{resetDatabase:i,generateMigration:o,executeMigration:l}=await import("./chunk-kjkkmrp8.js");if(s)console.log("-- Refreshing database...");if(await i(n),s)console.log("-- Running migrations...");if(await o(n,{full:!0}),await l(),s)console.log("-- Running seeders...");if(await yl({seedersDir:r,verbose:s}),s)console.log("-- \u2713 Database refreshed successfully")}catch(i){throw console.error("-- \u2717 Database refresh failed:",i),i}}Me();function qm(e,t,n={}){let r=mt({modelsDir:e}),s=as(r);if(_.debug)_.debug.captureText=!0;let i=ie({schema:s}),o=i.selectFrom(t).limit(Number(n.limit||10)).toText?.()??"";return console.log(o||"[query]"),{sql:o,qb:i,schema:s}}async function jm(e,t={}){let n=ie(),r=t.params?JSON.parse(t.params):void 0,s=await n.unsafe(e,r);return console.log(JSON.stringify(s)),s}Me();import{existsSync as Wm}from"fs";import{dirname as hl,join as pl}from"path";import bl from"process";function Um(e){let t=e;while(t!==hl(t)){if(Wm(pl(t,"package.json")))return t;t=hl(t)}return bl.cwd()}async function Tl(e){if(!e)e=pl(Um(bl.cwd()),"app/Models");let t=_.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${e}`),console.log(`-- Dialect: ${t}`),console.log();let n=[];try{let r=await mt({modelsDir:e}),s=Xn(r,{dialect:t}),i=ie(),o=[];if(t==="sqlite")o=(await i.unsafe(`
406
+ `;Lm(o,l),console.log(`-- \u2713 Created seeder: ${o}`)}async function qm(e={}){let t=cs(Xn.cwd()),n=e.modelsDir||Ut(t,"app/Models"),r=e.seedersDir||Ut(t,"database/seeders"),s=e.verbose??!0;try{let{resetDatabase:i,generateMigration:o,executeMigration:l}=await import("./chunk-y0ff2jm5.js");if(s)console.log("-- Refreshing database...");if(await i(n),s)console.log("-- Running migrations...");if(await o(n,{full:!0}),await l(),s)console.log("-- Running seeders...");if(await hl({seedersDir:r,verbose:s}),s)console.log("-- \u2713 Database refreshed successfully")}catch(i){throw console.error("-- \u2717 Database refresh failed:",i),i}}Me();function jm(e,t,n={}){let r=mt({modelsDir:e}),s=as(r);if(_.debug)_.debug.captureText=!0;let i=ie({schema:s}),o=i.selectFrom(t).limit(Number(n.limit||10)).toText?.()??"";return console.log(o||"[query]"),{sql:o,qb:i,schema:s}}async function Wm(e,t={}){let n=ie(),r=t.params?JSON.parse(t.params):void 0,s=await n.unsafe(e,r);return console.log(JSON.stringify(s)),s}Me();import{existsSync as Um}from"fs";import{dirname as pl,join as bl}from"path";import Tl from"process";function Qm(e){let t=e;while(t!==pl(t)){if(Um(bl(t,"package.json")))return t;t=pl(t)}return Tl.cwd()}async function wl(e){if(!e)e=bl(Qm(Tl.cwd()),"app/Models");let t=_.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${e}`),console.log(`-- Dialect: ${t}`),console.log();let n=[];try{let r=await mt({modelsDir:e}),s=Zn(r,{dialect:t}),i=ie(),o=[];if(t==="sqlite")o=(await i.unsafe(`
407
407
  SELECT name FROM sqlite_master
408
408
  WHERE type = 'table'
409
409
  AND name NOT LIKE 'sqlite_%'
@@ -429,18 +429,18 @@ export default class ${s} extends Seeder {
429
429
  FROM information_schema.columns
430
430
  WHERE table_name = ?
431
431
  AND table_schema = DATABASE()
432
- `,[c.table])).map((N)=>({name:N.column_name,type:N.data_type.toLowerCase()}));let m=u.map((w)=>w.name),h=c.columns.map((w)=>w.name);for(let w of c.columns)if(!m.includes(w.name))n.push({type:"missing_column",severity:"error",table:c.table,column:w.name,expected:w.type,message:`Column '${c.table}.${w.name}' defined in model but not found in database`});for(let w of u)if(!h.includes(w.name))n.push({type:"extra_column",severity:"warning",table:c.table,column:w.name,actual:w.type,message:`Column '${c.table}.${w.name}' exists in database but not defined in model`});for(let w of c.columns){let N=u.find((R)=>R.name===w.name);if(N){let R=(g)=>g.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim(),y=R(w.type),b=R(N.type);if(y!==b)n.push({type:"type_mismatch",severity:"warning",table:c.table,column:w.name,expected:w.type,actual:N.type,message:`Column '${c.table}.${w.name}' type mismatch: expected '${w.type}', found '${N.type}'`})}}}let a=n.filter((c)=>c.severity==="error").length===0;if(a&&n.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${n.length} issue(s)`),console.log();let c=n.filter((m)=>m.severity==="error"),u=n.filter((m)=>m.severity==="warning");if(c.length>0){console.log(`\u2717 Errors (${c.length}):`);for(let m of c)console.log(` - ${m.message}`);console.log()}if(u.length>0){console.log(`\u26A0 Warnings (${u.length}):`);for(let m of u)console.log(` - ${m.message}`);console.log()}if(!a)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:a,issues:n}}catch(r){throw console.error("-- Schema validation failed:",r),r}}async function Qm(e){return Tl(e)}async function Vm(e={}){let t=Number(e.attempts||10),n=Number(e.delay||100),r=ie();try{return await r.waitForReady({attempts:t,delayMs:n}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}Kl();tr();Me();class Vt{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(e){this.driver=Zt(e.config),this.client=e.client,this.tableName=e.config.tableName??""}table(e){return this.tableName=e,this}index(e){return this.indexName=e,this}entity(e){return this.entityType=e,this}whereKey(e,t,n){return this.keyConditions.push({attribute:e,operator:t,value:n}),this}wherePartitionKey(e,t){return this.whereKey(e,"=",t)}whereSortKey(e,t){return this.whereKey(e,"=",t)}whereSortKeyBeginsWith(e,t){return this.keyConditions.push({attribute:e,operator:"begins_with",value:t}),this}whereSortKeyBetween(e,t,n){return this.keyConditions.push({attribute:e,operator:"BETWEEN",values:[t,n]}),this}where(e,t,n){return this.filterConditions.push({attribute:e,operator:t,value:n}),this}whereEquals(e,t){return this.where(e,"=",t)}whereLessThan(e,t){return this.where(e,"<",t)}whereLessThanOrEqual(e,t){return this.where(e,"<=",t)}whereGreaterThan(e,t){return this.where(e,">",t)}whereGreaterThanOrEqual(e,t){return this.where(e,">=",t)}whereBetween(e,t,n){return this.filterConditions.push({attribute:e,operator:"BETWEEN",values:[t,n]}),this}whereBeginsWith(e,t){return this.filterConditions.push({attribute:e,operator:"begins_with",value:t}),this}whereContains(e,t){return this.where(e,"contains",t)}whereExists(e){return this.where(e,"attribute_exists")}whereNotExists(e){return this.where(e,"attribute_not_exists")}whereIn(e,t){return this.filterConditions.push({attribute:e,operator:"IN",values:t}),this}select(...e){return this.projectionAttrs.push(...e),this}limit(e){return this.limitValue=e,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(e=!0){return this.consistentReadValue=e,this}startFrom(e){return this.startKey=e,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let e=this.buildQueryParams(),t={TableName:e.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(e.indexName)t.IndexName=e.indexName;let n=0;if(e.keyConditions.length>0){let r=[];for(let s of e.keyConditions){let i=`#key${n}`;if(t.ExpressionAttributeNames[i]=s.attribute,s.operator==="begins_with"){let o=`:keyval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`begins_with(${i}, ${o})`)}else if(s.operator==="BETWEEN"){let o=`:keyval${n}a`,l=`:keyval${n}b`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.values?.[0]}).v,t.ExpressionAttributeValues[l]=this.driver.marshall({v:s.values?.[1]}).v,r.push(`${i} BETWEEN ${o} AND ${l}`)}else{let o=`:keyval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`${i} ${s.operator} ${o}`)}n++}t.KeyConditionExpression=r.join(" AND ")}if(e.filterConditions&&e.filterConditions.length>0){let r=[];for(let s of e.filterConditions){let i=`#flt${n}`;if(t.ExpressionAttributeNames[i]=s.attribute,s.operator==="attribute_exists")r.push(`attribute_exists(${i})`);else if(s.operator==="attribute_not_exists")r.push(`attribute_not_exists(${i})`);else if(s.operator==="begins_with"||s.operator==="contains"){let o=`:fltval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`${s.operator}(${i}, ${o})`)}else if(s.operator==="BETWEEN"){let o=`:fltval${n}a`,l=`:fltval${n}b`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.values?.[0]}).v,t.ExpressionAttributeValues[l]=this.driver.marshall({v:s.values?.[1]}).v,r.push(`${i} BETWEEN ${o} AND ${l}`)}else if(s.operator==="IN"){let o=(s.values??[]).map((l,a)=>`:fltval${n}_${a}`);s.values?.forEach((l,a)=>{t.ExpressionAttributeValues[`:fltval${n}_${a}`]=this.driver.marshall({v:l}).v}),r.push(`${i} IN (${o.join(", ")})`)}else{let o=`:fltval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`${i} ${s.operator} ${o}`)}n++}t.FilterExpression=r.join(" AND ")}if(e.projectionAttributes&&e.projectionAttributes.length>0){let r=[];for(let s of e.projectionAttributes){let i=`#proj${n}`;t.ExpressionAttributeNames[i]=s,r.push(i),n++}t.ProjectionExpression=r.join(", ")}if(e.limit!==void 0)t.Limit=e.limit;if(e.scanIndexForward!==void 0)t.ScanIndexForward=e.scanIndexForward;if(e.exclusiveStartKey)t.ExclusiveStartKey=this.driver.marshall(e.exclusiveStartKey);if(e.consistentRead)t.ConsistentRead=e.consistentRead;if(Object.keys(t.ExpressionAttributeNames).length===0)delete t.ExpressionAttributeNames;if(Object.keys(t.ExpressionAttributeValues).length===0)delete t.ExpressionAttributeValues;return t}toScanRequest(){let e=this.buildScanParams(),t={TableName:e.tableName};if(e.indexName)t.IndexName=e.indexName;if(e.filterConditions&&e.filterConditions.length>0){let{expression:n,expressionAttributeNames:r,expressionAttributeValues:s}=this.driver.buildFilterExpression(e.filterConditions);t.FilterExpression=n,t.ExpressionAttributeNames=r,t.ExpressionAttributeValues=s}if(e.projectionAttributes&&e.projectionAttributes.length>0){let{expression:n,expressionAttributeNames:r}=this.driver.buildProjectionExpression(e.projectionAttributes);t.ProjectionExpression=n,t.ExpressionAttributeNames={...t.ExpressionAttributeNames,...r}}if(e.limit!==void 0)t.Limit=e.limit;if(e.exclusiveStartKey)t.ExclusiveStartKey=this.driver.marshall(e.exclusiveStartKey);if(e.consistentRead)t.ConsistentRead=e.consistentRead;return t}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let e=this.toQueryRequest(),t=await this.client.query(e);return{items:t.Items?.map((n)=>this.driver.unmarshall(n)),count:t.Count,scannedCount:t.ScannedCount,lastEvaluatedKey:t.LastEvaluatedKey?this.driver.unmarshall(t.LastEvaluatedKey):void 0,consumedCapacity:t.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let e=this.toScanRequest(),t=await this.client.scan(e);return{items:t.Items?.map((n)=>this.driver.unmarshall(n)),count:t.Count,scannedCount:t.ScannedCount,lastEvaluatedKey:t.LastEvaluatedKey?this.driver.unmarshall(t.LastEvaluatedKey):void 0,consumedCapacity:t.ConsumedCapacity}}async getAll(){let e=[],t;do{if(t)this.startFrom(t);let n=this.keyConditions.length>0?await this.query():await this.scan();if(n.items)e.push(...n.items);t=n.lastEvaluatedKey}while(t);return e}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return e.Select="COUNT",(this.keyConditions.length>0?await this.client.query(e):await this.client.scan(e)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class Dt{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(e){this.driver=Zt(e.config),this.client=e.client,this.tableName=e.config.tableName??""}table(e){return this.tableName=e,this}key(e){return this.keyData=e,this}item(e){return this.itemData=e,this}set(e,t){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[e]=t,this}setMany(e){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,e),this}remove(e){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(e),this}add(e,t){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[e]=t,this}deleteFromSet(e,t){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[e]=t,this}condition(e){return this.conditionExpr=e,this}ifNotExists(e="pk"){return this.conditionExpr=`attribute_not_exists(${e})`,this}ifExists(e="pk"){return this.conditionExpr=`attribute_exists(${e})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let e={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)e.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")e.ReturnValues=this.returnValuesOption;return e}toUpdateRequest(){let e={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:t,expressionAttributeNames:n,expressionAttributeValues:r}=this.driver.buildUpdateExpression(this.updateExpressions);if(t)e.UpdateExpression=t,e.ExpressionAttributeNames=n,e.ExpressionAttributeValues=r;if(this.conditionExpr)e.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")e.ReturnValues=this.returnValuesOption;return e}toDeleteRequest(){let e={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)e.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")e.ReturnValues=this.returnValuesOption;return e}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toPutRequest(),t=await this.client.putItem(e);if(t.Attributes)return this.driver.unmarshall(t.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toUpdateRequest(),t=await this.client.updateItem(e);if(t.Attributes)return this.driver.unmarshall(t.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toDeleteRequest(),t=await this.client.deleteItem(e);if(t.Attributes)return this.driver.unmarshall(t.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toGetRequest(),t=await this.client.getItem(e);if(t.Item)return this.driver.unmarshall(t.Item);return}}function hw(e){return new Vt(e)}function pw(e){return new Dt(e)}function bw(e){let t=Zt(e.config);return{query:()=>new Vt(e),item:()=>new Dt(e),driver:t,registerEntity:(n)=>t.registerEntity(n),buildKey:(n,r)=>t.buildPrimaryKey(n,r)}}class Vl{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(e){this.config=e,this.pkAttribute=e.pkAttribute??"pk",this.skAttribute=e.skAttribute??"sk",this.typeAttribute=e.typeAttribute??"_type";for(let t of e.entities)this.entities.set(t.name,t)}getEntity(e){return this.entities.get(e)}registerEntity(e){this.entities.set(e.name,e)}buildKey(e,t){let n=this.entities.get(e);if(!n)throw Error(`Entity not found: ${e}`);let r=this.interpolatePattern(n.pkPattern,t),s=this.interpolatePattern(n.skPattern,t);return{pk:r,sk:s}}buildGSIKey(e,t,n){let r=this.entities.get(e);if(!r)throw Error(`Entity not found: ${e}`);let s=r.indexes?.find((l)=>l.name===t);if(!s)throw Error(`GSI not found: ${t} for entity ${e}`);let i=this.interpolatePattern(s.pkPattern,n),o=s.skPattern?this.interpolatePattern(s.skPattern,n):void 0;return{pk:i,sk:o}}createItem(e,t){let{pk:n,sk:r}=this.buildKey(e,t),s=this.entities.get(e),i={[this.pkAttribute]:n,[this.skAttribute]:r,[this.typeAttribute]:e,...t};if(s.indexes)for(let o of s.indexes){let l=this.buildGSIKey(e,o.name,t),a=this.config.indexes?.find((c)=>c.name===o.name);if(a){if(i[a.pkAttribute]=l.pk,a.skAttribute&&l.sk)i[a.skAttribute]=l.sk}}return i}parseEntityType(e){if(e[this.typeAttribute])return e[this.typeAttribute];let t=e[this.pkAttribute];if(!t)return;for(let[n,r]of this.entities){let s=r.pkPattern.split("${")[0];if(t.startsWith(s))return n}return}parseItem(e){let t=this.parseEntityType(e);if(!t)return;let{[this.pkAttribute]:n,[this.skAttribute]:r,[this.typeAttribute]:s,...i}=e;return{type:t,data:i}}getEntityPrefix(e){let t=this.entities.get(e);if(!t)throw Error(`Entity not found: ${e}`);return t.pkPattern.split("${")[0]}generateTableDefinition(){let e=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],t=[];if(this.config.indexes)for(let n of this.config.indexes){if(!e.find((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.find((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});t.push({indexName:n.name,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:t.length>0?t:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(e,t){return e.replace(/\$\{(\w+)\}/g,(n,r)=>{if(!(r in t))throw Error(`Missing value for pattern key: ${r}`);return String(t[r])})}}class Jl{manager;entityName;options;constructor(e,t,n){this.manager=e,this.entityName=t,this.options=n}async create(e){let t=this.manager.createItem(this.entityName,e),n=new Dt(this.options).table(this.options.config.tableName).item(t).ifNotExists("pk");if(this.options.client)await n.put();return e}async get(e){let{pk:t,sk:n}=this.manager.buildKey(this.entityName,e),r=new Dt(this.options).table(this.options.config.tableName).key({pk:t,sk:n});if(!this.options.client)throw Error("DynamoDB client not provided");let s=await r.get();if(!s)return;return this.manager.parseItem(s)?.data}async update(e,t){let{pk:n,sk:r}=this.manager.buildKey(this.entityName,e),s=new Dt(this.options).table(this.options.config.tableName).key({pk:n,sk:r}).setMany(t).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let i=await s.update();if(!i)return;return this.manager.parseItem(i)?.data}async delete(e){let{pk:t,sk:n}=this.manager.buildKey(this.entityName,e),r=new Dt(this.options).table(this.options.config.tableName).key({pk:t,sk:n});if(!this.options.client)throw Error("DynamoDB client not provided");return await r.delete(),!0}query(){return new Hl(this.manager,this.entityName,this.options)}async findAll(){let e=this.manager.typeAttribute??"_type",t=new Vt(this.options).table(this.options.config.tableName).whereEquals(e,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await t.getAll()).map((r)=>this.manager.parseItem(r)).filter((r)=>r!==void 0).map((r)=>r.data)}}class Hl{manager;entityName;options;builder;pkValue;skConditions=[];constructor(e,t,n){this.manager=e,this.entityName=t,this.options=n,this.builder=new Vt(n).table(n.config.tableName)}wherePartitionKey(e){let{pk:t}=this.manager.buildKey(this.entityName,e);this.pkValue=t;let n=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(n,t),this}whereSortKey(e){let{sk:t}=this.manager.buildKey(this.entityName,e),n=this.manager.skAttribute??"sk";return this.builder.whereSortKey(n,t),this}whereSortKeyBeginsWith(e){let t=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(t,e),this}useIndex(e,t){let n=this.manager.buildGSIKey(this.entityName,e,t),r=this.manager.config.indexes?.find((s)=>s.name===e);if(!r)throw Error(`GSI configuration not found: ${e}`);return this.builder.index(e),this.builder.wherePartitionKey(r.pkAttribute,n.pk),this}where(e,t,n){return this.builder.where(e,t,n),this}select(...e){return this.builder.select(...e),this}limit(e){return this.builder.limit(e),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map((t)=>this.manager.parseItem(t)).filter((t)=>t!==void 0).map((t)=>t.data)}async first(){return this.limit(1),(await this.execute())[0]}}function zl(e){return new Vl(e)}function Gl(e,t,n){return new Jl(e,t,n)}var Dw={simpleEntity:(e,t="id")=>({name:e,pkPattern:`${e.toUpperCase()}#\${${t}}`,skPattern:"METADATA",keyFields:[t]}),oneToMany:(e,t,n="id",r="id")=>({parent:{name:e,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:"METADATA",keyFields:[n]},child:{name:t,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:`${t.toUpperCase()}#\${${r}}`,keyFields:[n,r]}}),manyToMany:(e,t,n="id",r="relatedId")=>({entity:{name:e,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:"METADATA",keyFields:[n]},relation:{name:t,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:`${t.toUpperCase()}#\${${r}}`,keyFields:[n,r],indexes:[{name:"GSI1",pkPattern:`${e.toUpperCase()}#\${${r}}`,skPattern:`${t.toUpperCase()}#\${${n}}`}]}}),hierarchical:(e,t="rootId",n="path")=>({name:e,pkPattern:`ROOT#\${${t}}`,skPattern:`PATH#\${${n}}`,keyFields:[t,n]})};function Yl(e,t){let n={};for(let[r,s]of Object.entries(e))if(s)n[r]=s.replace(/\{([^}]+)\}/g,(i,o)=>t[o]!==void 0?String(t[o]):`{${o}}`);return n}async function dg(e){return{models:new Map}}function $w(e){return e}function Ew(e){return e}function xw(e){return e}function Rw(e){return e}class Xl{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(e){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...e};let t={region:e.region,endpoint:e.endpoint,credentials:e.credentials,tableName:e.tableName};this.driver=Zt(t);let n={tableName:e.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=zl(n),this.queryBuilderOptions={config:t}}setClient(e){return this.queryBuilderOptions.client=e,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let e=await dg({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),t=[];for(let[,n]of e.models)this.registerParsedModel(n),t.push(n);return t}registerModel(e){let t=this.parseWithTooling(e);return this.registerParsedModel(t)}registerParsedModel(e){this.models.set(e.name,e);let t=this.toSingleTableEntity(e);this.singleTableManager.registerEntity(t);let n=this.toEntityMapping(e);return this.driver.registerEntity(n),e}registerModels(e){return e.map((t)=>this.registerModel(t))}getModel(e){return this.models.get(e)}getAllModels(){return Array.from(this.models.values())}repository(e){if(!this.models.get(e))throw Error(`Model not found: ${e}`);return Gl(this.singleTableManager,e,this.queryBuilderOptions)}query(e){if(!this.models.get(e))throw Error(`Model not found: ${e}`);return new Vt(this.queryBuilderOptions).table(this.config.tableName).entity(e)}item(e){if(!this.models.get(e))throw Error(`Model not found: ${e}`);return new Dt(this.queryBuilderOptions).table(this.config.tableName)}buildKey(e,t){let n=this.models.get(e);if(!n)throw Error(`Model not found: ${e}`);let r=Yl(n.keyPatterns,t);return{pk:r.pk,sk:r.sk}}createItem(e,t){let n=this.models.get(e);if(!n)throw Error(`Model not found: ${e}`);let r=Yl(n.keyPatterns,t),s=r.pk,i=r.sk,o={[this.config.pkAttribute]:s,[this.config.skAttribute]:i,[this.config.entityTypeAttribute]:n.name,...t};if(n.hasTimestamps){let l=new Date().toISOString();if(!o.createdAt)o.createdAt=l;o.updatedAt=l}if(n.hasVersioning){if(!o._v)o._v=1}return o}parseItem(e){let t=e[this.config.entityTypeAttribute];if(!t)return;let{[this.config.pkAttribute]:n,[this.config.skAttribute]:r,[this.config.entityTypeAttribute]:s,...i}=e;return{type:t,data:i}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(e){let t=this.models.get(e);if(!t)throw Error(`Model not found: ${e}`);return t.accessPatterns}parseWithTooling(e){let t=e.name.toUpperCase(),n=e.primaryKey??"id",r=this.config.keyDelimiter,s=this.parseAttributes(e),i=this.parseRelationships(e,n),o={pk:`${t}${r}{${n}}`,sk:`${t}${r}{${n}}`,...this.deriveGSIKeyPatterns(t,n,r,i)},l=this.deriveAccessPatterns(e.name,t,n,i);return{name:e.name,entityType:t,primaryKey:n,attributes:s,relationships:i,keyPatterns:o,accessPatterns:l,traits:e.traits??{},hasTimestamps:e.traits?.useTimestamps??!1,hasSoftDeletes:e.traits?.useSoftDeletes??!1,hasUuid:e.traits?.useUuid??!1,hasTtl:e.traits?.useTtl??!1,hasVersioning:e.traits?.useVersioning??!1,original:e}}parseAttributes(e){let t=[];if(t.push({name:e.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),e.attributes)for(let[n,r]of Object.entries(e.attributes))t.push({name:n,fillable:r.fillable??!0,required:r.required??!1,nullable:r.nullable??!0,unique:r.unique??!1,hidden:r.hidden??!1,defaultValue:r.default,cast:r.cast,dynamoDbType:this.inferDynamoDBType(r)});if(e.traits?.useTimestamps)t.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(e.traits?.useSoftDeletes)t.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return t}inferDynamoDBType(e){if(e.cast){let t=e.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(t))return"N";if(["boolean","bool"].includes(t))return"BOOL";if(["array","list"].includes(t))return"L";if(["object","json","map"].includes(t))return"M"}if(e.validation?.rule){let t=String(e.validation.rule);if(t.includes("integer")||t.includes("numeric")||t.includes("number"))return"N";if(t.includes("boolean"))return"BOOL";if(t.includes("array"))return"L";if(t.includes("object"))return"M"}return"S"}parseRelationships(e,t){let n=[];if(e.hasOne)for(let r of e.hasOne)n.push({type:"hasOne",relatedModel:r,foreignKey:`${e.name.toLowerCase()}Id`,localKey:t,requiresGsi:!0});if(e.hasMany)for(let r of e.hasMany)n.push({type:"hasMany",relatedModel:r,foreignKey:`${e.name.toLowerCase()}Id`,localKey:t,requiresGsi:!1});if(e.belongsTo)for(let r of e.belongsTo)n.push({type:"belongsTo",relatedModel:r,foreignKey:`${r.toLowerCase()}Id`,localKey:t,requiresGsi:!0});if(e.belongsToMany){let r=Array.isArray(e.belongsToMany)?e.belongsToMany:Object.values(e.belongsToMany);for(let s of r){let i=typeof s==="string"?s:s?.model;if(!i)continue;let o=[e.name,i].sort();n.push({type:"belongsToMany",relatedModel:i,foreignKey:`${e.name.toLowerCase()}Id`,localKey:t,pivotEntity:o.join(""),requiresGsi:!0})}}return n}deriveGSIKeyPatterns(e,t,n,r){let s={},i=1;for(let o of r)if(o.requiresGsi&&i<=5)s[`gsi${i}pk`]=`${o.relatedModel.toUpperCase()}${n}{${o.foreignKey}}`,s[`gsi${i}sk`]=`${e}${n}{${t}}`,o.gsiIndex=i,i++;return s}deriveAccessPatterns(e,t,n,r){let s=[];s.push({name:`Get ${e} by ID`,description:`Retrieve a single ${e} by its primary key`,entityType:t,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${t}#123`,exampleSk:`${t}#123`,efficient:!0}),s.push({name:`List all ${e}s`,description:`Scan all ${e} entities`,entityType:t,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:t,efficient:!1});for(let i of r){if(i.type==="hasMany")s.push({name:`Get ${i.relatedModel}s for ${e}`,description:`Query ${i.relatedModel}s related to a ${e}`,entityType:t,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${t}#123`,exampleSk:`${i.relatedModel.toUpperCase()}#`,efficient:!0});if(i.gsiIndex){let o=`GSI${i.gsiIndex}`;s.push({name:`Get ${e}s by ${i.relatedModel}`,description:`Query ${e}s by their related ${i.relatedModel}`,entityType:t,operation:"query",index:o,keyCondition:`gsi${i.gsiIndex}pk = :pk`,examplePk:`${i.relatedModel.toUpperCase()}#123`,efficient:!0})}}return s}toSingleTableEntity(e){let t=this.extractKeyFields(e.keyPatterns.pk);return{name:e.name,pkPattern:e.keyPatterns.pk,skPattern:e.keyPatterns.sk,keyFields:t,indexes:this.extractGSIPatterns(e.keyPatterns)}}extractKeyFields(e){let t=e.match(/\{([^}]+)\}/g);if(!t)return[];return t.map((n)=>n.slice(1,-1))}extractGSIPatterns(e){let t=[];for(let n=1;n<=5;n++){let r=`gsi${n}pk`,s=`gsi${n}sk`;if(e[r])t.push({name:`GSI${n}`,pkPattern:e[r],skPattern:e[s]})}return t.length>0?t:void 0}toEntityMapping(e){return{entityType:e.name,pkPattern:e.keyPatterns.pk,skPattern:e.keyPatterns.sk}}buildGSIConfig(){let e=this.config.gsiConfig??{},t=[];if(e.gsi1pk)t.push({name:"GSI1",pkAttribute:e.gsi1pk,skAttribute:e.gsi1sk});if(e.gsi2pk)t.push({name:"GSI2",pkAttribute:e.gsi2pk,skAttribute:e.gsi2sk});if(e.gsi3pk)t.push({name:"GSI3",pkAttribute:e.gsi3pk,skAttribute:e.gsi3sk});return t}}function Mw(e){return new Xl(e)}function Ow(e){return e.accessPatterns}function Bw(e,t="#"){let n=e.name.toUpperCase(),r=e.primaryKey??"id";return{name:e.name,pkPattern:`${n}${t}\${${r}}`,skPattern:`${n}${t}\${${r}}`}}jt();function as(e){let t={};for(let n of Object.keys(e)){let r=e[n],s=r.definition??r.getDefinition?.()??r,i=Ft(s),o=s.attributes??{},l={};for(let a of Object.keys(o))l[a]=void 0;t[i]={columns:l,primaryKey:s.primaryKey??"id"}}return t}$i();jt();import{readdirSync as fg}from"fs";import{basename as Zl,extname as ec,isAbsolute as mg,join as tc}from"path";import gg from"process";var yg=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function hg(e){let t=ec(e);if(!yg.has(t))return!1;let n=Zl(e,t);if(n.startsWith("_")||n==="index")return!1;return!n.endsWith(".d")}function pg(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.name==="string"||typeof t.table==="string"}function nc(e){let t=[],n=fg(e,{withFileTypes:!0}).sort((r,s)=>r.name.localeCompare(s.name));for(let r of n){let s=tc(e,r.name);if(r.isDirectory()){t.push(...nc(s));continue}if(hg(r.name))t.push(s)}return t}async function mt(e){let t=e.cwd??gg.cwd(),n=mg(e.modelsDir)?e.modelsDir:tc(t,e.modelsDir),r={};for(let s of nc(n)){let i=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await import(`${s}${i}`),l=o.default??o,a=l.definition??l.getDefinition?.()??l;if(!pg(a))continue;let c=a.name??Zl(s,ec(s));r[c]={...a,name:c}}return r}jt();ds();function rc(e){let t={},n={},r={},s={},i={},o={};for(let l of Object.keys(e)){let a=e[l],c=a.definition??a.getDefinition?.()??a,u=Ft(c);t[l]=u,n[u]=l,r[u]=c.primaryKey??"id";let m=[];for(let[y,b]of Object.entries(c.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(b?.type??"")))m.push(y);let h=c.traits??{};if(h.useTimestamps??h.timestampable)m.push("created_at","updated_at");if(m.length>0)o[u]=[...new Set(m)];let w=(y)=>{if(!y)return{};let b={};if(Array.isArray(y)){for(let g of y){let p=us(g);if(p)b[p.model]=p.model}return b}if(typeof y==="object"){for(let[g,p]of Object.entries(y)){let E=us(p);if(E)b[g]=E.model}return b}return{}},N=(y)=>{if(!y)return{};if(Array.isArray(y)){let b={};for(let g of y)if(typeof g==="string")b[g]=g;else if(g&&typeof g==="object"&&typeof g.model==="string")b[g.model]=g;return b}return y},R=(y)=>{if(!y)return{};return y};if(s[u]={hasOne:w(c.hasOne),hasMany:w(c.hasMany),belongsTo:w(c.belongsTo),belongsToMany:N(c.belongsToMany),hasOneThrough:R(c.hasOneThrough),hasManyThrough:R(c.hasManyThrough),morphOne:w(c.morphOne),morphMany:w(c.morphMany),morphTo:c.morphTo,morphToMany:w(c.morphToMany),morphedByMany:w(c.morphedByMany)},c.scopes&&typeof c.scopes==="object"){i[u]={};for(let y of Object.keys(c.scopes)){let b=c.scopes[y];if(typeof b==="function")i[u][y]=b}}}return{modelToTable:t,tableToModel:n,primaryKeys:r,relations:s,scopes:i,models:e,temporalColumns:o}}ds();jt();Me();import{existsSync as Ki,mkdirSync as bg,readdirSync as Tg,readFileSync as wg,writeFileSync as Dg}from"fs";import{dirname as sc,join as ys}from"path";import cc from"process";function Ke(e){if(_.verbose)console.log(e)}function Jt(e){return e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function Oi(e){return qt(_.relations?.singularizeStrategy)(e)}var rr=0,Bt=0,Ht=0,hs=!0,ps=[],An=null;function uc(){return[...ps]}function Sg(e){let t=e;while(t!==sc(t)){if(Ki(ys(t,"package.json")))return t;t=sc(t)}return cc.cwd()}function $g(){let e=Sg(cc.cwd()),t=At(e,_.migrationDir);if(!Ki(t))bg(t,{recursive:!0}),Ke(`-- Created SQL directory: ${t}`);return t}var dc="-- qb:generated";function fc(e){return e.trimStart().startsWith(dc)}function mc(e){return e.split(`
432
+ `,[c.table])).map((N)=>({name:N.column_name,type:N.data_type.toLowerCase()}));let m=u.map((w)=>w.name),h=c.columns.map((w)=>w.name);for(let w of c.columns)if(!m.includes(w.name))n.push({type:"missing_column",severity:"error",table:c.table,column:w.name,expected:w.type,message:`Column '${c.table}.${w.name}' defined in model but not found in database`});for(let w of u)if(!h.includes(w.name))n.push({type:"extra_column",severity:"warning",table:c.table,column:w.name,actual:w.type,message:`Column '${c.table}.${w.name}' exists in database but not defined in model`});for(let w of c.columns){let N=u.find((R)=>R.name===w.name);if(N){let R=(g)=>g.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim(),y=R(w.type),b=R(N.type);if(y!==b)n.push({type:"type_mismatch",severity:"warning",table:c.table,column:w.name,expected:w.type,actual:N.type,message:`Column '${c.table}.${w.name}' type mismatch: expected '${w.type}', found '${N.type}'`})}}}let a=n.filter((c)=>c.severity==="error").length===0;if(a&&n.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${n.length} issue(s)`),console.log();let c=n.filter((m)=>m.severity==="error"),u=n.filter((m)=>m.severity==="warning");if(c.length>0){console.log(`\u2717 Errors (${c.length}):`);for(let m of c)console.log(` - ${m.message}`);console.log()}if(u.length>0){console.log(`\u26A0 Warnings (${u.length}):`);for(let m of u)console.log(` - ${m.message}`);console.log()}if(!a)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:a,issues:n}}catch(r){throw console.error("-- Schema validation failed:",r),r}}async function Vm(e){return wl(e)}async function Jm(e={}){let t=Number(e.attempts||10),n=Number(e.delay||100),r=ie();try{return await r.waitForReady({attempts:t,delayMs:n}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}Fl();tr();Me();class Jt{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(e){this.driver=Zt(e.config),this.client=e.client,this.tableName=e.config.tableName??""}table(e){return this.tableName=e,this}index(e){return this.indexName=e,this}entity(e){return this.entityType=e,this}whereKey(e,t,n){return this.keyConditions.push({attribute:e,operator:t,value:n}),this}wherePartitionKey(e,t){return this.whereKey(e,"=",t)}whereSortKey(e,t){return this.whereKey(e,"=",t)}whereSortKeyBeginsWith(e,t){return this.keyConditions.push({attribute:e,operator:"begins_with",value:t}),this}whereSortKeyBetween(e,t,n){return this.keyConditions.push({attribute:e,operator:"BETWEEN",values:[t,n]}),this}where(e,t,n){return this.filterConditions.push({attribute:e,operator:t,value:n}),this}whereEquals(e,t){return this.where(e,"=",t)}whereLessThan(e,t){return this.where(e,"<",t)}whereLessThanOrEqual(e,t){return this.where(e,"<=",t)}whereGreaterThan(e,t){return this.where(e,">",t)}whereGreaterThanOrEqual(e,t){return this.where(e,">=",t)}whereBetween(e,t,n){return this.filterConditions.push({attribute:e,operator:"BETWEEN",values:[t,n]}),this}whereBeginsWith(e,t){return this.filterConditions.push({attribute:e,operator:"begins_with",value:t}),this}whereContains(e,t){return this.where(e,"contains",t)}whereExists(e){return this.where(e,"attribute_exists")}whereNotExists(e){return this.where(e,"attribute_not_exists")}whereIn(e,t){return this.filterConditions.push({attribute:e,operator:"IN",values:t}),this}select(...e){return this.projectionAttrs.push(...e),this}limit(e){return this.limitValue=e,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(e=!0){return this.consistentReadValue=e,this}startFrom(e){return this.startKey=e,this}buildQueryParams(){return this.driver.buildQueryParams({tableName:this.tableName,indexName:this.indexName,keyConditions:this.keyConditions,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,scanIndexForward:this.scanForward,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}buildScanParams(){return this.driver.buildScanParams({tableName:this.tableName,indexName:this.indexName,filterConditions:this.filterConditions.length>0?this.filterConditions:void 0,projectionAttributes:this.projectionAttrs.length>0?this.projectionAttrs:void 0,limit:this.limitValue,exclusiveStartKey:this.startKey,consistentRead:this.consistentReadValue})}toQueryRequest(){let e=this.buildQueryParams(),t={TableName:e.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(e.indexName)t.IndexName=e.indexName;let n=0;if(e.keyConditions.length>0){let r=[];for(let s of e.keyConditions){let i=`#key${n}`;if(t.ExpressionAttributeNames[i]=s.attribute,s.operator==="begins_with"){let o=`:keyval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`begins_with(${i}, ${o})`)}else if(s.operator==="BETWEEN"){let o=`:keyval${n}a`,l=`:keyval${n}b`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.values?.[0]}).v,t.ExpressionAttributeValues[l]=this.driver.marshall({v:s.values?.[1]}).v,r.push(`${i} BETWEEN ${o} AND ${l}`)}else{let o=`:keyval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`${i} ${s.operator} ${o}`)}n++}t.KeyConditionExpression=r.join(" AND ")}if(e.filterConditions&&e.filterConditions.length>0){let r=[];for(let s of e.filterConditions){let i=`#flt${n}`;if(t.ExpressionAttributeNames[i]=s.attribute,s.operator==="attribute_exists")r.push(`attribute_exists(${i})`);else if(s.operator==="attribute_not_exists")r.push(`attribute_not_exists(${i})`);else if(s.operator==="begins_with"||s.operator==="contains"){let o=`:fltval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`${s.operator}(${i}, ${o})`)}else if(s.operator==="BETWEEN"){let o=`:fltval${n}a`,l=`:fltval${n}b`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.values?.[0]}).v,t.ExpressionAttributeValues[l]=this.driver.marshall({v:s.values?.[1]}).v,r.push(`${i} BETWEEN ${o} AND ${l}`)}else if(s.operator==="IN"){let o=(s.values??[]).map((l,a)=>`:fltval${n}_${a}`);s.values?.forEach((l,a)=>{t.ExpressionAttributeValues[`:fltval${n}_${a}`]=this.driver.marshall({v:l}).v}),r.push(`${i} IN (${o.join(", ")})`)}else{let o=`:fltval${n}`;t.ExpressionAttributeValues[o]=this.driver.marshall({v:s.value}).v,r.push(`${i} ${s.operator} ${o}`)}n++}t.FilterExpression=r.join(" AND ")}if(e.projectionAttributes&&e.projectionAttributes.length>0){let r=[];for(let s of e.projectionAttributes){let i=`#proj${n}`;t.ExpressionAttributeNames[i]=s,r.push(i),n++}t.ProjectionExpression=r.join(", ")}if(e.limit!==void 0)t.Limit=e.limit;if(e.scanIndexForward!==void 0)t.ScanIndexForward=e.scanIndexForward;if(e.exclusiveStartKey)t.ExclusiveStartKey=this.driver.marshall(e.exclusiveStartKey);if(e.consistentRead)t.ConsistentRead=e.consistentRead;if(Object.keys(t.ExpressionAttributeNames).length===0)delete t.ExpressionAttributeNames;if(Object.keys(t.ExpressionAttributeValues).length===0)delete t.ExpressionAttributeValues;return t}toScanRequest(){let e=this.buildScanParams(),t={TableName:e.tableName};if(e.indexName)t.IndexName=e.indexName;if(e.filterConditions&&e.filterConditions.length>0){let{expression:n,expressionAttributeNames:r,expressionAttributeValues:s}=this.driver.buildFilterExpression(e.filterConditions);t.FilterExpression=n,t.ExpressionAttributeNames=r,t.ExpressionAttributeValues=s}if(e.projectionAttributes&&e.projectionAttributes.length>0){let{expression:n,expressionAttributeNames:r}=this.driver.buildProjectionExpression(e.projectionAttributes);t.ProjectionExpression=n,t.ExpressionAttributeNames={...t.ExpressionAttributeNames,...r}}if(e.limit!==void 0)t.Limit=e.limit;if(e.exclusiveStartKey)t.ExclusiveStartKey=this.driver.marshall(e.exclusiveStartKey);if(e.consistentRead)t.ConsistentRead=e.consistentRead;return t}async query(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toQueryRequest() to get the request params.");let e=this.toQueryRequest(),t=await this.client.query(e);return{items:t.Items?.map((n)=>this.driver.unmarshall(n)),count:t.Count,scannedCount:t.ScannedCount,lastEvaluatedKey:t.LastEvaluatedKey?this.driver.unmarshall(t.LastEvaluatedKey):void 0,consumedCapacity:t.ConsumedCapacity}}async scan(){if(!this.client)throw Error("DynamoDB client not provided. Pass a client in options or use toScanRequest() to get the request params.");let e=this.toScanRequest(),t=await this.client.scan(e);return{items:t.Items?.map((n)=>this.driver.unmarshall(n)),count:t.Count,scannedCount:t.ScannedCount,lastEvaluatedKey:t.LastEvaluatedKey?this.driver.unmarshall(t.LastEvaluatedKey):void 0,consumedCapacity:t.ConsumedCapacity}}async getAll(){let e=[],t;do{if(t)this.startFrom(t);let n=this.keyConditions.length>0?await this.query():await this.scan();if(n.items)e.push(...n.items);t=n.lastEvaluatedKey}while(t);return e}async first(){return this.limit(1),(this.keyConditions.length>0?await this.query():await this.scan()).items?.[0]}async count(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return e.Select="COUNT",(this.keyConditions.length>0?await this.client.query(e):await this.client.scan(e)).Count??0}reset(){return this.indexName=void 0,this.entityType=void 0,this.keyConditions=[],this.filterConditions=[],this.projectionAttrs=[],this.limitValue=void 0,this.scanForward=!0,this.consistentReadValue=!1,this.startKey=void 0,this}}class St{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(e){this.driver=Zt(e.config),this.client=e.client,this.tableName=e.config.tableName??""}table(e){return this.tableName=e,this}key(e){return this.keyData=e,this}item(e){return this.itemData=e,this}set(e,t){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[e]=t,this}setMany(e){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,e),this}remove(e){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(e),this}add(e,t){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[e]=t,this}deleteFromSet(e,t){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[e]=t,this}condition(e){return this.conditionExpr=e,this}ifNotExists(e="pk"){return this.conditionExpr=`attribute_not_exists(${e})`,this}ifExists(e="pk"){return this.conditionExpr=`attribute_exists(${e})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let e={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)e.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")e.ReturnValues=this.returnValuesOption;return e}toUpdateRequest(){let e={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:t,expressionAttributeNames:n,expressionAttributeValues:r}=this.driver.buildUpdateExpression(this.updateExpressions);if(t)e.UpdateExpression=t,e.ExpressionAttributeNames=n,e.ExpressionAttributeValues=r;if(this.conditionExpr)e.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")e.ReturnValues=this.returnValuesOption;return e}toDeleteRequest(){let e={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)e.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")e.ReturnValues=this.returnValuesOption;return e}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toPutRequest(),t=await this.client.putItem(e);if(t.Attributes)return this.driver.unmarshall(t.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toUpdateRequest(),t=await this.client.updateItem(e);if(t.Attributes)return this.driver.unmarshall(t.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toDeleteRequest(),t=await this.client.deleteItem(e);if(t.Attributes)return this.driver.unmarshall(t.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let e=this.toGetRequest(),t=await this.client.getItem(e);if(t.Item)return this.driver.unmarshall(t.Item);return}}function bw(e){return new Jt(e)}function Tw(e){return new St(e)}function ww(e){let t=Zt(e.config);return{query:()=>new Jt(e),item:()=>new St(e),driver:t,registerEntity:(n)=>t.registerEntity(n),buildKey:(n,r)=>t.buildPrimaryKey(n,r)}}class Jl{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(e){this.config=e,this.pkAttribute=e.pkAttribute??"pk",this.skAttribute=e.skAttribute??"sk",this.typeAttribute=e.typeAttribute??"_type";for(let t of e.entities)this.entities.set(t.name,t)}getEntity(e){return this.entities.get(e)}registerEntity(e){this.entities.set(e.name,e)}buildKey(e,t){let n=this.entities.get(e);if(!n)throw Error(`Entity not found: ${e}`);let r=this.interpolatePattern(n.pkPattern,t),s=this.interpolatePattern(n.skPattern,t);return{pk:r,sk:s}}buildGSIKey(e,t,n){let r=this.entities.get(e);if(!r)throw Error(`Entity not found: ${e}`);let s=r.indexes?.find((l)=>l.name===t);if(!s)throw Error(`GSI not found: ${t} for entity ${e}`);let i=this.interpolatePattern(s.pkPattern,n),o=s.skPattern?this.interpolatePattern(s.skPattern,n):void 0;return{pk:i,sk:o}}createItem(e,t){let{pk:n,sk:r}=this.buildKey(e,t),s=this.entities.get(e),i={[this.pkAttribute]:n,[this.skAttribute]:r,[this.typeAttribute]:e,...t};if(s.indexes)for(let o of s.indexes){let l=this.buildGSIKey(e,o.name,t),a=this.config.indexes?.find((c)=>c.name===o.name);if(a){if(i[a.pkAttribute]=l.pk,a.skAttribute&&l.sk)i[a.skAttribute]=l.sk}}return i}parseEntityType(e){if(e[this.typeAttribute])return e[this.typeAttribute];let t=e[this.pkAttribute];if(!t)return;for(let[n,r]of this.entities){let s=r.pkPattern.split("${")[0];if(t.startsWith(s))return n}return}parseItem(e){let t=this.parseEntityType(e);if(!t)return;let{[this.pkAttribute]:n,[this.skAttribute]:r,[this.typeAttribute]:s,...i}=e;return{type:t,data:i}}getEntityPrefix(e){let t=this.entities.get(e);if(!t)throw Error(`Entity not found: ${e}`);return t.pkPattern.split("${")[0]}generateTableDefinition(){let e=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],t=[];if(this.config.indexes)for(let n of this.config.indexes){if(!e.find((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.find((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});t.push({indexName:n.name,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:t.length>0?t:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(e,t){return e.replace(/\$\{(\w+)\}/g,(n,r)=>{if(!(r in t))throw Error(`Missing value for pattern key: ${r}`);return String(t[r])})}}class Hl{manager;entityName;options;constructor(e,t,n){this.manager=e,this.entityName=t,this.options=n}async create(e){let t=this.manager.createItem(this.entityName,e),n=new St(this.options).table(this.options.config.tableName).item(t).ifNotExists("pk");if(this.options.client)await n.put();return e}async get(e){let{pk:t,sk:n}=this.manager.buildKey(this.entityName,e),r=new St(this.options).table(this.options.config.tableName).key({pk:t,sk:n});if(!this.options.client)throw Error("DynamoDB client not provided");let s=await r.get();if(!s)return;return this.manager.parseItem(s)?.data}async update(e,t){let{pk:n,sk:r}=this.manager.buildKey(this.entityName,e),s=new St(this.options).table(this.options.config.tableName).key({pk:n,sk:r}).setMany(t).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let i=await s.update();if(!i)return;return this.manager.parseItem(i)?.data}async delete(e){let{pk:t,sk:n}=this.manager.buildKey(this.entityName,e),r=new St(this.options).table(this.options.config.tableName).key({pk:t,sk:n});if(!this.options.client)throw Error("DynamoDB client not provided");return await r.delete(),!0}query(){return new zl(this.manager,this.entityName,this.options)}async findAll(){let e=this.manager.typeAttribute??"_type",t=new Jt(this.options).table(this.options.config.tableName).whereEquals(e,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await t.getAll()).map((r)=>this.manager.parseItem(r)).filter((r)=>r!==void 0).map((r)=>r.data)}}class zl{manager;entityName;options;builder;pkValue;skConditions=[];constructor(e,t,n){this.manager=e,this.entityName=t,this.options=n,this.builder=new Jt(n).table(n.config.tableName)}wherePartitionKey(e){let{pk:t}=this.manager.buildKey(this.entityName,e);this.pkValue=t;let n=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(n,t),this}whereSortKey(e){let{sk:t}=this.manager.buildKey(this.entityName,e),n=this.manager.skAttribute??"sk";return this.builder.whereSortKey(n,t),this}whereSortKeyBeginsWith(e){let t=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(t,e),this}useIndex(e,t){let n=this.manager.buildGSIKey(this.entityName,e,t),r=this.manager.config.indexes?.find((s)=>s.name===e);if(!r)throw Error(`GSI configuration not found: ${e}`);return this.builder.index(e),this.builder.wherePartitionKey(r.pkAttribute,n.pk),this}where(e,t,n){return this.builder.where(e,t,n),this}select(...e){return this.builder.select(...e),this}limit(e){return this.builder.limit(e),this}descending(){return this.builder.descending(),this}async execute(){if(!this.options.client)throw Error("DynamoDB client not provided");return((await this.builder.query()).items??[]).map((t)=>this.manager.parseItem(t)).filter((t)=>t!==void 0).map((t)=>t.data)}async first(){return this.limit(1),(await this.execute())[0]}}function Gl(e){return new Jl(e)}function Yl(e,t,n){return new Hl(e,t,n)}var $w={simpleEntity:(e,t="id")=>({name:e,pkPattern:`${e.toUpperCase()}#\${${t}}`,skPattern:"METADATA",keyFields:[t]}),oneToMany:(e,t,n="id",r="id")=>({parent:{name:e,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:"METADATA",keyFields:[n]},child:{name:t,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:`${t.toUpperCase()}#\${${r}}`,keyFields:[n,r]}}),manyToMany:(e,t,n="id",r="relatedId")=>({entity:{name:e,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:"METADATA",keyFields:[n]},relation:{name:t,pkPattern:`${e.toUpperCase()}#\${${n}}`,skPattern:`${t.toUpperCase()}#\${${r}}`,keyFields:[n,r],indexes:[{name:"GSI1",pkPattern:`${e.toUpperCase()}#\${${r}}`,skPattern:`${t.toUpperCase()}#\${${n}}`}]}}),hierarchical:(e,t="rootId",n="path")=>({name:e,pkPattern:`ROOT#\${${t}}`,skPattern:`PATH#\${${n}}`,keyFields:[t,n]})};function Xl(e,t){let n={};for(let[r,s]of Object.entries(e))if(s)n[r]=s.replace(/\{([^}]+)\}/g,(i,o)=>t[o]!==void 0?String(t[o]):`{${o}}`);return n}async function fg(e){return{models:new Map}}function xw(e){return e}function Rw(e){return e}function kw(e){return e}function Cw(e){return e}class Zl{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(e){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...e};let t={region:e.region,endpoint:e.endpoint,credentials:e.credentials,tableName:e.tableName};this.driver=Zt(t);let n={tableName:e.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=Gl(n),this.queryBuilderOptions={config:t}}setClient(e){return this.queryBuilderOptions.client=e,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let e=await fg({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),t=[];for(let[,n]of e.models)this.registerParsedModel(n),t.push(n);return t}registerModel(e){let t=this.parseWithTooling(e);return this.registerParsedModel(t)}registerParsedModel(e){this.models.set(e.name,e);let t=this.toSingleTableEntity(e);this.singleTableManager.registerEntity(t);let n=this.toEntityMapping(e);return this.driver.registerEntity(n),e}registerModels(e){return e.map((t)=>this.registerModel(t))}getModel(e){return this.models.get(e)}getAllModels(){return Array.from(this.models.values())}repository(e){if(!this.models.get(e))throw Error(`Model not found: ${e}`);return Yl(this.singleTableManager,e,this.queryBuilderOptions)}query(e){if(!this.models.get(e))throw Error(`Model not found: ${e}`);return new Jt(this.queryBuilderOptions).table(this.config.tableName).entity(e)}item(e){if(!this.models.get(e))throw Error(`Model not found: ${e}`);return new St(this.queryBuilderOptions).table(this.config.tableName)}buildKey(e,t){let n=this.models.get(e);if(!n)throw Error(`Model not found: ${e}`);let r=Xl(n.keyPatterns,t);return{pk:r.pk,sk:r.sk}}createItem(e,t){let n=this.models.get(e);if(!n)throw Error(`Model not found: ${e}`);let r=Xl(n.keyPatterns,t),s=r.pk,i=r.sk,o={[this.config.pkAttribute]:s,[this.config.skAttribute]:i,[this.config.entityTypeAttribute]:n.name,...t};if(n.hasTimestamps){let l=new Date().toISOString();if(!o.createdAt)o.createdAt=l;o.updatedAt=l}if(n.hasVersioning){if(!o._v)o._v=1}return o}parseItem(e){let t=e[this.config.entityTypeAttribute];if(!t)return;let{[this.config.pkAttribute]:n,[this.config.skAttribute]:r,[this.config.entityTypeAttribute]:s,...i}=e;return{type:t,data:i}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(e){let t=this.models.get(e);if(!t)throw Error(`Model not found: ${e}`);return t.accessPatterns}parseWithTooling(e){let t=e.name.toUpperCase(),n=e.primaryKey??"id",r=this.config.keyDelimiter,s=this.parseAttributes(e),i=this.parseRelationships(e,n),o={pk:`${t}${r}{${n}}`,sk:`${t}${r}{${n}}`,...this.deriveGSIKeyPatterns(t,n,r,i)},l=this.deriveAccessPatterns(e.name,t,n,i);return{name:e.name,entityType:t,primaryKey:n,attributes:s,relationships:i,keyPatterns:o,accessPatterns:l,traits:e.traits??{},hasTimestamps:e.traits?.useTimestamps??!1,hasSoftDeletes:e.traits?.useSoftDeletes??!1,hasUuid:e.traits?.useUuid??!1,hasTtl:e.traits?.useTtl??!1,hasVersioning:e.traits?.useVersioning??!1,original:e}}parseAttributes(e){let t=[];if(t.push({name:e.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),e.attributes)for(let[n,r]of Object.entries(e.attributes))t.push({name:n,fillable:r.fillable??!0,required:r.required??!1,nullable:r.nullable??!0,unique:r.unique??!1,hidden:r.hidden??!1,defaultValue:r.default,cast:r.cast,dynamoDbType:this.inferDynamoDBType(r)});if(e.traits?.useTimestamps)t.push({name:"createdAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"},{name:"updatedAt",fillable:!1,required:!0,nullable:!1,unique:!1,hidden:!1,dynamoDbType:"S"});if(e.traits?.useSoftDeletes)t.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return t}inferDynamoDBType(e){if(e.cast){let t=e.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(t))return"N";if(["boolean","bool"].includes(t))return"BOOL";if(["array","list"].includes(t))return"L";if(["object","json","map"].includes(t))return"M"}if(e.validation?.rule){let t=String(e.validation.rule);if(t.includes("integer")||t.includes("numeric")||t.includes("number"))return"N";if(t.includes("boolean"))return"BOOL";if(t.includes("array"))return"L";if(t.includes("object"))return"M"}return"S"}parseRelationships(e,t){let n=[];if(e.hasOne)for(let r of e.hasOne)n.push({type:"hasOne",relatedModel:r,foreignKey:`${e.name.toLowerCase()}Id`,localKey:t,requiresGsi:!0});if(e.hasMany)for(let r of e.hasMany)n.push({type:"hasMany",relatedModel:r,foreignKey:`${e.name.toLowerCase()}Id`,localKey:t,requiresGsi:!1});if(e.belongsTo)for(let r of e.belongsTo)n.push({type:"belongsTo",relatedModel:r,foreignKey:`${r.toLowerCase()}Id`,localKey:t,requiresGsi:!0});if(e.belongsToMany){let r=Array.isArray(e.belongsToMany)?e.belongsToMany:Object.values(e.belongsToMany);for(let s of r){let i=typeof s==="string"?s:s?.model;if(!i)continue;let o=[e.name,i].sort();n.push({type:"belongsToMany",relatedModel:i,foreignKey:`${e.name.toLowerCase()}Id`,localKey:t,pivotEntity:o.join(""),requiresGsi:!0})}}return n}deriveGSIKeyPatterns(e,t,n,r){let s={},i=1;for(let o of r)if(o.requiresGsi&&i<=5)s[`gsi${i}pk`]=`${o.relatedModel.toUpperCase()}${n}{${o.foreignKey}}`,s[`gsi${i}sk`]=`${e}${n}{${t}}`,o.gsiIndex=i,i++;return s}deriveAccessPatterns(e,t,n,r){let s=[];s.push({name:`Get ${e} by ID`,description:`Retrieve a single ${e} by its primary key`,entityType:t,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${t}#123`,exampleSk:`${t}#123`,efficient:!0}),s.push({name:`List all ${e}s`,description:`Scan all ${e} entities`,entityType:t,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:t,efficient:!1});for(let i of r){if(i.type==="hasMany")s.push({name:`Get ${i.relatedModel}s for ${e}`,description:`Query ${i.relatedModel}s related to a ${e}`,entityType:t,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${t}#123`,exampleSk:`${i.relatedModel.toUpperCase()}#`,efficient:!0});if(i.gsiIndex){let o=`GSI${i.gsiIndex}`;s.push({name:`Get ${e}s by ${i.relatedModel}`,description:`Query ${e}s by their related ${i.relatedModel}`,entityType:t,operation:"query",index:o,keyCondition:`gsi${i.gsiIndex}pk = :pk`,examplePk:`${i.relatedModel.toUpperCase()}#123`,efficient:!0})}}return s}toSingleTableEntity(e){let t=this.extractKeyFields(e.keyPatterns.pk);return{name:e.name,pkPattern:e.keyPatterns.pk,skPattern:e.keyPatterns.sk,keyFields:t,indexes:this.extractGSIPatterns(e.keyPatterns)}}extractKeyFields(e){let t=e.match(/\{([^}]+)\}/g);if(!t)return[];return t.map((n)=>n.slice(1,-1))}extractGSIPatterns(e){let t=[];for(let n=1;n<=5;n++){let r=`gsi${n}pk`,s=`gsi${n}sk`;if(e[r])t.push({name:`GSI${n}`,pkPattern:e[r],skPattern:e[s]})}return t.length>0?t:void 0}toEntityMapping(e){return{entityType:e.name,pkPattern:e.keyPatterns.pk,skPattern:e.keyPatterns.sk}}buildGSIConfig(){let e=this.config.gsiConfig??{},t=[];if(e.gsi1pk)t.push({name:"GSI1",pkAttribute:e.gsi1pk,skAttribute:e.gsi1sk});if(e.gsi2pk)t.push({name:"GSI2",pkAttribute:e.gsi2pk,skAttribute:e.gsi2sk});if(e.gsi3pk)t.push({name:"GSI3",pkAttribute:e.gsi3pk,skAttribute:e.gsi3sk});return t}}function Bw(e){return new Zl(e)}function Pw(e){return e.accessPatterns}function _w(e,t="#"){let n=e.name.toUpperCase(),r=e.primaryKey??"id";return{name:e.name,pkPattern:`${n}${t}\${${r}}`,skPattern:`${n}${t}\${${r}}`}}Wt();function as(e){let t={};for(let n of Object.keys(e)){let r=e[n],s=r.definition??r.getDefinition?.()??r,i=qt(s),o=s.attributes??{},l={};for(let a of Object.keys(o))l[a]=void 0;t[i]={columns:l,primaryKey:s.primaryKey??"id"}}return t}Ri();Wt();import{readdirSync as mg}from"fs";import{basename as ec,extname as tc,isAbsolute as gg,join as nc}from"path";import yg from"process";var hg=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function pg(e){let t=tc(e);if(!hg.has(t))return!1;let n=ec(e,t);if(n.startsWith("_")||n==="index")return!1;return!n.endsWith(".d")}function bg(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.name==="string"||typeof t.table==="string"}function rc(e){let t=[],n=mg(e,{withFileTypes:!0}).sort((r,s)=>r.name.localeCompare(s.name));for(let r of n){let s=nc(e,r.name);if(r.isDirectory()){t.push(...rc(s));continue}if(pg(r.name))t.push(s)}return t}async function mt(e){let t=e.cwd??yg.cwd(),n=gg(e.modelsDir)?e.modelsDir:nc(t,e.modelsDir),r={};for(let s of rc(n)){let i=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await import(`${s}${i}`),l=o.default??o,a=l.definition??l.getDefinition?.()??l;if(!bg(a))continue;let c=a.name??ec(s,tc(s));r[c]={...a,name:c}}return r}Wt();ds();function sc(e){let t={},n={},r={},s={},i={},o={};for(let l of Object.keys(e)){let a=e[l],c=a.definition??a.getDefinition?.()??a,u=qt(c);t[l]=u,n[u]=l,r[u]=c.primaryKey??"id";let m=[];for(let[y,b]of Object.entries(c.attributes??{}))if(/^(?:datetime|timestamp|timestamptz|date)$/i.test(String(b?.type??"")))m.push(y);let h=c.traits??{};if(h.useTimestamps??h.timestampable)m.push("created_at","updated_at");if(m.length>0)o[u]=[...new Set(m)];let w=(y)=>{if(!y)return{};let b={};if(Array.isArray(y)){for(let g of y){let p=us(g);if(p)b[p.model]=p.model}return b}if(typeof y==="object"){for(let[g,p]of Object.entries(y)){let E=us(p);if(E)b[g]=E.model}return b}return{}},N=(y)=>{if(!y)return{};if(Array.isArray(y)){let b={};for(let g of y)if(typeof g==="string")b[g]=g;else if(g&&typeof g==="object"&&typeof g.model==="string")b[g.model]=g;return b}return y},R=(y)=>{if(!y)return{};return y};if(s[u]={hasOne:w(c.hasOne),hasMany:w(c.hasMany),belongsTo:w(c.belongsTo),belongsToMany:N(c.belongsToMany),hasOneThrough:R(c.hasOneThrough),hasManyThrough:R(c.hasManyThrough),morphOne:w(c.morphOne),morphMany:w(c.morphMany),morphTo:c.morphTo,morphToMany:w(c.morphToMany),morphedByMany:w(c.morphedByMany)},c.scopes&&typeof c.scopes==="object"){i[u]={};for(let y of Object.keys(c.scopes)){let b=c.scopes[y];if(typeof b==="function")i[u][y]=b}}}return{modelToTable:t,tableToModel:n,primaryKeys:r,relations:s,scopes:i,models:e,temporalColumns:o}}ds();Wt();Me();import{existsSync as Fi,mkdirSync as Tg,readdirSync as wg,readFileSync as Dg,writeFileSync as Sg}from"fs";import{dirname as ic,join as bs}from"path";import uc from"process";function Ke(e){if(_.verbose)console.log(e)}function Ht(e){return e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function Bi(e){return jt(_.relations?.singularizeStrategy)(e)}var rr=0,Pt=0,zt=0,Ts=!0,ws=[],Nn=null;function dc(){return[...ws]}function $g(e){let t=e;while(t!==ic(t)){if(Fi(bs(t,"package.json")))return t;t=ic(t)}return uc.cwd()}function Eg(){let e=$g(uc.cwd()),t=Nt(e,_.migrationDir);if(!Fi(t))Tg(t,{recursive:!0}),Ke(`-- Created SQL directory: ${t}`);return t}var fc="-- qb:generated";function mc(e){return e.trimStart().startsWith(fc)}function gc(e){return e.split(`
433
433
  `).filter((t)=>!t.trimStart().startsWith("--")).join(`
434
- `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function Eg(e){let t=new Set,n;try{n=Tg(e).filter((r)=>r.endsWith(".sql"))}catch{return t}for(let r of n)try{t.add(mc(wg(ys(e,r),"utf8")))}catch{}return t}function gc(e,t){if(!e)return!1;let n=$g();if(An===null)An=Eg(n);let r=mc(e);if(r.length>0&&An.has(r))return Ke(`-- Migration already in the corpus, not writing it again: ${t}`),!1;rr++;let s=hs?String(rr).padStart(10,"0"):String(Math.floor(Date.now()/1000)+rr),i=`${s}-${t}.sql`;if(!hs){let l=Number(s);while(Ki(ys(n,i)))l+=1,s=String(l),i=`${s}-${t}.sql`}let o=ys(n,i);return Dg(o,`${dc}
435
- ${e}`),Ke(`-- Migration file created: ${i}`),Bt++,ps.push(i),An?.add(r),!0}function xg(e,t){return e==="integer"&&t==="bigint"||e==="string"&&t==="text"}function ic(e){if(e.endsWith("_id"))return"bigint";if(e.endsWith("_at"))return"datetime";if(e.startsWith("is_")||e.startsWith("has_"))return"boolean";return}function oc(e){if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint"||e instanceof Date)return e;return}function Rg(e){if(e&&typeof e==="object"&&"name"in e){let t=e;if(t.name==="enum"||t.getRules&&Array.isArray(t.getRules())){if(t.enumValues&&Array.isArray(t.enumValues))return t.enumValues.map((n)=>String(n));if(t._values&&Array.isArray(t._values))return t._values.map((n)=>String(n));if(t.values&&Array.isArray(t.values))return t.values.map((n)=>String(n))}}if(e&&typeof e==="object"){let t=e,n=t.allowedValues||t.enumValues||t._values||t.values;if(Array.isArray(n)&&n.length>0)return n.map((r)=>String(r))}return}function Pi(e){if(!e?.rules||!Array.isArray(e.rules))return;for(let t of e.rules)if(t?.name==="max"||t?.name==="maxLength"){if(t.params&&typeof t.params.max==="number")return t.params.max;if(Array.isArray(t.args)&&typeof t.args[0]==="number")return t.args[0];if(typeof t.value==="number")return t.value;if(typeof t.expectedValue==="number")return t.expectedValue}return}var _i=767;function kg(e){if(!e||typeof e!=="object")return;let t=e;if(t.name)switch(String(t.name).toLowerCase()){case"string":{let r=Pi(t);return r&&r>_i?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if(t.type){let n=String(t.type).toLowerCase();if(n==="string"||n==="text")return"string";if(n==="integer"||n==="int")return"integer";if(n==="bigint")return"bigint";if(n==="float")return"float";if(n==="number")return"integer";if(n==="boolean")return"boolean";if(n==="date")return"date";if(n==="datetime")return"datetime";if(n==="timestamptz"||n==="timestamp_tz")return"timestamptz";if(n==="json")return"json"}return}function Cg(e){if(typeof e!=="string")return;switch(e.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function Xn(e,t){let n=rc(e),r=[];for(let l of Object.keys(e)){let a=e[l],c=Ft(a),u=a.primaryKey??"id",m=a.autoIncrement!==!1,h=a.attributes??{},w=[],N=[];if(!h[u])w.push({name:Jt(u),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let R=new Map,y=Rn(a.belongsTo).length>0,b=new Set(Object.keys(h).map((C)=>Jt(C))),g=new Set;for(let C of b){if(!C.endsWith("_type"))continue;let k=`${C.slice(0,-5)}_id`;if(b.has(k))g.add(k)}for(let C of Rn(a.belongsTo)){let k=C.foreignKey??`${Jt(C.model)}_id`,P=n.modelToTable[C.model];if(P)R.set(k,{table:P,onDelete:C.onDelete})}for(let C of Object.keys(h)){let k=h[C],P=Jt(C),q=Boolean(k.validation?.rule?.isRequired),H=C===u?!1:k.nullable??!(k.required??q),M,V,U=C===u;if(M=Cg(k.type)??kg(k.validation?.rule),M==="string"){let Q=Pi(k.validation?.rule);if(Q&&Q>_i)M="text"}if(!M||M==="enum"){let Q=Rg(k.validation?.rule);if(Q&&Q.length>0)M="enum",V=Q}if(!M)M=ic(P);if(!M){let Q=oc(k.default);if(typeof Q==="string")M=Q.length>255?"text":"string";else if(typeof Q==="number")M=Number.isInteger(Q)?"integer":"float";else if(typeof Q==="boolean")M="boolean";else if(typeof Q==="bigint")M="bigint";else if(Q instanceof Date)M="datetime"}if(!M)M=U?"bigint":"string";let Y=M==="string"?Pi(k.validation?.rule):void 0,I={name:P,type:M,isPrimaryKey:U,isUnique:Boolean(k.unique),isNullable:H,hasDefault:typeof k.default<"u",defaultValue:oc(k.default),enumValues:V,maxLength:typeof Y==="number"&&Y>0&&Y<=_i?Y:void 0};if(P.endsWith("_id")&&k.foreignKey!==!1&&!g.has(P))if(typeof k.foreignKey==="object"&&k.foreignKey!==null){let Q=k.foreignKey;if(I.references={table:Q.table,column:Q.column??"id",onDelete:Q.onDelete,onUpdate:Q.onUpdate},Q.nullable!==void 0)I.isNullable=Q.nullable}else{let Q=R.get(P),oe=P.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(at,nt,cn)=>cn.toUpperCase()),fe=Q?.table??(y?void 0:n.modelToTable[oe]);if(fe){let at=n.primaryKeys[fe]??"id";I.references={table:fe,column:at,onDelete:Q?.onDelete}}}w.push(I)}let p=Rn(a.belongsTo);for(let C of p){let k=C.foreignKey??`${Jt(C.model)}_id`;if(w.some((H)=>H.name===k))continue;let P=n.modelToTable[C.model],q=P?n.primaryKeys[P]??"id":void 0;w.push({name:k,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:P&&q&&!g.has(k)?{table:P,column:q,onDelete:C.onDelete}:void 0})}let E=a.traits;if(E?.useTimestamps??E?.timestampable??!1){if(!w.some((C)=>C.name==="created_at"))w.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot});if(!w.some((C)=>C.name==="updated_at"))w.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(E?.useSoftDeletes??E?.softDeletable??!1){if(!w.some((C)=>C.name==="deleted_at"))w.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(E?.useUuid??!1){if(!w.some((C)=>C.name==="uuid"))w.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let C of a.indexes??[])N.push({name:C.name,columns:C.columns.map((k)=>Jt(k)),type:C.unique?"unique":"index",where:C.where});for(let C of w)if(C.isUnique&&!C.isPrimaryKey)N.push({name:`${c}_${C.name}_unique`,columns:[C.name],type:"unique"});let W=Array.isArray(a.shardKey)?a.shardKey.map(Jt):void 0,v=Array.isArray(a.sortKey)?a.sortKey.map(Jt):void 0,x=a.tableKind;r.push({table:c,columns:w,indexes:N,shardKey:W,sortKey:v,tableKind:x})}let s=new Set(r.map((l)=>l.table));function i(l){if(!s.has(l.table))s.add(l.table),r.push(l)}for(let l of Object.keys(e)){let a=e[l],c=a?.traits??{},u=Ft(a),m=Oi(u);if(c.likeable){let h=typeof c.likeable==="object"?c.likeable:{},w=h.table||`${u}_likes`,N=h.foreignKey||`${m}_id`;i({table:w,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:u,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${w}_user_target_unique`,columns:["user_id",N],type:"unique"}]})}if(c.taggable)i({table:"taggables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),i({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(c.categorizable)i({table:"categorizables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),i({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizables",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let l of Object.keys(e)){let a=e[l],c=a?.belongsToMany;if(!c||typeof c!=="object"||Array.isArray(c))continue;let u=Ft(a),m=Oi(u);for(let[h,w]of Object.entries(c)){let N=w;if(!N||typeof N!=="object")continue;if(N.through)continue;let R=N.pivot;if(!R||!R.columns&&!R.timestamps&&!R.uniques)continue;let y=N.model,g=e[y]?.table||`${String(y).toLowerCase()}s`,p=Oi(g),E=N.table||[m,p].sort().join("_"),D=N.foreignKey||`${m}_id`,J=N.relatedKey||`${p}_id`,B=new Set([D,J,...Object.keys(R.columns??{})]),W=new Set;for(let P of B){if(!P.endsWith("_type"))continue;let q=`${P.slice(0,-5)}_id`;if(B.has(q))W.add(q)}let v=(P,q)=>W.has(P)?void 0:{table:q,column:"id"},x=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:D,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:v(D,u)},{name:J,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:v(J,g)}];if(R.columns)for(let[P,q]of Object.entries(R.columns)){let H=q,M=ic(P)??"string";x.push({name:P,type:M,isPrimaryKey:!1,isUnique:!1,isNullable:H?.nullable??!1,hasDefault:H?.default!==void 0,defaultValue:H?.default})}if(R.timestamps)x.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Ot}),x.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let C=[],k=R.uniques&&R.uniques.length>0?R.uniques:[[D,J]];for(let P=0;P<k.length;P++){let q=k[P];C.push({name:`${E}_${q.join("_")}_unique${P>0?`_${P}`:""}`,columns:[...q],type:"unique"})}i({table:E,columns:x,indexes:C})}}let o=new Map(r.map((l)=>[l.table,l]));for(let l of r)for(let a of l.columns){if(!a.references)continue;let c=o.get(a.references.table)?.columns.find((u)=>u.name===a.references.column);if(!c||a.type===c.type)continue;a.type=c.type,a.maxLength=c.maxLength,a.enumValues=c.enumValues,a.enumTypeName=c.enumTypeName}return{dialect:t.dialect,vitessSharded:t.vitessSharded,tables:r}}function bs(e,t={}){rr=0,Bt=0,Ht=0,ps=[],An=null,hs=!0;let n=t.dryRun?()=>!1:gc,r=[],s=Tt(e.dialect,{vitessSharded:e.vitessSharded}),{tables:i,deferredForeignKeys:o}=yc(e.tables,e.dialect);for(let[a,c]of i.entries()){let u={...c,columns:c.columns.map((R)=>o.has(Nn(c.table,R.name))?{...R,references:void 0}:R)},m=[],h=new Set;for(let R of u.columns)if(R.type==="enum"&&R.enumValues&&R.enumValues.length>0){let y=`${u.table}_${R.name}_type`;if(R.enumTypeName=y,!h.has(y)){let b=s.createEnumType(y,R.enumValues);if(b)m.push(b);h.add(y)}}let w=s.createTable(u);m.push(w);for(let R of u.indexes)m.push(s.createIndex(u.table,R,u.columns));if(a===i.length-1)for(let R of i)for(let y of R.columns){if(!y.references||!o.has(Nn(R.table,y.name)))continue;let b=s.addForeignKey(R.table,y.name,y.references.table,y.references.column,y.references.onDelete,y.references.onUpdate);if(b)m.push(b)}r.push(...m);let N=m.join(`
434
+ `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function xg(e){let t=new Set,n;try{n=wg(e).filter((r)=>r.endsWith(".sql"))}catch{return t}for(let r of n)try{t.add(gc(Dg(bs(e,r),"utf8")))}catch{}return t}function yc(e,t){if(!e)return!1;let n=Eg();if(Nn===null)Nn=xg(n);let r=gc(e);if(r.length>0&&Nn.has(r))return Ke(`-- Migration already in the corpus, not writing it again: ${t}`),!1;rr++;let s=Ts?String(rr).padStart(10,"0"):String(Math.floor(Date.now()/1000)+rr),i=`${s}-${t}.sql`;if(!Ts){let l=Number(s);while(Fi(bs(n,i)))l+=1,s=String(l),i=`${s}-${t}.sql`}let o=bs(n,i);return Sg(o,`${fc}
435
+ ${e}`),Ke(`-- Migration file created: ${i}`),Pt++,ws.push(i),Nn?.add(r),!0}function Rg(e,t){return e==="integer"&&t==="bigint"||e==="string"&&t==="text"}function oc(e){if(e.endsWith("_id"))return"bigint";if(e.endsWith("_at"))return"datetime";if(e.startsWith("is_")||e.startsWith("has_"))return"boolean";return}function ac(e){if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint"||e instanceof Date)return e;return}function kg(e){if(e&&typeof e==="object"&&"name"in e){let t=e;if(t.name==="enum"||t.getRules&&Array.isArray(t.getRules())){if(t.enumValues&&Array.isArray(t.enumValues))return t.enumValues.map((n)=>String(n));if(t._values&&Array.isArray(t._values))return t._values.map((n)=>String(n));if(t.values&&Array.isArray(t.values))return t.values.map((n)=>String(n))}}if(e&&typeof e==="object"){let t=e,n=t.allowedValues||t.enumValues||t._values||t.values;if(Array.isArray(n)&&n.length>0)return n.map((r)=>String(r))}return}function _i(e){if(!e?.rules||!Array.isArray(e.rules))return;for(let t of e.rules)if(t?.name==="max"||t?.name==="maxLength"){if(t.params&&typeof t.params.max==="number")return t.params.max;if(Array.isArray(t.args)&&typeof t.args[0]==="number")return t.args[0];if(typeof t.value==="number")return t.value;if(typeof t.expectedValue==="number")return t.expectedValue}return}var Ii=767;function Cg(e){if(!e||typeof e!=="object")return;let t=e;if(t.name)switch(String(t.name).toLowerCase()){case"string":{let r=_i(t);return r&&r>Ii?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if(t.type){let n=String(t.type).toLowerCase();if(n==="string"||n==="text")return"string";if(n==="integer"||n==="int")return"integer";if(n==="bigint")return"bigint";if(n==="float")return"float";if(n==="number")return"integer";if(n==="boolean")return"boolean";if(n==="date")return"date";if(n==="datetime")return"datetime";if(n==="timestamptz"||n==="timestamp_tz")return"timestamptz";if(n==="json")return"json"}return}function vg(e){if(typeof e!=="string")return;switch(e.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function Zn(e,t){let n=sc(e),r=[];for(let l of Object.keys(e)){let a=e[l],c=qt(a),u=a.primaryKey??"id",m=a.autoIncrement!==!1,h=a.attributes??{},w=[],N=[];if(!h[u])w.push({name:Ht(u),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let R=new Map,y=Rn(a.belongsTo).length>0,b=new Set(Object.keys(h).map((C)=>Ht(C))),g=new Set;for(let C of b){if(!C.endsWith("_type"))continue;let k=`${C.slice(0,-5)}_id`;if(b.has(k))g.add(k)}for(let C of Rn(a.belongsTo)){let k=C.foreignKey??`${Ht(C.model)}_id`,P=n.modelToTable[C.model];if(P)R.set(k,{table:P,onDelete:C.onDelete})}for(let C of Object.keys(h)){let k=h[C],P=Ht(C),q=Boolean(k.validation?.rule?.isRequired),H=C===u?!1:k.nullable??!(k.required??q),M,V,U=C===u;if(M=vg(k.type)??Cg(k.validation?.rule),M==="string"){let Q=_i(k.validation?.rule);if(Q&&Q>Ii)M="text"}if(!M||M==="enum"){let Q=kg(k.validation?.rule);if(Q&&Q.length>0)M="enum",V=Q}if(!M)M=oc(P);if(!M){let Q=ac(k.default);if(typeof Q==="string")M=Q.length>255?"text":"string";else if(typeof Q==="number")M=Number.isInteger(Q)?"integer":"float";else if(typeof Q==="boolean")M="boolean";else if(typeof Q==="bigint")M="bigint";else if(Q instanceof Date)M="datetime"}if(!M)M=U?"bigint":"string";let Y=M==="string"?_i(k.validation?.rule):void 0,I={name:P,type:M,isPrimaryKey:U,isUnique:Boolean(k.unique),isNullable:H,hasDefault:typeof k.default<"u",defaultValue:ac(k.default),enumValues:V,maxLength:typeof Y==="number"&&Y>0&&Y<=Ii?Y:void 0};if(P.endsWith("_id")&&k.foreignKey!==!1&&!g.has(P))if(typeof k.foreignKey==="object"&&k.foreignKey!==null){let Q=k.foreignKey;if(I.references={table:Q.table,column:Q.column??"id",onDelete:Q.onDelete,onUpdate:Q.onUpdate},Q.nullable!==void 0)I.isNullable=Q.nullable}else{let Q=R.get(P),oe=P.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(at,nt,ln)=>ln.toUpperCase()),fe=Q?.table??(y?void 0:n.modelToTable[oe]);if(fe){let at=n.primaryKeys[fe]??"id";I.references={table:fe,column:at,onDelete:Q?.onDelete}}}w.push(I)}let p=Rn(a.belongsTo);for(let C of p){let k=C.foreignKey??`${Ht(C.model)}_id`;if(w.some((H)=>H.name===k))continue;let P=n.modelToTable[C.model],q=P?n.primaryKeys[P]??"id":void 0;w.push({name:k,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:P&&q&&!g.has(k)?{table:P,column:q,onDelete:C.onDelete}:void 0})}let E=a.traits;if(E?.useTimestamps??E?.timestampable??!1){if(!w.some((C)=>C.name==="created_at"))w.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt});if(!w.some((C)=>C.name==="updated_at"))w.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(E?.useSoftDeletes??E?.softDeletable??!1){if(!w.some((C)=>C.name==="deleted_at"))w.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(E?.useUuid??!1){if(!w.some((C)=>C.name==="uuid"))w.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let C of a.indexes??[])N.push({name:C.name,columns:C.columns.map((k)=>Ht(k)),type:C.unique?"unique":"index",where:C.where});for(let C of w)if(C.isUnique&&!C.isPrimaryKey)N.push({name:`${c}_${C.name}_unique`,columns:[C.name],type:"unique"});let W=Array.isArray(a.shardKey)?a.shardKey.map(Ht):void 0,v=Array.isArray(a.sortKey)?a.sortKey.map(Ht):void 0,x=a.tableKind;r.push({table:c,columns:w,indexes:N,shardKey:W,sortKey:v,tableKind:x})}let s=new Set(r.map((l)=>l.table));function i(l){if(!s.has(l.table))s.add(l.table),r.push(l)}for(let l of Object.keys(e)){let a=e[l],c=a?.traits??{},u=qt(a),m=Bi(u);if(c.likeable){let h=typeof c.likeable==="object"?c.likeable:{},w=h.table||`${u}_likes`,N=h.foreignKey||`${m}_id`;i({table:w,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:u,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${w}_user_target_unique`,columns:["user_id",N],type:"unique"}]})}if(c.taggable)i({table:"taggables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),i({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(c.categorizable)i({table:"categorizables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),i({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizables",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let l of Object.keys(e)){let a=e[l],c=a?.belongsToMany;if(!c||typeof c!=="object"||Array.isArray(c))continue;let u=qt(a),m=Bi(u);for(let[h,w]of Object.entries(c)){let N=w;if(!N||typeof N!=="object")continue;if(N.through)continue;let R=N.pivot;if(!R||!R.columns&&!R.timestamps&&!R.uniques)continue;let y=N.model,g=e[y]?.table||`${String(y).toLowerCase()}s`,p=Bi(g),E=N.table||[m,p].sort().join("_"),D=N.foreignKey||`${m}_id`,J=N.relatedKey||`${p}_id`,B=new Set([D,J,...Object.keys(R.columns??{})]),W=new Set;for(let P of B){if(!P.endsWith("_type"))continue;let q=`${P.slice(0,-5)}_id`;if(B.has(q))W.add(q)}let v=(P,q)=>W.has(P)?void 0:{table:q,column:"id"},x=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:D,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:v(D,u)},{name:J,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:v(J,g)}];if(R.columns)for(let[P,q]of Object.entries(R.columns)){let H=q,M=oc(P)??"string";x.push({name:P,type:M,isPrimaryKey:!1,isUnique:!1,isNullable:H?.nullable??!1,hasDefault:H?.default!==void 0,defaultValue:H?.default})}if(R.timestamps)x.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:Bt}),x.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let C=[],k=R.uniques&&R.uniques.length>0?R.uniques:[[D,J]];for(let P=0;P<k.length;P++){let q=k[P];C.push({name:`${E}_${q.join("_")}_unique${P>0?`_${P}`:""}`,columns:[...q],type:"unique"})}i({table:E,columns:x,indexes:C})}}let o=new Map(r.map((l)=>[l.table,l]));for(let l of r)for(let a of l.columns){if(!a.references)continue;let c=o.get(a.references.table)?.columns.find((u)=>u.name===a.references.column);if(!c||a.type===c.type)continue;a.type=c.type,a.maxLength=c.maxLength,a.enumValues=c.enumValues,a.enumTypeName=c.enumTypeName}return{dialect:t.dialect,vitessSharded:t.vitessSharded,tables:r}}function Ds(e,t={}){rr=0,Pt=0,zt=0,ws=[],Nn=null,Ts=!0;let n=t.dryRun?()=>!1:yc,r=[],s=Tt(e.dialect,{vitessSharded:e.vitessSharded}),{tables:i,deferredForeignKeys:o}=hc(e.tables,e.dialect);for(let[a,c]of i.entries()){let u={...c,columns:c.columns.map((R)=>o.has(Mn(c.table,R.name))?{...R,references:void 0}:R)},m=[],h=new Set;for(let R of u.columns)if(R.type==="enum"&&R.enumValues&&R.enumValues.length>0){let y=`${u.table}_${R.name}_type`;if(R.enumTypeName=y,!h.has(y)){let b=s.createEnumType(y,R.enumValues);if(b)m.push(b);h.add(y)}}let w=s.createTable(u);m.push(w);for(let R of u.indexes)m.push(s.createIndex(u.table,R,u.columns));if(a===i.length-1)for(let R of i)for(let y of R.columns){if(!y.references||!o.has(Mn(R.table,y.name)))continue;let b=s.addForeignKey(R.table,y.name,y.references.table,y.references.column,y.references.onDelete,y.references.onUpdate);if(b)m.push(b)}r.push(...m);let N=m.join(`
436
436
 
437
- `);n(N,`create-${u.table}-table`)}if(Bt+Ht===0)Ke("-- Nothing to migrate");else{let a=[];if(Bt>0)a.push(`${Bt} created`);if(Ht>0)a.push(`${Ht} updated`);Ke(`-- Migration files: ${a.join(", ")}`)}return r}function Nn(e,t){return`${e}\x00${t}`}function yc(e,t){if(t==="sqlite"||e.length<2)return{tables:e,deferredForeignKeys:new Set};let n=new Map(e.map((a)=>[a.table,a])),r=new Map;for(let a of e)r.set(a.table,new Set(a.columns.map((c)=>c.references?.table).filter((c)=>Boolean(c&&c!==a.table&&n.has(c)))));let s=[],i=new Set;while(s.length<e.length){let a=e.find((c)=>!i.has(c.table)&&[...r.get(c.table)??[]].every((u)=>i.has(u)));if(!a)break;s.push(a),i.add(a.table)}let o=new Set(e.filter((a)=>!i.has(a.table)).map((a)=>a.table)),l=new Set;for(let a of e){if(!o.has(a.table))continue;for(let c of a.columns)if(c.references&&o.has(c.references.table)&&c.references.table!==a.table)l.add(Nn(a.table,c.name))}return s.push(...e.filter((a)=>o.has(a.table))),{tables:s,deferredForeignKeys:l}}function nD(e){return bs(e).join(`
438
- `)}function rD(e,t){return Og(e,t).join(`
439
- `)}function hc(e){let t=ze("crypto");function n(s){if(s==null||typeof s!=="object"||s instanceof Date)return s;if(Array.isArray(s))return s.map((o)=>n(o));let i={};for(let o of Object.keys(s).sort())i[o]=n(s[o]);return i}let r=JSON.stringify(n(e));return t.createHash("sha256").update(r).digest("hex")}function ac(e){let t={};for(let n of e)t[n.table]=n;return t}function nr(e){let t={};for(let n of e)t[n.name]=n;return t}function Ii(e,t){if(t==="sqlite"){if(e.name.endsWith("_id")&&$n(e.type))return"INTEGER";switch(e.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if(t==="mysql"||t==="vitess"||t==="singlestore")switch(e.type){case"string":return`VARCHAR(${e.maxLength??255})`;case"text":return"TEXT";case"boolean":return"TINYINT(1)";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"float":return"REAL";case"double":return"DOUBLE";case"decimal":return"DECIMAL";case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return e.type}return e.type}var Ot="UTC_TIMESTAMP";function Li(e,t){if(!e.hasDefault||e.defaultValue===void 0)return;let n=e.defaultValue;if(n instanceof Date)return n.toISOString();if(typeof n==="boolean")return n?"1":"0";if(typeof n==="bigint"||typeof n==="number")return String(n);let r=String(n).trim();if(r=r.replace(/::[\w ]+$/i,"").trim(),r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))r=r.slice(1,-1);let s=r.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(s.replace(/\s+/g," ")))return Ot;if(t==="sqlite"&&s==="CURRENT_TIMESTAMP")return Ot;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(s))return s==="NOW()"?"CURRENT_TIMESTAMP":s;if(e.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(r))return"1";if(/^(?:0|f|false|no)$/i.test(r))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(r))return String(Number(r));return r}function vg(e,t,n){if(Ii(e,n)!==Ii(t,n))return!0;if(e.isNullable!==t.isNullable)return!0;if(e.hasDefault!==t.hasDefault)return!0;if(Li(e,n)!==Li(t,n))return!0;if(e.isUnique!==t.isUnique)return!0;if(e.type==="enum"&&t.type==="enum"){let r=(e.enumValues||[]).slice().sort().join(","),s=(t.enumValues||[]).slice().sort().join(",");if(r!==s)return!0}return!1}function lc(e,t){return JSON.stringify([Ii(e,t),e.isPrimaryKey,e.isUnique,e.isNullable,e.hasDefault,Li(e,t)??null,(e.enumValues??[]).slice().sort(),e.references?[e.references.table,e.references.column,e.references.onDelete??null,e.references.onUpdate??null]:null])}function Ag(e,t,n){let r=Object.keys(e).filter((u)=>!t[u]),s=Object.keys(t).filter((u)=>!e[u]),i=new Map,o=new Map;for(let u of r){let m=lc(e[u],n),h=i.get(m)??[];h.push(u),i.set(m,h)}for(let u of s){let m=lc(t[u],n),h=o.get(m)??[];h.push(u),o.set(m,h)}let l=[],a=new Set,c=new Set;for(let[u,m]of i){let h=o.get(u);if(m.length===1&&h&&h.length===1)l.push({from:m[0],to:h[0]}),a.add(m[0]),c.add(h[0])}return{renames:l,removed:r.filter((u)=>!a.has(u)),added:s.filter((u)=>!c.has(u))}}function Ng(e,t){let n=e.columns.find((r)=>r.name===t);if(n&&(n.isPrimaryKey||n.isUnique||n.references))return!0;return e.indexes.some((r)=>r.columns.includes(t))}function Mg(e,t){if(Boolean(e)!==Boolean(t))return!0;if(!e||!t)return!1;if((e.constraintNames?.length??0)>1)return!0;let n=(r)=>(r??"no action").toLowerCase();return e.table!==t.table||e.column!==t.column||n(e.onDelete)!==n(t.onDelete)||n(e.onUpdate)!==n(t.onUpdate)}function pc(e,t){return`${e.type}:${ft(t,e.name)}:${e.columns.join(",")}`}function Bi(e,t){let n={};for(let r of e)n[pc(r,t)]=r;return n}function Fi(e,t,n={}){if(!e||e.dialect!==t.dialect){let g=bs(t,{dryRun:n.dryRun}),p=t.tables.map((E)=>({kind:"create_table",table:E.table,destructive:!1,sql:""}));return{statements:g,operations:p}}let r=n.applyRenames!==!1,s=n.preserveUnknownColumns===!0,i=n.dryRun?()=>!1:gc;rr=0,Bt=0,Ht=0,ps=[],An=null,hs=!1;let o=[],l=[],a=Tt(t.dialect,{vitessSharded:t.vitessSharded}),c=t.dialect,u=ac(e.tables),m=ac(t.tables);for(let g of Object.keys(u))if(!m[g]){let p=a.dropTable(g);o.push(p),l.push({kind:"drop_table",table:g,destructive:!0,sql:p}),i(p,`drop-${g}-table`),Ke(`-- Detected dropped table: ${g}`)}let h=Object.keys(m).filter((g)=>!u[g]).map((g)=>m[g]),{tables:w,deferredForeignKeys:N}=yc(h,c);for(let[g,p]of w.entries()){let E={...p,columns:p.columns.map((v)=>N.has(Nn(p.table,v.name))?{...v,references:void 0}:v)},D=[],J=new Set;for(let v of E.columns)if(v.type==="enum"&&v.enumValues&&v.enumValues.length>0){let x=`${E.table}_${v.name}_type`;if(v.enumTypeName=x,!J.has(x)){let C=a.createEnumType(x,v.enumValues);if(C)D.push(C);J.add(x)}}let B=a.createTable(E);D.push(B);for(let v of E.indexes){let x=a.createIndex(E.table,v,E.columns);D.push(x),l.push({kind:"create_index",table:E.table,column:v.name,destructive:!1,sql:x})}for(let v of p.columns)if(v.references&&!N.has(Nn(p.table,v.name)))l.push({kind:"add_foreign_key",table:p.table,column:v.name,destructive:!1,sql:B});if(g===w.length-1)for(let v of w)for(let x of v.columns){if(!x.references||!N.has(Nn(v.table,x.name)))continue;let C=a.addForeignKey(v.table,x.name,x.references.table,x.references.column,x.references.onDelete,x.references.onUpdate);if(!C)continue;D.push(C),l.push({kind:"add_foreign_key",table:v.table,column:x.name,destructive:!1,sql:C})}o.push(...D),l.push({kind:"create_table",table:E.table,destructive:!1,sql:B});let W=D.join(`
437
+ `);n(N,`create-${u.table}-table`)}if(Pt+zt===0)Ke("-- Nothing to migrate");else{let a=[];if(Pt>0)a.push(`${Pt} created`);if(zt>0)a.push(`${zt} updated`);Ke(`-- Migration files: ${a.join(", ")}`)}return r}function Mn(e,t){return`${e}\x00${t}`}function hc(e,t){if(t==="sqlite"||e.length<2)return{tables:e,deferredForeignKeys:new Set};let n=new Map(e.map((a)=>[a.table,a])),r=new Map;for(let a of e)r.set(a.table,new Set(a.columns.map((c)=>c.references?.table).filter((c)=>Boolean(c&&c!==a.table&&n.has(c)))));let s=[],i=new Set;while(s.length<e.length){let a=e.find((c)=>!i.has(c.table)&&[...r.get(c.table)??[]].every((u)=>i.has(u)));if(!a)break;s.push(a),i.add(a.table)}let o=new Set(e.filter((a)=>!i.has(a.table)).map((a)=>a.table)),l=new Set;for(let a of e){if(!o.has(a.table))continue;for(let c of a.columns)if(c.references&&o.has(c.references.table)&&c.references.table!==a.table)l.add(Mn(a.table,c.name))}return s.push(...e.filter((a)=>o.has(a.table))),{tables:s,deferredForeignKeys:l}}function sD(e){return Ds(e).join(`
438
+ `)}function iD(e,t){return Bg(e,t).join(`
439
+ `)}function pc(e){let t=ze("crypto");function n(s){if(s==null||typeof s!=="object"||s instanceof Date)return s;if(Array.isArray(s))return s.map((o)=>n(o));let i={};for(let o of Object.keys(s).sort())i[o]=n(s[o]);return i}let r=JSON.stringify(n(e));return t.createHash("sha256").update(r).digest("hex")}function lc(e){let t={};for(let n of e)t[n.table]=n;return t}function nr(e){let t={};for(let n of e)t[n.name]=n;return t}function Li(e,t){if(t==="sqlite"){if(e.name.endsWith("_id")&&$n(e.type))return"INTEGER";switch(e.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if(t==="mysql"||t==="vitess"||t==="singlestore")switch(e.type){case"string":return`VARCHAR(${e.maxLength??255})`;case"text":return"TEXT";case"boolean":return"TINYINT(1)";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"float":return"REAL";case"double":return"DOUBLE";case"decimal":return"DECIMAL";case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return e.type}return e.type}var Bt="UTC_TIMESTAMP";function Ki(e,t){if(!e.hasDefault||e.defaultValue===void 0)return;let n=e.defaultValue;if(n instanceof Date)return n.toISOString();if(typeof n==="boolean")return n?"1":"0";if(typeof n==="bigint"||typeof n==="number")return String(n);let r=String(n).trim();if(r=r.replace(/::[\w ]+$/i,"").trim(),r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))r=r.slice(1,-1);let s=r.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(s.replace(/\s+/g," ")))return Bt;if(t==="sqlite"&&s==="CURRENT_TIMESTAMP")return Bt;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(s))return s==="NOW()"?"CURRENT_TIMESTAMP":s;if(e.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(r))return"1";if(/^(?:0|f|false|no)$/i.test(r))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(r))return String(Number(r));return r}function Ag(e,t,n){if(Li(e,n)!==Li(t,n))return!0;if(e.isNullable!==t.isNullable)return!0;if(e.hasDefault!==t.hasDefault)return!0;if(Ki(e,n)!==Ki(t,n))return!0;if(e.isUnique!==t.isUnique)return!0;if(e.type==="enum"&&t.type==="enum"){let r=(e.enumValues||[]).slice().sort().join(","),s=(t.enumValues||[]).slice().sort().join(",");if(r!==s)return!0}return!1}function cc(e,t){return JSON.stringify([Li(e,t),e.isPrimaryKey,e.isUnique,e.isNullable,e.hasDefault,Ki(e,t)??null,(e.enumValues??[]).slice().sort(),e.references?[e.references.table,e.references.column,e.references.onDelete??null,e.references.onUpdate??null]:null])}function Ng(e,t,n){let r=Object.keys(e).filter((u)=>!t[u]),s=Object.keys(t).filter((u)=>!e[u]),i=new Map,o=new Map;for(let u of r){let m=cc(e[u],n),h=i.get(m)??[];h.push(u),i.set(m,h)}for(let u of s){let m=cc(t[u],n),h=o.get(m)??[];h.push(u),o.set(m,h)}let l=[],a=new Set,c=new Set;for(let[u,m]of i){let h=o.get(u);if(m.length===1&&h&&h.length===1)l.push({from:m[0],to:h[0]}),a.add(m[0]),c.add(h[0])}return{renames:l,removed:r.filter((u)=>!a.has(u)),added:s.filter((u)=>!c.has(u))}}function Mg(e,t){let n=e.columns.find((r)=>r.name===t);if(n&&(n.isPrimaryKey||n.isUnique||n.references))return!0;return e.indexes.some((r)=>r.columns.includes(t))}function Og(e,t){if(Boolean(e)!==Boolean(t))return!0;if(!e||!t)return!1;if((e.constraintNames?.length??0)>1)return!0;let n=(r)=>(r??"no action").toLowerCase();return e.table!==t.table||e.column!==t.column||n(e.onDelete)!==n(t.onDelete)||n(e.onUpdate)!==n(t.onUpdate)}function bc(e,t){return`${e.type}:${ft(t,e.name)}:${e.columns.join(",")}`}function Pi(e,t){let n={};for(let r of e)n[bc(r,t)]=r;return n}function qi(e,t,n={}){if(!e||e.dialect!==t.dialect){let g=Ds(t,{dryRun:n.dryRun}),p=t.tables.map((E)=>({kind:"create_table",table:E.table,destructive:!1,sql:""}));return{statements:g,operations:p}}let r=n.applyRenames!==!1,s=n.preserveUnknownColumns===!0,i=n.dryRun?()=>!1:yc;rr=0,Pt=0,zt=0,ws=[],Nn=null,Ts=!1;let o=[],l=[],a=Tt(t.dialect,{vitessSharded:t.vitessSharded}),c=t.dialect,u=lc(e.tables),m=lc(t.tables);for(let g of Object.keys(u))if(!m[g]){let p=a.dropTable(g);o.push(p),l.push({kind:"drop_table",table:g,destructive:!0,sql:p}),i(p,`drop-${g}-table`),Ke(`-- Detected dropped table: ${g}`)}let h=Object.keys(m).filter((g)=>!u[g]).map((g)=>m[g]),{tables:w,deferredForeignKeys:N}=hc(h,c);for(let[g,p]of w.entries()){let E={...p,columns:p.columns.map((v)=>N.has(Mn(p.table,v.name))?{...v,references:void 0}:v)},D=[],J=new Set;for(let v of E.columns)if(v.type==="enum"&&v.enumValues&&v.enumValues.length>0){let x=`${E.table}_${v.name}_type`;if(v.enumTypeName=x,!J.has(x)){let C=a.createEnumType(x,v.enumValues);if(C)D.push(C);J.add(x)}}let B=a.createTable(E);D.push(B);for(let v of E.indexes){let x=a.createIndex(E.table,v,E.columns);D.push(x),l.push({kind:"create_index",table:E.table,column:v.name,destructive:!1,sql:x})}for(let v of p.columns)if(v.references&&!N.has(Mn(p.table,v.name)))l.push({kind:"add_foreign_key",table:p.table,column:v.name,destructive:!1,sql:B});if(g===w.length-1)for(let v of w)for(let x of v.columns){if(!x.references||!N.has(Mn(v.table,x.name)))continue;let C=a.addForeignKey(v.table,x.name,x.references.table,x.references.column,x.references.onDelete,x.references.onUpdate);if(!C)continue;D.push(C),l.push({kind:"add_foreign_key",table:v.table,column:x.name,destructive:!1,sql:C})}o.push(...D),l.push({kind:"create_table",table:E.table,destructive:!1,sql:B});let W=D.join(`
440
440
 
441
- `);i(W,`create-${E.table}-table`)}let R=new Set;for(let g of Object.keys(m)){let p=u[g],E=m[g];if(!p)continue;let D=nr(p.columns),J=nr(E.columns);for(let B of Object.keys(J)){let W=J[B];if(W.type!=="enum"||!W.enumValues||W.enumValues.length===0)continue;let v=`${E.table}_${W.name}_type`;if(W.enumTypeName=v,D[B])continue;if(!R.has(v)){let x=a.createEnumType(v,W.enumValues);if(x)o.push(x),l.push({kind:"create_enum",table:E.table,column:W.name,destructive:!1,sql:x}),i(x,`create-${v}-enum`);R.add(v)}}}for(let g of Object.keys(m)){let p=u[g],E=m[g];if(!p)continue;let D=nr(p.columns),J=Bi(p.indexes,p.table),B=nr(E.columns),W=Bi(E.indexes,E.table),v=[],x=Object.keys(D).filter((M)=>!B[M]),C=Object.keys(B).filter((M)=>!D[M]);if(r&&!s){let M=Ag(D,B,c);v=M.renames,x=M.removed,C=M.added}if(s){let M=x.map((U)=>D[U]),V=p.indexes.filter((U)=>!W[pc(U,p.table)]);if(M.length>0||V.length>0){if(M.length>0)Ke(`-- Keeping ${M.length} column(s) on "${E.table}" no model declares: ${x.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(V.length>0)Ke(`-- Keeping ${V.length} index(es) on "${E.table}" no model declares: ${V.map((U)=>U.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);E={...E,columns:[...E.columns,...M],indexes:[...E.indexes,...V]},B=nr(E.columns),W=Bi(E.indexes,E.table)}x=[]}let k=Object.keys(B).filter((M)=>D[M]&&vg(D[M],B[M],c)),P=Object.keys(B).filter((M)=>D[M]&&Mg(D[M].references,B[M].references));if(c==="sqlite"){if(k.length>0||P.length>0||x.some((V)=>Ng(p,V))){let V={},U=new Map(v.map((oe)=>[oe.to,oe.from]));for(let oe of E.columns)if(D[oe.name])V[oe.name]=oe.name;else if(U.has(oe.name))V[oe.name]=U.get(oe.name);let Y=`_qb_tmp_${E.table}`,I=0;while((u[Y]||m[Y])&&I<100)I+=1,Y=`_qb_tmp_${E.table}_${I}`;let Q=a.rebuildTable({target:E,tempName:Y,columnSource:V});o.push(Q);let se=k.some((oe)=>D[oe].type!==B[oe].type);l.push({kind:"rebuild_table",table:E.table,destructive:x.length>0||se,sql:Q});for(let oe of v)l.push({kind:"rename_column",table:E.table,from:oe.from,to:oe.to,destructive:!1,confidence:"high",sql:Q});for(let oe of x)l.push({kind:"drop_column",table:E.table,column:oe,destructive:!0,sql:Q});Ke(`-- Detected SQLite table rebuild required: ${E.table}`),i(Q,`alter-${E.table}-table`);continue}}let q=[],H=!1;for(let M of Object.keys(J))if(!W[M]){let V=J[M],U=a.dropIndex(E.table,V.name);q.push(U),o.push(U),l.push({kind:"drop_index",table:E.table,column:V.name,destructive:!1,sql:U}),Ke(`-- Detected dropped index: ${V.name} from ${E.table}`),H=!0}for(let M of v){let V=a.renameColumn(E.table,M.from,M.to);q.push(V),o.push(V),l.push({kind:"rename_column",table:E.table,from:M.from,to:M.to,destructive:!1,confidence:"high",sql:V}),Ke(`-- Detected renamed column: ${E.table}.${M.from} -> ${M.to}`),H=!0}for(let M of x){let V=a.dropColumn(E.table,M);q.push(V),o.push(V),l.push({kind:"drop_column",table:E.table,column:M,destructive:!0,sql:V}),Ke(`-- Detected dropped column: ${E.table}.${M}`),H=!0}for(let M of k){let V=D[M],U=B[M],Y=a.modifyColumn(E.table,U);q.push(Y),o.push(Y),l.push({kind:"modify_column",table:E.table,column:M,destructive:V.type!==U.type&&!xg(V.type,U.type),sql:Y}),Ke(`-- Detected column change: ${E.table}.${M} (${V.type} -> ${U.type})`),H=!0}for(let M of P){let V=B[M];if(!V.references)continue;let U=a.addForeignKey(E.table,V.name,V.references.table,V.references.column,V.references.onDelete,V.references.onUpdate,D[M].references?.constraintNames);if(!U)continue;q.push(U),o.push(U),l.push({kind:"add_foreign_key",table:E.table,column:M,destructive:!1,sql:U}),Ke(`-- Detected foreign-key change: ${E.table}.${M} -> ${V.references.table}(${V.references.column})`),H=!0}for(let M of C){let V=B[M],U=a.addColumn(E.table,V);if(q.push(U),o.push(U),l.push({kind:"add_column",table:E.table,column:V.name,destructive:!1,sql:U}),Ke(`-- Detected new column: ${E.table}.${V.name}`),H=!0,V.references){let Y=a.addForeignKey(E.table,V.name,V.references.table,V.references.column,V.references.onDelete,V.references.onUpdate);if(Y)q.push(Y),o.push(Y),l.push({kind:"add_foreign_key",table:E.table,column:V.name,destructive:!1,sql:Y})}}for(let M of Object.keys(W))if(!J[M]){let V=W[M],U=a.createIndex(E.table,V,E.columns);q.push(U),o.push(U),l.push({kind:"create_index",table:E.table,column:V.name,destructive:!1,sql:U}),Ke(`-- Detected new index: ${V.name} in ${E.table}`),H=!0}if(H){let M=q.join(`
441
+ `);i(W,`create-${E.table}-table`)}let R=new Set;for(let g of Object.keys(m)){let p=u[g],E=m[g];if(!p)continue;let D=nr(p.columns),J=nr(E.columns);for(let B of Object.keys(J)){let W=J[B];if(W.type!=="enum"||!W.enumValues||W.enumValues.length===0)continue;let v=`${E.table}_${W.name}_type`;if(W.enumTypeName=v,D[B])continue;if(!R.has(v)){let x=a.createEnumType(v,W.enumValues);if(x)o.push(x),l.push({kind:"create_enum",table:E.table,column:W.name,destructive:!1,sql:x}),i(x,`create-${v}-enum`);R.add(v)}}}for(let g of Object.keys(m)){let p=u[g],E=m[g];if(!p)continue;let D=nr(p.columns),J=Pi(p.indexes,p.table),B=nr(E.columns),W=Pi(E.indexes,E.table),v=[],x=Object.keys(D).filter((M)=>!B[M]),C=Object.keys(B).filter((M)=>!D[M]);if(r&&!s){let M=Ng(D,B,c);v=M.renames,x=M.removed,C=M.added}if(s){let M=x.map((U)=>D[U]),V=p.indexes.filter((U)=>!W[bc(U,p.table)]);if(M.length>0||V.length>0){if(M.length>0)Ke(`-- Keeping ${M.length} column(s) on "${E.table}" no model declares: ${x.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(V.length>0)Ke(`-- Keeping ${V.length} index(es) on "${E.table}" no model declares: ${V.map((U)=>U.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);E={...E,columns:[...E.columns,...M],indexes:[...E.indexes,...V]},B=nr(E.columns),W=Pi(E.indexes,E.table)}x=[]}let k=Object.keys(B).filter((M)=>D[M]&&Ag(D[M],B[M],c)),P=Object.keys(B).filter((M)=>D[M]&&Og(D[M].references,B[M].references));if(c==="sqlite"){if(k.length>0||P.length>0||x.some((V)=>Mg(p,V))){let V={},U=new Map(v.map((oe)=>[oe.to,oe.from]));for(let oe of E.columns)if(D[oe.name])V[oe.name]=oe.name;else if(U.has(oe.name))V[oe.name]=U.get(oe.name);let Y=`_qb_tmp_${E.table}`,I=0;while((u[Y]||m[Y])&&I<100)I+=1,Y=`_qb_tmp_${E.table}_${I}`;let Q=a.rebuildTable({target:E,tempName:Y,columnSource:V});o.push(Q);let se=k.some((oe)=>D[oe].type!==B[oe].type);l.push({kind:"rebuild_table",table:E.table,destructive:x.length>0||se,sql:Q});for(let oe of v)l.push({kind:"rename_column",table:E.table,from:oe.from,to:oe.to,destructive:!1,confidence:"high",sql:Q});for(let oe of x)l.push({kind:"drop_column",table:E.table,column:oe,destructive:!0,sql:Q});Ke(`-- Detected SQLite table rebuild required: ${E.table}`),i(Q,`alter-${E.table}-table`);continue}}let q=[],H=!1;for(let M of Object.keys(J))if(!W[M]){let V=J[M],U=a.dropIndex(E.table,V.name);q.push(U),o.push(U),l.push({kind:"drop_index",table:E.table,column:V.name,destructive:!1,sql:U}),Ke(`-- Detected dropped index: ${V.name} from ${E.table}`),H=!0}for(let M of v){let V=a.renameColumn(E.table,M.from,M.to);q.push(V),o.push(V),l.push({kind:"rename_column",table:E.table,from:M.from,to:M.to,destructive:!1,confidence:"high",sql:V}),Ke(`-- Detected renamed column: ${E.table}.${M.from} -> ${M.to}`),H=!0}for(let M of x){let V=a.dropColumn(E.table,M);q.push(V),o.push(V),l.push({kind:"drop_column",table:E.table,column:M,destructive:!0,sql:V}),Ke(`-- Detected dropped column: ${E.table}.${M}`),H=!0}for(let M of k){let V=D[M],U=B[M],Y=a.modifyColumn(E.table,U);q.push(Y),o.push(Y),l.push({kind:"modify_column",table:E.table,column:M,destructive:V.type!==U.type&&!Rg(V.type,U.type),sql:Y}),Ke(`-- Detected column change: ${E.table}.${M} (${V.type} -> ${U.type})`),H=!0}for(let M of P){let V=B[M];if(!V.references)continue;let U=a.addForeignKey(E.table,V.name,V.references.table,V.references.column,V.references.onDelete,V.references.onUpdate,D[M].references?.constraintNames);if(!U)continue;q.push(U),o.push(U),l.push({kind:"add_foreign_key",table:E.table,column:M,destructive:!1,sql:U}),Ke(`-- Detected foreign-key change: ${E.table}.${M} -> ${V.references.table}(${V.references.column})`),H=!0}for(let M of C){let V=B[M],U=a.addColumn(E.table,V);if(q.push(U),o.push(U),l.push({kind:"add_column",table:E.table,column:V.name,destructive:!1,sql:U}),Ke(`-- Detected new column: ${E.table}.${V.name}`),H=!0,V.references){let Y=a.addForeignKey(E.table,V.name,V.references.table,V.references.column,V.references.onDelete,V.references.onUpdate);if(Y)q.push(Y),o.push(Y),l.push({kind:"add_foreign_key",table:E.table,column:V.name,destructive:!1,sql:Y})}}for(let M of Object.keys(W))if(!J[M]){let V=W[M],U=a.createIndex(E.table,V,E.columns);q.push(U),o.push(U),l.push({kind:"create_index",table:E.table,column:V.name,destructive:!1,sql:U}),Ke(`-- Detected new index: ${V.name} in ${E.table}`),H=!0}if(H){let M=q.join(`
442
442
 
443
- `);i(M,`alter-${E.table}-table`)}}if(Bt+Ht===0)Ke("-- Nothing to migrate");else{let g=[];if(Bt>0)g.push(`${Bt} created`);if(Ht>0)g.push(`${Ht} updated`);Ke(`-- Migration files: ${g.join(", ")}`)}return{statements:o.length===0?["-- No changes detected"]:o,operations:l}}function Og(e,t,n={}){return Fi(e,t,n).statements}Ni();function iD(e){return e}class Bg{get order(){return 100}get description(){return}}function aD(e){return e}tr();tr();ns();Hr();Me();function bc(e){switch(e){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":case"timestamptz":return"date";case"json":return"json";default:return"other"}}function Tc(e){let t=String(e??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(t)||t==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(t))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(t))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test(t))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(t))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(t))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(t)||/^float\d*\b/.test(t))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(t)||/^int\d*\b/.test(t))return"integer";return"other"}function wc(e,t,n){if(e===t)return!0;if(n==="sqlite"){if(e==="boolean"&&t==="integer")return!0;if((e==="date"||e==="json")&&t==="text")return!0}if(ne(n)&&e==="boolean"&&t==="integer")return!0;if(e==="varchar"&&t==="text")return!0;if(e==="integer"&&t==="fractional")return!0;if(e==="other"||t==="other")return!0;return!1}async function Pg(e,t={}){let n=t.dialect??_.dialect,r=e.tables.map((c)=>c.table),s=await gi({tables:r}),i=new Map(s.map((c)=>[c.table.toLowerCase(),c])),o=[],l=[],a=[];for(let c of e.tables){let u=i.get(c.table.toLowerCase());if(!u){o.push(c.table);continue}let m=new Map(u.columns.map((h)=>[h.name.toLowerCase(),h]));for(let h of c.columns){let w=m.get(h.name.toLowerCase()),N=bc(h.type);if(!w){l.push({table:c.table,column:h.name,expected:N});continue}let R=Tc(w.sqlType);if(!wc(N,R,n))a.push({table:c.table,column:h.name,expected:N,actual:R,actualSqlType:w.sqlType})}}return{missingTables:o,missingColumns:l,typeMismatches:a,clean:o.length===0&&l.length===0&&a.length===0}}function _g(e){if(e.clean)return"";let t=[];if(e.missingTables.length>0)t.push(` Missing tables: ${e.missingTables.join(", ")}`);for(let s of e.missingColumns.slice(0,10))t.push(` \u2022 ${s.table}.${s.column} is missing (models declare ${s.expected})`);for(let s of e.typeMismatches.slice(0,10))t.push(` \u2022 ${s.table}.${s.column} is ${s.actualSqlType}, models declare ${s.expected}`);let n=Math.min(e.missingColumns.length,10)+Math.min(e.typeMismatches.length,10),r=e.missingColumns.length+e.typeMismatches.length;if(r>n)t.push(` + ${r-n} more`);return["The live schema does not match the models.",...t,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
444
- `)}async function Kg(e,t,n){if(n.length===0)return;let r=Ac(ln());try{await Nc(e,t);for(let s of n)await Ts(e,s,t),re(`-- \u2713 Recorded applied migration: ${s}`)}catch(s){re(`-- Could not record applied migrations (the schema change itself succeeded): ${s instanceof Error?s.message:String(s)}`)}}function kc(e,t){try{return fc(sr(tt(e,t),"utf8"))}catch{return!1}}function Fg(e){let t=e instanceof Error?e.message:String(e);return/duplicate column name/i.test(t)||/duplicate key name/i.test(t)||/duplicate foreign key constraint name/i.test(t)||/\balready exists\b/i.test(t)}function re(e){if(_.verbose)console.log(e)}function Cc(e){return tt(e,_.snapshotDir||".qb")}function Wi(e,t){return tt(Cc(e),`model-snapshot.${t}.json`)}function qg(e,t){let n=Wi(e,t);if(!Pt(n))return;try{let r=sr(n,"utf8"),s=JSON.parse(r);if(s?.plan&&Array.isArray(s.plan.tables)&&s.plan.dialect)return s.plan;if(Array.isArray(s?.tables)&&s?.dialect)return s;re("-- Invalid snapshot format, treating as no previous state");return}catch(r){re(`-- Could not load snapshot, treating as no previous state: ${r instanceof Error?r.message:String(r)}`);return}}function vc(e,t,n){let r=Wi(e,t),s=Cc(e),i=hc(n);if(Pt(r))try{let l=JSON.parse(sr(r,"utf8"));if(l?.hash===i&&l?.dialect===t&&l?.plan){re("-- Model snapshot unchanged");return}}catch{}if(!Pt(s))$c(s,{recursive:!0}),re(`-- Created snapshot directory: ${s}`);let o={plan:n,hash:i,dialect:t,updatedAt:new Date().toISOString()};Rc(r,JSON.stringify(o,null,2)),re(`-- Model snapshot saved to ${r}`)}function Jm(e,t={}){let n=t.dialect??e.dialect;vc(t.workspaceRoot??ln(),n,e)}function ln(){return wi()}function Ac(e){let t=At(e,_.migrationDir);if(!Pt(t))$c(t,{recursive:!0}),re(`-- Created SQL directory: ${t}`);return t}async function Ti(e,t={}){if(await Jr(),!e)e=tt(ji.cwd(),"app/Models");let n=t.dialect||_.dialect||"postgres",r=ln(),s=await mt({modelsDir:e}),i=Xn(s,{dialect:n,vitessSharded:t.vitessSharded}),o,l=!1;if(!t.full)if(o=qg(r,n),o)re("-- Comparing with stored model snapshot");else{let w=tt(e,`.qb-migrations.${n}.json`),N=String(t.state||w);if(Pt(N))try{let R=sr(N,"utf8"),y=JSON.parse(R);if(o=y?.plan&&y.plan.tables?y.plan:y?.tables?y:void 0,o)re("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!o||t.fromDb)try{let R=await Za(n),y=new Set(i.tables.map((g)=>g.table)),b=R.tables.filter((g)=>y.has(g.table));if(b.length>0)o={dialect:R.dialect,tables:b},l=!0,re(`-- No snapshot; reconciling against live database (${b.length} matching table${b.length===1?"":"s"})`)}catch(R){re(`-- Could not introspect live database, treating as no previous state: ${R instanceof Error?R.message:String(R)}`)}if(!o)re("-- No previous snapshot found, generating full migration")}else re("-- Full migration requested, ignoring any previous state");let a=t.full?{statements:bs(i,{dryRun:t.dryRun}),operations:i.tables.map((w)=>({kind:"create_table",table:w.table,destructive:!1,sql:""}))}:Fi(o,i,{applyRenames:t.applyRenames,dryRun:t.dryRun,preserveUnknownColumns:l}),c=a.statements,u=a.operations,m=c.join(`
445
- `),h=c.some((w)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(w));if(t.apply){let w=Ig(tt(Lg(),"qb-migrate-")),N=tt(w,"migration.sql");try{if(h){Rc(N,m);let R=ie();await R.file(N),re("-- Migration applied"),await Kg(R,n,uc())}else re("-- No changes; nothing to apply")}catch(R){throw console.error("-- Migration failed:",R),R}finally{xc(w,{recursive:!0,force:!0})}}if(!t.dryRun)vc(r,n,i);return{sql:m,sqlStatements:c,hasChanges:h,plan:i,operations:u}}var Dc="bun-query-builder:migrate",jg=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function Sc(e){return e==="postgres"||e==="sqlite"}async function Wg(e,t){if(e==="sqlite")return await t();let n=ie(),r;try{r=await n.reserve()}catch{return await t()}let s=!1;try{return await r.advisoryLock(Dc),s=!0,await t()}finally{try{if(s)await r.advisoryUnlock(Dc)}finally{r.release?.()}}}async function Hm(e){await Jr();let t=ln(),n=Ac(t),r=_.dialect||"postgres",i=Ec(n).filter((o)=>o.endsWith(".sql")).sort();if(i.length===0)return re("-- No migration files found to execute"),!0;re(`-- Found ${i.length} script files to execute`);try{let o=ie();return await Wg(r,async()=>{await Nc(o,r);let l=await Jg(o,r),a=i.filter((c)=>!l.includes(c));if(a.length===0)return re("-- No pending migrations to execute"),!0;re(`-- Executing ${a.length} migration${a.length===1?"":"s"}`);for(let c of a){let u=tt(n,c);re(`-- Executing: ${c}`);try{if(Sc(r)&&!jg.test(sr(u,"utf-8")))await o.transaction(async(h)=>{await h.file(u),await Ts(h,c,r)});else if(await o.file(u),await Ts(o,c,r),!Sc(r))re(`-- (${r} commits DDL implicitly, so ${c} was not applied atomically)`);else re(`-- (${c} contains a statement that cannot run in a transaction, so it was not applied atomically)`);re(`-- \u2713 Migration ${c} executed and recorded`)}catch(m){if(kc(n,c)&&Fg(m)){await Ts(o,c,r),re(`-- \u2713 Migration ${c} was already applied; recorded it (${m instanceof Error?m.message:String(m)})`);continue}throw console.error(`-- \u2717 Migration ${c} failed:`,m),m}}return re("-- All migrations executed successfully"),!0})}catch(o){throw console.error("-- Migration execution failed:",o),o}return!0}async function zm(e,t={}){if(await Jr(),!e)e=tt(ji.cwd(),"app/Models");let n=t.dialect||_.dialect||"postgres",r=Tt(n),s=ln(),i=async(o)=>{let l=r.dropTable(o);await ci(async(a)=>{if(n==="sqlite")await a.unsafe("PRAGMA foreign_keys = OFF").execute();if(n==="mysql"||n==="vitess")await a.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await a.unsafe(l).execute()}finally{if(n==="sqlite")await a.unsafe("PRAGMA foreign_keys = ON").execute();if(n==="mysql"||n==="vitess")await a.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await i("migrations"),re("-- Dropped migrations table")}catch(a){console.error(a)}let o=[],l=[];try{let a=await mt({modelsDir:e}),c=Xn(a,{dialect:n});o=c.tables.map((m)=>m.table);let u=new Set;for(let m of c.tables)for(let h of m.columns)if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let w=`${m.table}_${h.name}_type`;u.add(w)}l=Array.from(u)}catch(a){console.error(a),o=[],l=[]}if(o.length===0)re("-- No tables found to drop");else{re(`-- Dropping ${o.length} tables: ${o.join(", ")}`);for(let a of o.reverse())try{await i(a),re(`-- Dropped table: ${a}`)}catch(c){console.error(c),re(`-- Table ${a} may not exist, skipping drop`)}}if(l.length>0){re(`-- Dropping ${l.length} enum types: ${l.join(", ")}`);for(let a of l)try{let c=r.dropEnumType(a);if(c)await ci(async(u)=>{await u.unsafe(c).execute(),re(`-- Dropped enum type: ${a}`)})}catch(c){console.error(c),re(`-- Enum type ${a} may not exist, skipping drop`)}}else re("-- No enum types found to drop");if(o.length>0&&!t.preserveMigrationState)try{await Ug(e,s,t)}catch(a){console.error(a),re("-- Could not clean up migration files")}else if(o.length===0)re("-- No models directory found; keeping committed migration files in place");else re("-- Preserving migration files and model snapshot for fresh replay");if(!t.preserveMigrationState)try{await Vg(s)}catch(a){console.error(a),re("-- Could not clear generated directory")}return re("-- Database reset completed successfully"),!0}catch(o){return console.error("-- Database reset failed:",o),!1}}async function Ug(e,t,n={}){if(!e)e=tt(ji.cwd(),"app/Models");if(!t)t=ln();let r=String(n.dialect||_.dialect||"postgres"),s=Wi(t,r);if(Pt(s))qi(s),re(`-- Removed model snapshot file: ${s}`);let i=tt(e,`.qb-migrations.${r}.json`),o=String(n.state||i);if(Pt(o))qi(o),re(`-- Removed legacy migration state file: ${o}`);Qg(At(t,_.migrationDir))}function Qg(e){if(!Pt(e))return;let t=0,n=[];for(let r of Ec(e).filter((s)=>s.endsWith(".sql"))){if(!kc(e,r)){n.push(r);continue}qi(tt(e,r)),re(`-- Removed generated migration file: ${r}`),t+=1}if(re(`-- Cleaned up ${t} generated migration file${t===1?"":"s"} from migrations directory`),n.length>0)re(`-- Kept ${n.length} hand-written migration${n.length===1?"":"s"}: ${n.slice(0,5).join(", ")}${n.length>5?`, +${n.length-5} more`:""}`)}async function GD(e,t){}async function Vg(e){if(!e)e=ln();let t=tt(e,"generated");if(Pt(t))try{xc(t,{recursive:!0,force:!0}),re("-- Cleared generated directory")}catch(n){console.error("-- Failed to clear generated directory:",n)}}async function Nc(e,t){let r=Tt(t).createMigrationsTable();try{await e.unsafe(r).execute(),re("-- Migrations table ready")}catch(s){throw console.error("-- Failed to create migrations table:",s),s}}async function Jg(e,t){let n=Tt(t);try{return(await e.unsafe(n.getExecutedMigrationsQuery()).execute()).map((s)=>s.migration)}catch(r){return console.error("-- Failed to get executed migrations:",r),[]}}async function Ts(e,t,n){let r=Tt(n);try{re(`-- Recording migration: ${t}`),await e.unsafe(r.recordMigrationQuery(),[t]).execute(),re(`-- Successfully recorded migration: ${t}`)}catch(s){throw console.error(`-- Failed to record migration ${t}:`,s),s}}
446
- export{ne as a,Sa as b,_ as c,Vr as d,Z as e,ve as f,Jr as g,xa as h,jh as i,Zd as j,ef as k,Wn as l,Oa as m,pf as n,di as o,Ft as p,bf as q,Tf as r,qt as s,en as t,Op as u,Df as v,qp as w,ot as x,Sf as y,xf as z,ie as A,qa as B,ja as C,_f as D,If as E,Lf as F,Wa as G,Ff as H,Wf as I,Uf as J,Qf as K,Ua as L,Vf as M,Qa as N,Va as O,Jf as P,Hf as Q,Ja as R,zf as S,Gf as T,Ha as U,mi as V,Ga as W,gi as X,dm as Y,Ie as Z,Gr as _,Yr as $,Xr as aa,es as ba,Tt as ca,Jm as da,Ti as ea,Hm as fa,zm as ga,Ug as ha,GD as ia,Vg as ja,fm as ka,wm as la,ol as ma,$m as na,ll as oa,Rm as pa,dl as qa,fl as ra,yl as sa,Lm as ta,Km as ua,Fm as va,qm as wa,jm as xa,Tl as ya,Qm as za,Vm as Aa,Dl as Ba,Nl as Ca,$l as Da,El as Ea,aw as Fa,lw as Ga,Pl as Ha,_l as Ia,cw as Ja,uw as Ka,Fl as La,ql as Ma,jl as Na,Wl as Oa,Ul as Pa,Mi as Qa,Ql as Ra,ug as Sa,Vt as Ta,Dt as Ua,hw as Va,pw as Wa,bw as Xa,Vl as Ya,Jl as Za,Hl as _a,zl as $a,Gl as ab,Dw as bb,Yl as cb,dg as db,$w as eb,Ew as fb,xw as gb,Rw as hb,Xl as ib,Mw as jb,Ow as kb,Bw as lb,as as mb,mt as nb,rc as ob,uc as pb,dc as qb,fc as rb,mc as sb,xg as tb,Xn as ub,bs as vb,nD as wb,rD as xb,hc as yb,Ii as zb,Ot as Ab,Li as Bb,Fi as Cb,Og as Db,iD as Eb,Bg as Fb,aD as Gb,bc as Hb,Tc as Ib,wc as Jb,Pg as Kb,_g as Lb};
443
+ `);i(M,`alter-${E.table}-table`)}}if(Pt+zt===0)Ke("-- Nothing to migrate");else{let g=[];if(Pt>0)g.push(`${Pt} created`);if(zt>0)g.push(`${zt} updated`);Ke(`-- Migration files: ${g.join(", ")}`)}return{statements:o.length===0?["-- No changes detected"]:o,operations:l}}function Bg(e,t,n={}){return qi(e,t,n).statements}Mi();function aD(e){return e}class Pg{get order(){return 100}get description(){return}}function cD(e){return e}tr();tr();ns();Hr();Me();function Tc(e){switch(e){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":case"timestamptz":return"date";case"json":return"json";default:return"other"}}function wc(e){let t=String(e??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(t)||t==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(t))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(t))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test(t))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(t))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(t))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(t)||/^float\d*\b/.test(t))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(t)||/^int\d*\b/.test(t))return"integer";return"other"}function Dc(e,t,n){if(e===t)return!0;if(n==="sqlite"){if(e==="boolean"&&t==="integer")return!0;if((e==="date"||e==="json")&&t==="text")return!0}if(ne(n)&&e==="boolean"&&t==="integer")return!0;if(e==="varchar"&&t==="text")return!0;if(e==="integer"&&t==="fractional")return!0;if(e==="other"||t==="other")return!0;return!1}async function _g(e,t={}){let n=t.dialect??_.dialect,r=e.tables.map((c)=>c.table),s=await pi({tables:r}),i=new Map(s.map((c)=>[c.table.toLowerCase(),c])),o=[],l=[],a=[];for(let c of e.tables){let u=i.get(c.table.toLowerCase());if(!u){o.push(c.table);continue}let m=new Map(u.columns.map((h)=>[h.name.toLowerCase(),h]));for(let h of c.columns){let w=m.get(h.name.toLowerCase()),N=Tc(h.type);if(!w){l.push({table:c.table,column:h.name,expected:N});continue}let R=wc(w.sqlType);if(!Dc(N,R,n))a.push({table:c.table,column:h.name,expected:N,actual:R,actualSqlType:w.sqlType})}}return{missingTables:o,missingColumns:l,typeMismatches:a,clean:o.length===0&&l.length===0&&a.length===0}}function Ig(e){if(e.clean)return"";let t=[];if(e.missingTables.length>0)t.push(` Missing tables: ${e.missingTables.join(", ")}`);for(let s of e.missingColumns.slice(0,10))t.push(` \u2022 ${s.table}.${s.column} is missing (models declare ${s.expected})`);for(let s of e.typeMismatches.slice(0,10))t.push(` \u2022 ${s.table}.${s.column} is ${s.actualSqlType}, models declare ${s.expected}`);let n=Math.min(e.missingColumns.length,10)+Math.min(e.typeMismatches.length,10),r=e.missingColumns.length+e.typeMismatches.length;if(r>n)t.push(` + ${r-n} more`);return["The live schema does not match the models.",...t,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
444
+ `)}async function Fg(e,t,n){if(n.length===0)return;let r=Nc(an());try{await Mc(e,t);for(let s of n)await Ss(e,s,t),re(`-- \u2713 Recorded applied migration: ${s}`)}catch(s){re(`-- Could not record applied migrations (the schema change itself succeeded): ${s instanceof Error?s.message:String(s)}`)}}function Cc(e,t){try{return mc(sr(tt(e,t),"utf8"))}catch{return!1}}function qg(e){let t=e instanceof Error?e.message:String(e);return/duplicate column name/i.test(t)||/duplicate key name/i.test(t)||/duplicate foreign key constraint name/i.test(t)||/\balready exists\b/i.test(t)}function re(e){if(_.verbose)console.log(e)}function vc(e){return tt(e,_.snapshotDir||".qb")}function Ui(e,t){return tt(vc(e),`model-snapshot.${t}.json`)}function jg(e,t){let n=Ui(e,t);if(!_t(n))return;try{let r=sr(n,"utf8"),s=JSON.parse(r);if(s?.plan&&Array.isArray(s.plan.tables)&&s.plan.dialect)return s.plan;if(Array.isArray(s?.tables)&&s?.dialect)return s;re("-- Invalid snapshot format, treating as no previous state");return}catch(r){re(`-- Could not load snapshot, treating as no previous state: ${r instanceof Error?r.message:String(r)}`);return}}function Ac(e,t,n){let r=Ui(e,t),s=vc(e),i=pc(n);if(_t(r))try{let l=JSON.parse(sr(r,"utf8"));if(l?.hash===i&&l?.dialect===t&&l?.plan){re("-- Model snapshot unchanged");return}}catch{}if(!_t(s))Ec(s,{recursive:!0}),re(`-- Created snapshot directory: ${s}`);let o={plan:n,hash:i,dialect:t,updatedAt:new Date().toISOString()};kc(r,JSON.stringify(o,null,2)),re(`-- Model snapshot saved to ${r}`)}function Hm(e,t={}){let n=t.dialect??e.dialect;Ac(t.workspaceRoot??an(),n,e)}function an(){return $i()}function Nc(e){let t=Nt(e,_.migrationDir);if(!_t(t))Ec(t,{recursive:!0}),re(`-- Created SQL directory: ${t}`);return t}async function Si(e,t={}){if(await Jr(),!e)e=tt(Wi.cwd(),"app/Models");let n=t.dialect||_.dialect||"postgres",r=an(),s=await mt({modelsDir:e}),i=Zn(s,{dialect:n,vitessSharded:t.vitessSharded}),o,l=!1;if(!t.full)if(o=jg(r,n),o)re("-- Comparing with stored model snapshot");else{let w=tt(e,`.qb-migrations.${n}.json`),N=String(t.state||w);if(_t(N))try{let R=sr(N,"utf8"),y=JSON.parse(R);if(o=y?.plan&&y.plan.tables?y.plan:y?.tables?y:void 0,o)re("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!o||t.fromDb)try{let R=await el(n),y=new Set(i.tables.map((g)=>g.table)),b=R.tables.filter((g)=>y.has(g.table));if(b.length>0)o={dialect:R.dialect,tables:b},l=!0,re(`-- No snapshot; reconciling against live database (${b.length} matching table${b.length===1?"":"s"})`)}catch(R){re(`-- Could not introspect live database, treating as no previous state: ${R instanceof Error?R.message:String(R)}`)}if(!o)re("-- No previous snapshot found, generating full migration")}else re("-- Full migration requested, ignoring any previous state");let a=t.full?{statements:Ds(i,{dryRun:t.dryRun}),operations:i.tables.map((w)=>({kind:"create_table",table:w.table,destructive:!1,sql:""}))}:qi(o,i,{applyRenames:t.applyRenames,dryRun:t.dryRun,preserveUnknownColumns:l}),c=a.statements,u=a.operations,m=c.join(`
445
+ `),h=c.some((w)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(w));if(t.apply){let w=Lg(tt(Kg(),"qb-migrate-")),N=tt(w,"migration.sql");try{if(h){kc(N,m);let R=ie();await R.file(N),re("-- Migration applied"),await Fg(R,n,dc())}else re("-- No changes; nothing to apply")}catch(R){throw console.error("-- Migration failed:",R),R}finally{Rc(w,{recursive:!0,force:!0})}}if(!t.dryRun)Ac(r,n,i);return{sql:m,sqlStatements:c,hasChanges:h,plan:i,operations:u}}var Sc="bun-query-builder:migrate",Wg=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function $c(e){return e==="postgres"||e==="sqlite"}async function Ug(e,t){if(e==="sqlite")return await t();let n=ie(),r;try{r=await n.reserve()}catch{return await t()}let s=!1;try{return await r.advisoryLock(Sc),s=!0,await t()}finally{try{if(s)await r.advisoryUnlock(Sc)}finally{r.release?.()}}}async function zm(e){await Jr();let t=an(),n=Nc(t),r=_.dialect||"postgres",i=xc(n).filter((o)=>o.endsWith(".sql")).sort();if(i.length===0)return re("-- No migration files found to execute"),!0;re(`-- Found ${i.length} script files to execute`);try{let o=ie();return await Ug(r,async()=>{await Mc(o,r);let l=await Hg(o,r),a=i.filter((c)=>!l.includes(c));if(a.length===0)return re("-- No pending migrations to execute"),!0;re(`-- Executing ${a.length} migration${a.length===1?"":"s"}`);for(let c of a){let u=tt(n,c);re(`-- Executing: ${c}`);try{if($c(r)&&!Wg.test(sr(u,"utf-8")))await o.transaction(async(h)=>{await h.file(u),await Ss(h,c,r)});else if(await o.file(u),await Ss(o,c,r),!$c(r))re(`-- (${r} commits DDL implicitly, so ${c} was not applied atomically)`);else re(`-- (${c} contains a statement that cannot run in a transaction, so it was not applied atomically)`);re(`-- \u2713 Migration ${c} executed and recorded`)}catch(m){if(Cc(n,c)&&qg(m)){await Ss(o,c,r),re(`-- \u2713 Migration ${c} was already applied; recorded it (${m instanceof Error?m.message:String(m)})`);continue}throw console.error(`-- \u2717 Migration ${c} failed:`,m),m}}return re("-- All migrations executed successfully"),!0})}catch(o){throw console.error("-- Migration execution failed:",o),o}return!0}async function Gm(e,t={}){if(await Jr(),!e)e=tt(Wi.cwd(),"app/Models");let n=t.dialect||_.dialect||"postgres",r=Tt(n),s=an(),i=async(o)=>{let l=r.dropTable(o);await fi(async(a)=>{if(n==="sqlite")await a.unsafe("PRAGMA foreign_keys = OFF").execute();if(n==="mysql"||n==="vitess")await a.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await a.unsafe(l).execute()}finally{if(n==="sqlite")await a.unsafe("PRAGMA foreign_keys = ON").execute();if(n==="mysql"||n==="vitess")await a.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await i("migrations"),re("-- Dropped migrations table")}catch(a){console.error(a)}let o=[],l=[];try{let a=await mt({modelsDir:e}),c=Zn(a,{dialect:n});o=c.tables.map((m)=>m.table);let u=new Set;for(let m of c.tables)for(let h of m.columns)if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let w=`${m.table}_${h.name}_type`;u.add(w)}l=Array.from(u)}catch(a){console.error(a),o=[],l=[]}if(o.length===0)re("-- No tables found to drop");else{re(`-- Dropping ${o.length} tables: ${o.join(", ")}`);for(let a of o.reverse())try{await i(a),re(`-- Dropped table: ${a}`)}catch(c){console.error(c),re(`-- Table ${a} may not exist, skipping drop`)}}if(l.length>0){re(`-- Dropping ${l.length} enum types: ${l.join(", ")}`);for(let a of l)try{let c=r.dropEnumType(a);if(c)await fi(async(u)=>{await u.unsafe(c).execute(),re(`-- Dropped enum type: ${a}`)})}catch(c){console.error(c),re(`-- Enum type ${a} may not exist, skipping drop`)}}else re("-- No enum types found to drop");if(o.length>0&&!t.preserveMigrationState)try{await Qg(e,s,t)}catch(a){console.error(a),re("-- Could not clean up migration files")}else if(o.length===0)re("-- No models directory found; keeping committed migration files in place");else re("-- Preserving migration files and model snapshot for fresh replay");if(!t.preserveMigrationState)try{await Jg(s)}catch(a){console.error(a),re("-- Could not clear generated directory")}return re("-- Database reset completed successfully"),!0}catch(o){return console.error("-- Database reset failed:",o),!1}}async function Qg(e,t,n={}){if(!e)e=tt(Wi.cwd(),"app/Models");if(!t)t=an();let r=String(n.dialect||_.dialect||"postgres"),s=Ui(t,r);if(_t(s))ji(s),re(`-- Removed model snapshot file: ${s}`);let i=tt(e,`.qb-migrations.${r}.json`),o=String(n.state||i);if(_t(o))ji(o),re(`-- Removed legacy migration state file: ${o}`);Vg(Nt(t,_.migrationDir))}function Vg(e){if(!_t(e))return;let t=0,n=[];for(let r of xc(e).filter((s)=>s.endsWith(".sql"))){if(!Cc(e,r)){n.push(r);continue}ji(tt(e,r)),re(`-- Removed generated migration file: ${r}`),t+=1}if(re(`-- Cleaned up ${t} generated migration file${t===1?"":"s"} from migrations directory`),n.length>0)re(`-- Kept ${n.length} hand-written migration${n.length===1?"":"s"}: ${n.slice(0,5).join(", ")}${n.length>5?`, +${n.length-5} more`:""}`)}async function XD(e,t){}async function Jg(e){if(!e)e=an();let t=tt(e,"generated");if(_t(t))try{Rc(t,{recursive:!0,force:!0}),re("-- Cleared generated directory")}catch(n){console.error("-- Failed to clear generated directory:",n)}}async function Mc(e,t){let r=Tt(t).createMigrationsTable();try{await e.unsafe(r).execute(),re("-- Migrations table ready")}catch(s){throw console.error("-- Failed to create migrations table:",s),s}}async function Hg(e,t){let n=Tt(t);try{return(await e.unsafe(n.getExecutedMigrationsQuery()).execute()).map((s)=>s.migration)}catch(r){return console.error("-- Failed to get executed migrations:",r),[]}}async function Ss(e,t,n){let r=Tt(n);try{re(`-- Recording migration: ${t}`),await e.unsafe(r.recordMigrationQuery(),[t]).execute(),re(`-- Successfully recorded migration: ${t}`)}catch(s){throw console.error(`-- Failed to record migration ${t}:`,s),s}}
446
+ export{ne as a,$a as b,_ as c,Vr as d,Z as e,ve as f,Jr as g,Ra as h,Wh as i,ef as j,tf as k,Un as l,gf as m,bf as n,gi as o,qt as p,Tf as q,wf as r,jt as s,en as t,Bp as u,Sf as v,jp as w,ot as x,$f as y,Rf as z,ie as A,ja as B,Wa as C,If as D,Lf as E,Kf as F,Ua as G,qf as H,Uf as I,Qf as J,Vf as K,Qa as L,Jf as M,Va as N,Ja as O,Hf as P,zf as Q,Ha as R,Gf as S,Yf as T,za as U,hi as V,Ya as W,pi as X,fm as Y,Ie as Z,Gr as _,Yr as $,Xr as aa,es as ba,Tt as ca,Hm as da,Si as ea,zm as fa,Gm as ga,Qg as ha,XD as ia,Jg as ja,mm as ka,Dm as la,al as ma,Em as na,cl as oa,km as pa,fl as qa,ml as ra,hl as sa,Km as ta,Fm as ua,qm as va,jm as wa,Wm as xa,wl as ya,Vm as za,Jm as Aa,Sl as Ba,Ml as Ca,El as Da,xl as Ea,lw as Fa,cw as Ga,uw as Ha,_l as Ia,Il as Ja,dw as Ka,fw as La,ql as Ma,jl as Na,Wl as Oa,Ul as Pa,Ql as Qa,Oi as Ra,Vl as Sa,dg as Ta,Jt as Ua,St as Va,bw as Wa,Tw as Xa,ww as Ya,Jl as Za,Hl as _a,zl as $a,Gl as ab,Yl as bb,$w as cb,Xl as db,fg as eb,xw as fb,Rw as gb,kw as hb,Cw as ib,Zl as jb,Bw as kb,Pw as lb,_w as mb,as as nb,mt as ob,sc as pb,dc as qb,fc as rb,mc as sb,gc as tb,Rg as ub,Zn as vb,Ds as wb,sD as xb,iD as yb,pc as zb,Li as Ab,Bt as Bb,Ki as Cb,qi as Db,Bg as Eb,aD as Fb,Pg as Gb,cD as Hb,Tc as Ib,wc as Jb,Dc as Kb,_g as Lb,Ig as Mb};