bun-query-builder 0.2.51 → 0.2.53

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.
@@ -0,0 +1,445 @@
1
+ // @bun
2
+ import{Rb as q1,Ub as T1}from"./chunk-fkjeeh31.js";import{Wb as a8}from"./chunk-605xwkdk.js";import{nc as gU,oc as oU,pc as z8,qc as sZ}from"./chunk-c6mb5jxz.js";import{existsSync as f0,statSync as g0}from"fs";import{resolve as T9}from"path";import kJ from"process";import{existsSync as yJ,mkdirSync as n2,readdirSync as i2,readFileSync as hJ,writeFileSync as l2}from"fs";import{homedir as z9}from"os";import{dirname as r2,resolve as V8}from"path";import v$ from"process";import{existsSync as p0,statSync as d0}from"fs";import{existsSync as x7,mkdirSync as bJ,readdirSync as fJ,writeFileSync as gJ}from"fs";import{homedir as H9}from"os";import{dirname as m0,resolve as nZ}from"path";import o8 from"process";import{join as pJ,relative as dJ,resolve as c0}from"path";import D$ from"process";import{existsSync as PY,mkdirSync as Uz,readdirSync as zz,writeFileSync as Hz}from"fs";import{homedir as V7}from"os";import{dirname as jz,resolve as uZ}from"path";import x9 from"process";import{join as mJ,relative as cJ,resolve as u0}from"path";import E$ from"process";import{existsSync as qY,mkdirSync as Lz,readdirSync as Fz,writeFileSync as Bz}from"fs";import{dirname as Oz,resolve as I$}from"path";import v7 from"process";import{Buffer as x8}from"buffer";import{createCipheriv as uJ,createDecipheriv as nJ,randomBytes as K7}from"crypto";import{closeSync as L7,createReadStream as n0,createWriteStream as iJ,existsSync as F7,fsyncSync as i0,openSync as l0,writeFileSync as lJ}from"fs";import{access as sJ,constants as s0,mkdir as oJ,readdir as Y$,rename as o0,stat as A9,unlink as X$,writeFile as B7}from"fs/promises";import{join as W9}from"path";import fZ from"process";import{pipeline as rJ}from"stream/promises";import{createGzip as r0}from"zlib";import j9 from"process";import O8 from"process";import{Buffer as B8}from"buffer";import{createCipheriv as aJ,createDecipheriv as tJ,randomBytes as R7}from"crypto";import{closeSync as O7,createReadStream as a0,createWriteStream as eJ,existsSync as J$,fsyncSync as t0,openSync as e0,writeFileSync as ZG}from"fs";import{access as $G,constants as ZY,mkdir as YG,readdir as G$,rename as $Y,stat as Q9,unlink as U$,writeFile as D7}from"fs/promises";import{isAbsolute as XG,join as _9,resolve as JG}from"path";import QZ from"process";import{pipeline as GG}from"stream/promises";import{createGzip as YY}from"zlib";import V9 from"process";import D8 from"process";import z$ from"process";import{existsSync as H$}from"fs";import{resolve as E7}from"path";import{existsSync as UG}from"fs";import{existsSync as zG,readdirSync as HG}from"fs";import{extname as I7,resolve as XY}from"path";import AG from"process";import{join as WG,relative as jG,resolve as JY}from"path";import M$ from"process";import{Buffer as R8}from"buffer";import{createCipheriv as QG,createDecipheriv as _G,randomBytes as M7}from"crypto";import{closeSync as w7,createReadStream as GY,createWriteStream as VG,existsSync as A$,fsyncSync as UY,openSync as zY,writeFileSync as KG}from"fs";import{access as LG,constants as HY,mkdir as FG,readdir as W$,rename as AY,stat as K9,unlink as j$,writeFile as C7}from"fs/promises";import{isAbsolute as BG,join as L9,resolve as RG}from"path";import _Z from"process";import{pipeline as OG}from"stream/promises";import{createGzip as WY}from"zlib";import F9 from"process";import E8 from"process";import _$ from"process";import{existsSync as V$}from"fs";import{resolve as MY}from"path";import{existsSync as p5}from"fs";class wY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Z={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Z}}generateKey(Z,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${Z}${Y}`}isExpired(Z){return Date.now()-Z.timestamp.getTime()>Z.ttl}estimateSize(Z){try{return JSON.stringify(Z).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Z=Array.from(this.cache.entries()).sort(([,Y],[,X])=>Y.timestamp.getTime()-X.timestamp.getTime()),$=Z.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(Z[Y][0])}set(Z,$,Y,X){if(!this.options.enabled)return;let J=this.generateKey(Z,Y),G=X??this.options.ttl,U=this.estimateSize($);this.cache.set(J,{value:$,timestamp:new Date,ttl:G,hits:0,size:U}),this.evictIfNeeded()}get(Z,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Z,$),X=this.cache.get(Y);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(Y),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified(Z,$){try{if(!f0(Z))return!0;return g0(Z).mtime>$}catch{return!0}}getWithFileCheck(Z,$){let Y=this.get(Z,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(Z,$);return}return Y.value}setWithFileCheck(Z,$,Y,X){try{let J=f0(Y)?g0(Y):null,G=J?J.mtime:new Date;this.set(Z,{value:$,fileTimestamp:G},Y,X)}catch{this.set(Z,$,Y,X)}}delete(Z,$){let Y=this.generateKey(Z,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Z=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),Z++;return Z}getStats(){let Z=Array.from(this.cache.values()),$=Z.reduce((X,J)=>X+J.size,0),Y=Z.map((X)=>X.timestamp).sort();return{size:$,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Z={};for(let[$,Y]of this.cache.entries())Z[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Z}import(Z){this.cache.clear();for(let[$,Y]of Object.entries(Z))if(typeof Y==="object"&&Y!==null){let X=Y;this.cache.set($,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class CY{metrics=[];maxMetrics=1000;async track(Z,$,Y={}){let X=performance.now(),J=new Date;try{let G=await $(),U=performance.now()-X;return this.recordMetric({operation:Z,duration:U,timestamp:J,...Y}),G}catch(G){let U=performance.now()-X;throw this.recordMetric({operation:`${Z}:error`,duration:U,timestamp:J,...Y}),G}}recordMetric(Z){if(this.metrics.push(Z),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Z){let $=Z?this.metrics.filter((J)=>J.operation===Z):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((J)=>J.duration),X=Y.reduce((J,G)=>J+G,0);return{count:$.length,averageDuration:X/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:X,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Z){return this.metrics.filter(($)=>$.duration>Z)}}function NY(Z={}){let{name:$="",alias:Y}=Z,X=["config",".config"];if($)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let G of J){if(!G)continue;if(X.push(G,`.${G}.config`,`${G}.config`,`.${G}`),$)X.push(`${$}.${G}.config`,`.${$}.${G}.config`)}return Array.from(new Set(X.filter(Boolean)))}function xJ(Z){return NY(Z).flatMap((Y)=>SY.map((X)=>T9(Z.directory,`${Y}${X}`)))}function vJ(Z={}){let $=T9(Z.cwd||kJ.cwd());return Array.from(new Set([$,T9($,"config"),T9($,".config"),Z.configDir?T9($,Z.configDir):void 0].filter((Y)=>Boolean(Y))))}function IG(Z,$){this[Z]=EG.bind(null,$)}class i7{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Z={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Z}}generateKey(Z,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${Z}${Y}`}isExpired(Z){return Date.now()-Z.timestamp.getTime()>Z.ttl}estimateSize(Z){try{return JSON.stringify(Z).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Z=Array.from(this.cache.entries()).sort(([,Y],[,X])=>Y.timestamp.getTime()-X.timestamp.getTime()),$=Z.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(Z[Y][0])}set(Z,$,Y,X){if(!this.options.enabled)return;let J=this.generateKey(Z,Y),G=X??this.options.ttl,U=this.estimateSize($);this.cache.set(J,{value:$,timestamp:new Date,ttl:G,hits:0,size:U}),this.evictIfNeeded()}get(Z,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Z,$),X=this.cache.get(Y);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(Y),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified(Z,$){try{if(!p0(Z))return!0;return d0(Z).mtime>$}catch{return!0}}getWithFileCheck(Z,$){let Y=this.get(Z,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(Z,$);return}return Y.value}setWithFileCheck(Z,$,Y,X){try{let J=p0(Y)?d0(Y):null,G=J?J.mtime:new Date;this.set(Z,{value:$,fileTimestamp:G},Y,X)}catch{this.set(Z,$,Y,X)}}delete(Z,$){let Y=this.generateKey(Z,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Z=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),Z++;return Z}getStats(){let Z=Array.from(this.cache.values()),$=Z.reduce((X,J)=>X+J.size,0),Y=Z.map((X)=>X.timestamp).sort();return{size:$,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Z={};for(let[$,Y]of this.cache.entries())Z[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Z}import(Z){this.cache.clear();for(let[$,Y]of Object.entries(Z))if(typeof Y==="object"&&Y!==null){let X=Y;this.cache.set($,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class l7{metrics=[];maxMetrics=1000;async track(Z,$,Y={}){let X=performance.now(),J=new Date;try{let G=await $(),U=performance.now()-X;return this.recordMetric({operation:Z,duration:U,timestamp:J,...Y}),G}catch(G){let U=performance.now()-X;throw this.recordMetric({operation:`${Z}:error`,duration:U,timestamp:J,...Y}),G}}recordMetric(Z){if(this.metrics.push(Z),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Z){let $=Z?this.metrics.filter((J)=>J.operation===Z):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((J)=>J.duration),X=Y.reduce((J,G)=>J+G,0);return{count:$.length,averageDuration:X/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:X,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Z){return this.metrics.filter(($)=>$.duration>Z)}}function CG(Z,$={}){let X=Object.keys($).sort().map((J)=>`${J}:${$[J]}`).join("|");return X?`${Z}:${X}`:Z}function SG(Z,$){try{return JSON.stringify(Z)===JSON.stringify($)}catch{return Z===$}}function NG(Z){return Z.getStats().size*2}function s7(Z,$){if(Array.isArray($)&&Array.isArray(Z)&&$.length===2&&Z.length===2&&MZ($[0])&&"id"in $[0]&&$[0].id===3&&MZ($[1])&&"id"in $[1]&&$[1].id===4)return $;if(MZ($)&&MZ(Z)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return Z;if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray($)&&Array.isArray(Z)){if(MZ(Z)&&"arr"in Z&&Array.isArray(Z.arr)&&MZ($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Z.length>0&&MZ($[0])&&MZ(Z[0])){let X=[...$];for(let J of Z)if(MZ(J)&&"name"in J){if(!X.find((U)=>MZ(U)&&("name"in U)&&U.name===J.name))X.push(J)}else if(MZ(J)&&"path"in J){if(!X.find((U)=>MZ(U)&&("path"in U)&&U.path===J.path))X.push(J)}else if(!X.some((G)=>w$(G,J)))X.push(J);return X}if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}if(!MZ($)||!MZ(Z))return $;let Y={...Z};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let J=$[X];if(J===null||J===void 0)continue;else if(MZ(J)&&MZ(Y[X]))Y[X]=s7(Y[X],J);else if(Array.isArray(J)&&Array.isArray(Y[X]))if(J.length>0&&Y[X].length>0&&MZ(J[0])&&MZ(Y[X][0])){let G=[...J];for(let U of Y[X])if(MZ(U)&&"name"in U){if(!G.find((z)=>MZ(z)&&("name"in z)&&z.name===U.name))G.push(U)}else if(MZ(U)&&"path"in U){if(!G.find((z)=>MZ(z)&&("path"in z)&&z.path===U.path))G.push(U)}else if(!G.some((H)=>w$(H,U)))G.push(U);Y[X]=G}else if(J.every((G)=>typeof G==="string")&&Y[X].every((G)=>typeof G==="string")){let G=[...J];for(let U of Y[X])if(!G.includes(U))G.push(U);Y[X]=G}else Y[X]=J;else Y[X]=J}return Y}function w$(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!w$(Z[Y],$[Y]))return!1;return!0}if(MZ(Z)&&MZ($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!w$(Z[J],$[J]))return!1}return!0}return!1}function MZ(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}async function PG(Z,$){if(!qY(Z))return null;try{let Y=await import(Z),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return s7($,X)}catch{return null}}catch{return null}}async function qG({name:Z="",cwd:$,defaultConfig:Y}){let X=$||v7.cwd(),J=[".ts",".js",".mjs",".cjs",".json"],G=[`${Z}.config`,`.${Z}.config`,Z,`.${Z}`];for(let U of G)for(let H of J){let z=I$(X,`${U}${H}`),A=await PG(z,Y);if(A!==null)return A}try{let U=I$(X,"package.json");if(qY(U)){let z=(await import(U))[Z];if(z&&typeof z==="object"&&!Array.isArray(z))try{return s7(Y,z)}catch{}}}catch{}return Y}function TG(Z,$={}){let Y=E$.cwd();while(Y.includes("storage"))Y=u0(Y,"..");let X=u0(Y,Z||"");if($?.relative)return cJ(E$.cwd(),X);return X}async function kG(){try{let Z=await qG({name:"clarity",defaultConfig:L$,cwd:E$.cwd(),endpoint:"",headers:{}});return{...L$,...Z}}catch{return L$}}function CZ(){if(O8.env.NODE_ENV==="test"||O8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xG(){if(O8.env.NODE_ENV==="test"||O8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O8<"u"){let Z=O8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(O8.versions&&(O8.versions.node||O8.versions.bun))}return!1}class kY{async format(Z){let $=await xG(),Y=await this.getMetadata($);return JSON.stringify({timestamp:Z.timestamp.toISOString(),level:Z.level,name:Z.name,message:Z.message,metadata:Y})}async getMetadata(Z){if(Z){let{hostname:$}=await import("os");return{pid:j9.pid,hostname:$(),environment:j9.env.NODE_ENV||"development",platform:j9.platform,version:j9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:j9.env.NODE_ENV||j9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class C${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(Z,$={}){this.name=Z,this.config={...h7},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new kY,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??fZ.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},X=$.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Z){if(!Z.fingersCrossedEnabled&&Z.fingersCrossed)return{...F$,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...F$};return{...F$,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:h7.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(Z).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(Z){let Y=(async()=>{let J,G=0,U=3,H=1000;while(G<U)try{try{try{await sJ(this.config.logDirectory,s0.F_OK|s0.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await oJ(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let z=this.validateEncryptionConfig()?(await this.encrypt(Z)).encrypted:x8.from(Z);try{if(!F7(this.currentLogFile))await B7(this.currentLogFile,"",{mode:420});if(J=l0(this.currentLogFile,"a",420),lJ(J,z,{flag:"a"}),i0(J),J!==void 0)L7(J),J=void 0;if((await A9(this.currentLogFile)).size===0){if(await B7(this.currentLogFile,z,{flag:"w",mode:420}),(await A9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let W=A;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(G<U-1){let Q=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${U}:`,Q);let R=H*2**G;await new Promise((O)=>setTimeout(O,R)),G++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{L7(J)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(z){if(G===U-1){let W=z,Q=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Q),z}G++;let A=H*2**(G-1);await new Promise((W)=>setTimeout(W,A))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,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 W9(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 W9(this.config.logDirectory,`${this.name}.log`);let Z=new Date().toISOString().split("T")[0];return W9(this.config.logDirectory,`${this.name}-${Z}.log`)}setupRotation(){if(CZ())return;if(typeof this.config.rotation==="boolean")return;let Z=this.config.rotation,$;switch(Z.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,z])=>z.createdAt.getTime()-H.createdAt.getTime()),G=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,G);if(J.length>U)for(let[H]of J.slice(U))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return K7(16).toString("hex")}generateKey(){return K7(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Z=this.keys.get(this.currentKeyId);if(!Z)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Z,id:this.currentKeyId}}encrypt(Z){let{key:$}=this.getCurrentKey(),Y=K7(16),X=uJ("aes-256-gcm",$,Y),J=x8.concat([X.update(Z,"utf8"),X.final()]),G=X.getAuthTag();return{encrypted:x8.concat([Y,J,G]),iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=r0(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(x8.from(x8.concat(J)))),X.on("error",Y),X.write(Z),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Z={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Z,...$}}return Z}async rotateLog(){if(CZ())return;let Z=await A9(this.currentLogFile).catch(()=>null);if(!Z)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Z.size>=$.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await Y$(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,A)=>{let W=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),U=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Y}.${U}`;if(await A9(Y).catch(()=>null))try{if(await o0(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await X$(H)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await B7(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await A9(Y).catch(()=>null))await o0(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await Y$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await X$(W9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=n0(Z),X=iJ($),J=r0();await rJ(Y,J,X)}async handleFingersCrossedBuffer(Z,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Z)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);await this.writeToFile(X),console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Z,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Z){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Z)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Z){return{debug:0,info:1,success:2,warning:3,error:4}[Z]}shouldLog(Z){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Z]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Z)=>{if(Z instanceof Promise)return Z.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),F7(this.currentLogFile))try{let Z=l0(this.currentLogFile,"r+");i0(Z),L7(Z)}catch(Z){console.error(`Error flushing file: ${Z}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Z of this.pendingOperations)if(typeof Z.cancel==="function")Z.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Z){console.error("Error waiting for pending operations:",Z)}if(!CZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await Y$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await X$(W9(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch(Z){console.error("Error cleaning up temporary files:",Z)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Z){if(!Z)return"";return`${this.tagFormat.prefix}${Z}${this.tagFormat.suffix}`}formatFileTimestamp(Z){return`[${Z.toISOString()}]`}formatConsoleTimestamp(Z){return this.fancy?EZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}formatConsoleMessage(Z){let{timestamp:$,icon:Y="",tag:X="",message:J,level:G,showTimestamp:U=!0}=Z,H=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(U)O.push($);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)O.push(X.replace(/[[\]]/g,""));return O.push(J),O.join(" ")}let z=fZ.stdout.columns||120,A="";if(G==="warning"||G==="error")A=`${Y} ${J}`;else if(G==="info"||G==="success")A=`${Y} ${X} ${J}`;else A=`${Y} ${X} ${EZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,R=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(R)}${$}`}formatMessage(Z,$){if($.length===1&&Array.isArray($[0]))return Z.replace(/\{(\d+)\}/g,(G,U)=>{let H=Number.parseInt(U,10);return H<$[0].length?String($[0][H]):G});let Y=/%([sdijfo%])/g,X=0,J=Z.replace(Y,(G,U)=>{if(U==="%")return"%";if(X>=$.length)return G;let H=$[X++];switch(U){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 G}});if(X<$.length)J+=` ${$.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}async log(Z,$,...Y){let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),U,H;if($ instanceof Error)U=$.message,H=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!CZ()){let A=mY[Z],W=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"",Q;switch(Z){case"debug":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:EZ.gray(U),level:Z}),console.error(Q);break;case"info":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:U,level:Z}),console.error(Q);break;case"success":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:EZ.green(U),level:Z}),console.error(Q);break;case"warning":Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:U,level:Z}),console.warn(Q);break;case"error":if(Q=this.formatConsoleMessage({timestamp:J,icon:A,tag:W,message:U,level:Z}),console.error(Q),H){let R=H.split(`
3
+ `);for(let O of R)if(O.trim()&&!O.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:EZ.gray(` ${O}`),level:Z,showTimestamp:!1}))}break}}else if(!CZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}if(!this.shouldLog(Z))return;let z=`${G} ${this.environment}.${Z.toUpperCase()}: ${U}
4
+ `;if(H)z+=`${H}
5
+ `;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(Z){let $=performance.now();if(this.fancy&&!CZ()){let Y=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:EZ.blue("\u25D0"),tag:Y,message:`${EZ.cyan(Z)}...`}))}return async(Y)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-$),G=`${Z} completed in ${J}ms`,U=new Date,H=this.formatConsoleTimestamp(U),A=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${G}`;if(Y)A+=` ${JSON.stringify(Y)}`;if(A+=`
6
+ `,A=A.replace(this.ANSI_PATTERN,""),this.fancy&&!CZ()){let W=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:EZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!CZ())console.error(A.trim());await this.writeToFile(A)}}async debug(Z,...$){await this.log("debug",Z,...$)}async info(Z,...$){await this.log("info",Z,...$)}async success(Z,...$){await this.log("success",Z,...$)}async warn(Z,...$){await this.log("warning",Z,...$)}async error(Z,...$){await this.log("error",Z,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Z=this.config.rotation,{encrypt:$}=Z;return!!$}async only(Z){if(!this.enabled)return;return await Z()}isEnabled(){return this.enabled}setEnabled(Z){this.enabled=Z}extend(Z){let $=`${this.name}:${Z}`,Y=new C$($,{...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(Y),Y}createReadStream(){if(CZ())throw Error("createReadStream is not supported in browser environments");if(!F7(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return n0(this.currentLogFile,{encoding:"utf8"})}async decrypt(Z){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let X=x8.isBuffer(Z)?Z:x8.from(Z,"base64"),J=X.slice(0,16),G=X.slice(-16),U=X.slice(16,-16),H=nJ("aes-256-gcm",Y,J);return H.setAuthTag(G),x8.concat([H.update(U),H.final()]).toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return CZ()}isServerMode(){return!CZ()}setTestEncryptionKey(Z,$){this.currentKeyId=Z,this.keys.set(Z,$)}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(Z){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($);if(this.fancy&&!CZ()){let G=Z.split(`
7
+ `),U=Math.max(...G.map((W)=>W.length))+2,H=`\u250C${"\u2500".repeat(U)}\u2510`,z=`\u2514${"\u2500".repeat(U)}\u2518`,A=G.map((W)=>{let Q=" ".repeat(U-W.length-2);return`\u2502 ${W}${Q} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.cyan(H)})),A.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:EZ.cyan(z),showTimestamp:!1}))}else if(!CZ())console.error(`${X} ${this.environment}.INFO: [BOX] ${Z}`);let J=`${X} ${this.environment}.INFO: [BOX] ${Z}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}async prompt(Z){if(CZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${EZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();fZ.stdin.removeListener("data",Y);try{if(typeof fZ.stdin.setRawMode==="function")fZ.stdin.setRawMode(!1)}catch{}fZ.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof fZ.stdin.setRawMode==="function")fZ.stdin.setRawMode(!0)}catch{}fZ.stdin.resume(),fZ.stdin.once("data",Y)})}setFancy(Z){this.fancy=Z}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Z,...$){if(!this.enabled)return;let Y=Z;if($&&$.length>0){let U=/%([sdijfo%])/g,H=0;if(Y=Z.replace(U,(z,A)=>{if(A==="%")return"%";if(H>=$.length)return z;let W=$[H++];switch(A){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return z}}),H<$.length)Y+=` ${$.slice(H).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}if(this.fancy&&!CZ()){let U=this.options.showTags!==!1&&this.name?EZ.gray(this.formatTag(this.name)):"",H=EZ.blue("\u25D0");console.error(`${H} ${U} ${EZ.cyan(Y)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(G)}progress(Z,$=""){if(!this.enabled||!this.fancy||CZ()||Z<=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 Y=20;return this.activeProgressBar={total:Z,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||CZ())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Z,U)),H!==void 0)this.activeProgressBar.message=H;let z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,z)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||CZ())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,H="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||CZ())return;fZ.stdout.write(`${"\r".padEnd(fZ.stdout.columns||80)}\r`),this.log(H,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Z,$=!1){if(!this.enabled||!this.fancy||CZ()||!fZ.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Z.current/Z.total*100))),X=Math.round(Z.barLength*Y/100),J=Z.barLength-X,G=EZ.green("\u2501".repeat(X)),U=EZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=$||Y===100?EZ.green("\u2713"):EZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${EZ.gray(this.formatTag(this.name))}`:"",R=`\r${W}${Q} ${H} ${z}${A}`,O=fZ.stdout.columns||80,N=" ".repeat(Math.max(0,O-R.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${R}${N}`,fZ.stdout.write(Z.lastRenderedLine),$)fZ.stdout.write(`
10
+ `)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||CZ()||!fZ.stdout.isTTY){this.activeProgressBar=null;return}if(Z.current<Z.total)Z.current=Z.total;if($)Z.message=$;this.renderProgressBar(Z,!0),this.activeProgressBar=null}async clear(Z={}){if(CZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await Y$(this.config.logDirectory),Y=[];for(let X of $){if(!(Z.name?new RegExp(Z.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=W9(this.config.logDirectory,X);if(Z.before)try{if((await A9(G)).mtime>=Z.before)continue}catch(U){console.error(`Failed to get stats for file ${G}:`,U);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await X$(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function K$(Z,$){if(Array.isArray($)&&Array.isArray(Z)&&$.length===2&&Z.length===2&&LZ($[0])&&"id"in $[0]&&$[0].id===3&&LZ($[1])&&"id"in $[1]&&$[1].id===4)return $;if(LZ($)&&LZ(Z)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return Z;if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray($)&&Array.isArray(Z)){if(LZ(Z)&&"arr"in Z&&Array.isArray(Z.arr)&&LZ($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Z.length>0&&LZ($[0])&&LZ(Z[0])){let X=[...$];for(let J of Z)if(LZ(J)&&"name"in J){if(!X.find((U)=>LZ(U)&&("name"in U)&&U.name===J.name))X.push(J)}else if(LZ(J)&&"path"in J){if(!X.find((U)=>LZ(U)&&("path"in U)&&U.path===J.path))X.push(J)}else if(!X.some((G)=>S$(G,J)))X.push(J);return X}if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}if(!LZ($)||!LZ(Z))return $;let Y={...Z};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let J=$[X];if(J===null||J===void 0)continue;else if(LZ(J)&&LZ(Y[X]))Y[X]=K$(Y[X],J);else if(Array.isArray(J)&&Array.isArray(Y[X]))if(J.length>0&&Y[X].length>0&&LZ(J[0])&&LZ(Y[X][0])){let G=[...J];for(let U of Y[X])if(LZ(U)&&"name"in U){if(!G.find((z)=>LZ(z)&&("name"in z)&&z.name===U.name))G.push(U)}else if(LZ(U)&&"path"in U){if(!G.find((z)=>LZ(z)&&("path"in z)&&z.path===U.path))G.push(U)}else if(!G.some((H)=>S$(H,U)))G.push(U);Y[X]=G}else if(J.every((G)=>typeof G==="string")&&Y[X].every((G)=>typeof G==="string")){let G=[...J];for(let U of Y[X])if(!G.includes(U))G.push(U);Y[X]=G}else Y[X]=J;else Y[X]=J}return Y}function o7(Z,$,Y="replace"){if($===null||$===void 0)return Z;if(Array.isArray($))return Y==="replace"?$:K$(Z,$);if(Array.isArray(Z))return Y==="replace"?$:K$(Z,$);if(!LZ($)||!LZ(Z))return $;let X={...Z};for(let J of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,J))continue;let G=$[J],U=X[J];if(G===null||G===void 0)continue;if(Array.isArray(G)||Array.isArray(U))if(Y==="replace")X[J]=G;else X[J]=K$(U,G);else if(LZ(G)&&LZ(U))X[J]=o7(U,G,Y);else X[J]=G}return X}function S$(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!S$(Z[Y],$[Y]))return!1;return!0}if(LZ(Z)&&LZ($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!S$(Z[J],$[J]))return!1}return!0}return!1}function LZ(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}async function Q$(Z,$,Y="replace"){if(!PY(Z))return null;try{let X=await import(Z),J=X.default||X;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return o7($,J,Y)}catch{return null}}catch{return null}}function vG(Z,$,Y=!1){if(!Z)return $;let X=Z.toUpperCase().replace(/-/g,"_"),J={...$};function G(U,H=[]){let z={...U};for(let[A,W]of Object.entries(U)){let Q=[...H,A],R=(_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${X}_${Q.map(R).join("_")}`,N=`${X}_${Q.map((_)=>_.toUpperCase()).join("_")}`;if(Y)pZ.info(`Checking environment variable ${O} for config ${Z}.${Q.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))z[A]=G(W,Q);else{let _=x9.env[O]||x9.env[N];if(_!==void 0){if(Y)pZ.info(`Using environment variable ${_?O:N} for config ${Z}.${Q.join(".")}`);if(typeof W==="number")z[A]=Number(_);else if(typeof W==="boolean")z[A]=_.toLowerCase()==="true";else if(Array.isArray(W))try{let F=JSON.parse(_);if(Array.isArray(F))z[A]=F;else z[A]=_.split(",").map((L)=>L.trim())}catch{z[A]=_.split(",").map((F)=>F.trim())}else z[A]=_}}}return z}return G(J)}async function yG({name:Z="",alias:$,cwd:Y,configDir:X,defaultConfig:J,verbose:G=!1,checkEnv:U=!0,arrayStrategy:H="replace"}){let z=U&&typeof J==="object"&&J!==null&&!Array.isArray(J)?vG(Z,J,G):J,A=Y||x9.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(G)pZ.info(`Loading configuration for "${Z}"${$?` (alias: "${$}")`:""} from ${A}`);let Q=[Z,`.${Z}`].filter(Boolean),R=[`${Z}.config`,`.${Z}.config`].filter(Boolean),O=$?[$,`.${$}`]:[],N=$?[`${$}.config`,`.${$}.config`]:[],_=Array.from(new Set([A,uZ(A,"config"),uZ(A,".config"),X?uZ(A,X):void 0].filter(Boolean)));for(let F of _){if(G)pZ.info(`Searching for configuration in: ${F}`);let K=[uZ(A,"config"),uZ(A,".config")].concat(X?[uZ(A,X)]:[]).includes(F)?[...Q,...R,...O,...N]:[...R,...Q,...N,...O];for(let I of K)for(let B of W){let v=uZ(F,`${I}${B}`),P=await Q$(v,z,H);if(P!==null){if(G)pZ.success(`Configuration loaded from: ${v}`);return P}}}if(Z){let F=uZ(V7(),".config",Z),L=["config",`${Z}.config`];if($)L.push(`${$}.config`);if(G)pZ.info(`Checking user config directory: ${F}`);for(let K of L)for(let I of W){let B=uZ(F,`${K}${I}`),v=await Q$(B,z,H);if(v!==null){if(G)pZ.success(`Configuration loaded from user config directory: ${B}`);return v}}}if(Z){let F=uZ(V7(),".config"),L=[`.${Z}.config`];if($)L.push(`.${$}.config`);if(G)pZ.info(`Checking user config directory for dotfile configs: ${F}`);for(let K of L)for(let I of W){let B=uZ(F,`${K}${I}`),v=await Q$(B,z,H);if(v!==null){if(G)pZ.success(`Configuration loaded from user config directory dotfile: ${B}`);return v}}}if(Z){let F=V7(),L=[`.${Z}.config`,`.${Z}`];if($)L.push(`.${$}.config`),L.push(`.${$}`);if(G)pZ.info(`Checking user home directory for dotfile configs: ${F}`);for(let K of L)for(let I of W){let B=uZ(F,`${K}${I}`),v=await Q$(B,z,H);if(v!==null){if(G)pZ.success(`Configuration loaded from user home directory: ${B}`);return v}}}try{let F=uZ(A,"package.json");if(PY(F)){let L=await import(F),K=L[Z];if(!K&&$){if(K=L[$],K&&G)pZ.success(`Using alias "${$}" configuration from package.json`)}if(K&&typeof K==="object"&&!Array.isArray(K))try{if(G)pZ.success(`Configuration loaded from package.json: ${K===L[Z]?Z:$}`);return o7(z,K,H)}catch(I){if(G)pZ.warn("Failed to merge package.json config:",I)}}}catch(F){if(G)pZ.warn("Failed to load package.json:",F)}if(G)pZ.info(`No configuration found for "${Z}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function hG(Z,$={}){let Y=D$.cwd();while(Y.includes("storage"))Y=c0(Y,"..");let X=c0(Y,Z||"");if($?.relative)return dJ(D$.cwd(),X);return X}async function bG(){try{let Z=await yG({name:"clarity",alias:"logging",defaultConfig:B$,cwd:D$.cwd()});return{...B$,...Z||{}}}catch{return B$}}function kZ(){if(D8.env.NODE_ENV==="test"||D8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fG(){if(D8.env.NODE_ENV==="test"||D8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D8<"u"){let Z=D8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(D8.versions&&(D8.versions.node||D8.versions.bun))}return!1}class xY{async format(Z){let $=await fG(),Y=await this.getMetadata($);return JSON.stringify({timestamp:Z.timestamp.toISOString(),level:Z.level,name:Z.name,message:Z.message,metadata:Y})}async getMetadata(Z){if(Z){let{hostname:$}=await import("os");return{pid:V9.pid,hostname:$(),environment:V9.env.NODE_ENV||"development",platform:V9.platform,version:V9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:V9.env.NODE_ENV||V9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class N${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(Z,$={}){this.name=Z,this.config={...b7},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new xY,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??QZ.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},X=$.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Z){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[Z]>=$[Y]}initializeFingersCrossedConfig(Z){if(!Z.fingersCrossedEnabled&&Z.fingersCrossed)return{...R$,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...R$};return{...R$,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:b7.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(Z).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!kZ()&&this.config.writeToFile===!0}async writeToFile(Z){let Y=(async()=>{let J,G=0,U=3,H=1000;while(G<U)try{try{try{await $G(this.config.logDirectory,ZY.F_OK|ZY.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await YG(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let z=this.validateEncryptionConfig()?(await this.encrypt(Z)).encrypted:B8.from(Z);try{if(!J$(this.currentLogFile))await D7(this.currentLogFile,"",{mode:420});if(J=e0(this.currentLogFile,"a",420),ZG(J,z,{flag:"a"}),t0(J),J!==void 0)O7(J),J=void 0;if((await Q9(this.currentLogFile)).size===0){if(await D7(this.currentLogFile,z,{flag:"w",mode:420}),(await Q9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let W=A;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(G<U-1){let Q=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${U}:`,Q);let R=H*2**G;await new Promise((O)=>setTimeout(O,R)),G++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{O7(J)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(z){if(G===U-1){let W=z,Q=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Q),z}G++;let A=H*2**(G-1);await new Promise((W)=>setTimeout(W,A))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,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 _9(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 _9(this.config.logDirectory,`${this.name}.log`);let Z=new Date().toISOString().split("T")[0];return _9(this.config.logDirectory,`${this.name}-${Z}.log`)}setupRotation(){if(kZ())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Z=this.config.rotation,$;switch(Z.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,z])=>z.createdAt.getTime()-H.createdAt.getTime()),G=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,G);if(J.length>U)for(let[H]of J.slice(U))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return R7(16).toString("hex")}generateKey(){return R7(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Z=this.keys.get(this.currentKeyId);if(!Z)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Z,id:this.currentKeyId}}encrypt(Z){let{key:$}=this.getCurrentKey(),Y=R7(16),X=aJ("aes-256-gcm",$,Y),J=B8.isBuffer(Z)?Z:B8.from(Z,"utf8"),G=X.update(J),U=X.final(),H=G.length+U.length,z=X.getAuthTag(),A=B8.allocUnsafe(16+H+16);return Y.copy(A,0),G.copy(A,16),U.copy(A,16+G.length),z.copy(A,16+H),{encrypted:A,iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=YY(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(B8.from(B8.concat(J)))),X.on("error",Y),X.write(Z),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Z={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Z,...$}}return Z}async rotateLog(){if(kZ())return;if(!this.shouldWriteToFile())return;let Z=await Q9(this.currentLogFile).catch(()=>null);if(!Z)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Z.size>=$.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await G$(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,A)=>{let W=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),U=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Y}.${U}`;if(await Q9(Y).catch(()=>null))try{if(await $Y(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await U$(H)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await D7(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await Q9(Y).catch(()=>null))await $Y(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await G$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await U$(_9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=a0(Z),X=eJ($),J=YY();await GG(Y,J,X)}async handleFingersCrossedBuffer(Z,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Z)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(Z){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Z]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Z)=>{if(Z instanceof Promise)return Z.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),J$(this.currentLogFile))try{let Z=e0(this.currentLogFile,"r+");t0(Z),O7(Z)}catch(Z){console.error(`Error flushing file: ${Z}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Z of this.pendingOperations)if(typeof Z.cancel==="function")Z.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Z){console.error("Error waiting for pending operations:",Z)}if(!kZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await G$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await U$(_9(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch(Z){console.error("Error cleaning up temporary files:",Z)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Z){if(!Z)return"";return`${this.tagFormat.prefix}${Z}${this.tagFormat.suffix}`}formatFileTimestamp(Z){return`[${Z.toISOString()}]`}formatConsoleTimestamp(Z){return this.shouldStyleConsole()?VZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||kZ())return!1;let Z=typeof QZ.env.NO_COLOR<"u",$=QZ.env.FORCE_COLOR==="0";if(Z||$)return!1;return!!(typeof QZ.stderr<"u"&&QZ.stderr.isTTY||typeof QZ.stdout<"u"&&QZ.stdout.isTTY)}formatConsoleMessage(Z){let{timestamp:$,icon:Y="",tag:X="",message:J,level:G,showTimestamp:U=!0}=Z,H=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(U)O.push($);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)O.push(X.replace(/[[\]]/g,""));return O.push(J),O.join(" ")}let z=QZ.stdout.columns||120,A="";if(G==="warning"||G==="error")A=`${Y} ${J}`;else if(G==="info"||G==="success")A=`${Y} ${X} ${J}`;else A=`${Y} ${X} ${VZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,R=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(R)}${$}`}formatMessage(Z,$){if($.length===1&&Array.isArray($[0]))return Z.replace(/\{(\d+)\}/g,(G,U)=>{let H=Number.parseInt(U,10);return H<$[0].length?String($[0][H]):G});let Y=/%([sdijfo%])/g,X=0,J=Z.replace(Y,(G,U)=>{if(U==="%")return"%";if(X>=$.length)return G;let H=$[X++];switch(U){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 G}});if(X<$.length)J+=` ${$.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}formatMarkdown(Z){if(!Z)return Z;let $=Z;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,X,J)=>{let G=VZ.underline(VZ.blue(X)),U=this.toAbsoluteFilePath(J);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(U)}`,z="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${H}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),$=$.replace(/`([^`]+)`/g,(Y,X)=>VZ.bgGray(X)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,X)=>VZ.bold(X)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,X)=>VZ.italic(X)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,X)=>VZ.italic(X)),$=$.replace(/~([^~]+)~/g,(Y,X)=>VZ.strikethrough(X)),$}supportsHyperlinks(){if(kZ())return!1;let Z=QZ.env;if(!Z)return!1;if(Z.TERM_PROGRAM==="iTerm.app"||Z.TERM_PROGRAM==="vscode"||Z.TERM_PROGRAM==="WezTerm")return!0;if(Z.WT_SESSION)return!0;if(Z.TERM==="xterm-kitty")return!0;let $=Z.VTE_VERSION?Number.parseInt(Z.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(Z){try{let $=Z;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=QZ.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(XG($)||$.startsWith("./")||$.startsWith("../"))$=JG($);else return null;return J$($)?$:null}catch{return null}}buildOutputTexts(Z){let $=this.shouldStyleConsole()?this.formatMarkdown(Z):Z,Y=Z.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(Z,$,...Y){let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),U,H;if($ instanceof Error)U=$.message,H=$.stack;else U=this.formatMessage($,Y);let{consoleText:z,fileText:A}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let Q=this.options.showIcons===!1?"":cY[Z],R=this.options.showTags!==!1&&this.name?VZ.gray(this.formatTag(this.name)):"",O;switch(Z){case"debug":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:VZ.gray(z),level:Z}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:VZ.green(z),level:Z}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.error(O),H){let N=H.split(`
11
+ `);for(let _ of N)if(_.trim()&&!_.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:VZ.gray(` ${_}`),level:Z,showTimestamp:!1}))}break}}else if(!kZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}if(!this.shouldLog(Z))return;let W=`${G} ${this.environment}.${Z.toUpperCase()}: ${A}
12
+ `;if(H)W+=`${H}
13
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress(Z,$=""){let Y={update:(H,z)=>{},finish:(H)=>{},interrupt:(H,z)=>{}};if(!this.enabled)return Y;let X=30;if(this.activeProgressBar={total:Math.max(1,Z||1),current:0,message:$||"",barLength:X,lastRenderedLine:""},this.shouldStyleConsole()&&!kZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(H,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,H),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!kZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,z="info")=>{if(!kZ()&&QZ.stdout.isTTY)QZ.stdout.write(`
14
+ `);if(this[z==="warning"?"warn":z](H),this.activeProgressBar&&this.shouldStyleConsole()&&!kZ()&&QZ.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Z){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?VZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":VZ.blue("\u25D0"),tag:Y,message:`${VZ.cyan(Z)}...`}))}return async(Y)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-$),G=`${Z} completed in ${J}ms`,U=new Date,H=this.formatConsoleTimestamp(U),A=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${G}`;if(Y)A+=` ${JSON.stringify(Y)}`;if(A+=`
15
+ `,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?VZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":VZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!kZ())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(Z,...$){await this.log("debug",Z,...$)}async info(Z,...$){await this.log("info",Z,...$)}async success(Z,...$){await this.log("success",Z,...$)}async warn(Z,...$){await this.log("warning",Z,...$)}async error(Z,...$){await this.log("error",Z,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Z=this.config.rotation,{encrypt:$}=Z;return!!$}async only(Z){if(!this.enabled)return;return await Z()}isEnabled(){return this.enabled}setEnabled(Z){this.enabled=Z}extend(Z){let $=`${this.name}:${Z}`,Y=new N$($,{...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(Y),Y}createReadStream(){if(kZ())throw Error("createReadStream is not supported in browser environments");if(!J$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return a0(this.currentLogFile,{encoding:"utf8"})}async decrypt(Z){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let X=B8.isBuffer(Z)?Z:B8.from(Z,"base64"),J=X.subarray(0,16),G=X.subarray(X.length-16),U=X.subarray(16,X.length-16),H=tJ("aes-256-gcm",Y,J);H.setAuthTag(G);let z=H.update(U),A=H.final(),W=z.length+A.length,Q=B8.allocUnsafe(W);return z.copy(Q,0),A.copy(Q,z.length),Q.toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return kZ()}isServerMode(){return!kZ()}setTestEncryptionKey(Z,$){this.currentKeyId=Z,this.keys.set(Z,$)}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(Z){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($),{consoleText:J,fileText:G}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let H=J.split(`
16
+ `),z=Math.max(...H.map((R)=>R.length))+2,A=`\u250C${"\u2500".repeat(z)}\u2510`,W=`\u2514${"\u2500".repeat(z)}\u2518`,Q=H.map((R)=>{return this.formatConsoleMessage({timestamp:Y,message:VZ.cyan(R),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:VZ.cyan(A),showTimestamp:!1})),Q.forEach((R)=>console.error(R)),console.error(this.formatConsoleMessage({timestamp:Y,message:VZ.cyan(W),showTimestamp:!1}))}else if(!kZ())console.error(`${X} ${this.environment}.INFO: [BOX] ${G}`);let U=`${X} ${this.environment}.INFO: [BOX] ${G}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Z){if(kZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${VZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();QZ.stdin.removeListener("data",Y);try{if(typeof QZ.stdin.setRawMode==="function")QZ.stdin.setRawMode(!1)}catch{}QZ.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof QZ.stdin.setRawMode==="function")QZ.stdin.setRawMode(!0)}catch{}QZ.stdin.resume(),QZ.stdin.once("data",Y)})}setFancy(Z){this.fancy=Z}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Z,...$){if(!this.enabled)return;let Y=Z;if($&&$.length>0){let z=/%([sdijfo%])/g,A=0;if(Y=Z.replace(z,(W,Q)=>{if(Q==="%")return"%";if(A>=$.length)return W;let R=$[A++];switch(Q){case"s":return String(R);case"d":case"i":return Number(R).toString();case"j":case"o":return JSON.stringify(R,null,2);default:return W}}),A<$.length)Y+=` ${$.slice(A).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:X,fileText:J}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?VZ.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${VZ.blue("\u25D0")} `;console.error(`${A}${z} ${VZ.cyan(X)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar(Z,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!QZ.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Z.current/Z.total*100))),X=Math.round(Z.barLength*Y/100),J=Z.barLength-X,G=VZ.green("\u2501".repeat(X)),U=VZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=this.options.showIcons===!1?"":$||Y===100?VZ.green("\u2713"):VZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${VZ.gray(this.formatTag(this.name))}`:"",R=`\r${W}${Q} ${H} ${z}${A}`,O=QZ.stdout.columns||80,N=" ".repeat(Math.max(0,O-R.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${R}${N}`,QZ.stdout.write(Z.lastRenderedLine),$)QZ.stdout.write(`
19
+ `)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||kZ()||!QZ.stdout.isTTY){this.activeProgressBar=null;return}if(Z.current<Z.total)Z.current=Z.total;if($)Z.message=$;this.renderProgressBar(Z,!0),this.activeProgressBar=null}async clear(Z={}){if(kZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await G$(this.config.logDirectory),Y=[];for(let X of $){if(!(Z.name?new RegExp(Z.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=_9(this.config.logDirectory,X);if(Z.before)try{if((await Q9(G)).mtime>=Z.before)continue}catch(U){console.error(`Failed to get stats for file ${G}:`,U);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await U$(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function vY(Z,$={}){let{maxRetries:Y=3,retryDelay:X=1000,isRetryable:J=()=>!0,fallback:G}=$,U=Error("Unknown error occurred");for(let H=0;H<=Y;H++)try{return await Z()}catch(z){if(U=z instanceof Error?z:Error(String(z)),H===Y||!J(U))break;if(X>0)await new Promise((A)=>setTimeout(A,X))}if(G!==void 0)return G;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function yY(Z){return Z instanceof aZ}function gG(Z){return Z instanceof P$}function pG(Z){if(yY(Z))return Z.code==="FILE_SYSTEM_ERROR"||Z.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Z.message.toLowerCase().includes(Y.toLowerCase()))}class y${defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Z,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(Z.toLowerCase()),parse:(Z)=>{let $=Z.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(Z,$)=>$==="number"||!Number.isNaN(Number(Z))&&!Number.isNaN(Number.parseFloat(Z)),parse:(Z)=>{let $=Number(Z);if(Number.isNaN($))throw TypeError(`Cannot parse "${Z}" as number`);return $}},{name:"array",canParse:(Z,$)=>$==="array"||Z.startsWith("[")||Z.includes(","),parse:(Z)=>{try{let $=JSON.parse(Z);if(Array.isArray($))return $}catch{}return Z.split(",").map(($)=>$.trim())}},{name:"json",canParse:(Z,$)=>$==="object"||(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")),parse:(Z)=>{try{return JSON.parse(Z)}catch($){throw Error(`Cannot parse "${Z}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(Z,$,Y={}){let{prefix:X,useCamelCase:J=!0,useBackwardCompatibility:G=!0,customParsers:U={},verbose:H=!1,trackPerformance:z=!0}=Y,A=async()=>{if(!Z)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let W=X||this.generateEnvPrefix(Z),Q={...$};return this.processObject(Q,[],W,{useCamelCase:J,useBackwardCompatibility:G,customParsers:U,verbose:H,configName:Z}),{config:Q,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return h9.track("applyEnvironmentVariables",A,{configName:Z});return A()}generateEnvPrefix(Z){return Z.toUpperCase().replace(/-/g,"_")}formatEnvKey(Z,$){if(!$)return Z.toUpperCase();return Z.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=U.map((W)=>this.formatEnvKey(W,X.useCamelCase)),z=`${Y}_${H.join("_")}`,A=X.useBackwardCompatibility?`${Y}_${U.map((W)=>W.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,U,Y,X);else{let W=z$.env[z]||(A?z$.env[A]:void 0);if(W!==void 0){if(X.verbose){let Q=z$.env[z]?z:A}try{Z[J]=this.parseEnvironmentValue(W,typeof G,z,X.customParsers,X.configName)}catch(Q){if(Q instanceof q$)throw Q;throw v8.envVar(z,W,typeof G,X.configName)}}}}}parseEnvironmentValue(Z,$,Y,X,J){for(let[G,U]of Object.entries(X))try{return U(Z)}catch{continue}for(let G of this.defaultParsers)if(G.canParse(Z,$))try{return G.parse(Z)}catch{throw v8.envVar(Y,Z,`${$} (via ${G.name} parser)`,J)}return Z}getEnvironmentVariables(Z){let $={},Y=Z.toUpperCase();for(let[X,J]of Object.entries(z$.env))if(X.startsWith(Y)&&J!==void 0)$[X]=J;return $}validateEnvironmentVariable(Z,$,Y){let X=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Z))X.push(`Environment variable key "${Z}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Z,$,Y,{})}catch(J){X.push(`Cannot parse value "${$}" as ${Y}: ${J}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs(Z,$,Y={}){let{prefix:X,format:J="text"}=Y,G=X||this.generateEnvPrefix(Z),U=[];switch(this.extractEnvVarInfo($,[],G,U),J){case"markdown":return this.formatAsMarkdown(U,Z);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Z)}}extractEnvVarInfo(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=`${Y}_${U.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,U,Y,X);else X.push({key:H,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${U.join(".")}`,example:this.generateExample(G)})}}generateExample(Z){if(Array.isArray(Z))return JSON.stringify(Z);if(typeof Z==="object"&&Z!==null)return JSON.stringify(Z);return String(Z)}formatAsText(Z,$){let Y=`Environment Variables for ${$}:
20
+
21
+ `;for(let X of Z)Y+=`${X.key}
22
+ `,Y+=` Type: ${X.type}
23
+ `,Y+=` Description: ${X.description}
24
+ `,Y+=` Example: ${X.example}
25
+
26
+ `;return Y}formatAsMarkdown(Z,$){let Y=`# Environment Variables for ${$}
27
+
28
+ `;Y+=`| Variable | Type | Description | Example |
29
+ `,Y+=`|----------|------|-------------|----------|
30
+ `;for(let X of Z)Y+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
31
+ `;return Y}}function dG(Z,$){let Y=pY("process");if(typeof Y>"u"||!Y.env)return $;let X=Y.env[Z];return X!==void 0?X:$}function hY(Z,$,Y={}){return bY(Z,$,Y,new WeakMap)}function bY(Z,$,Y,X){let{arrayMergeMode:J="replace",skipNullish:G=!1,customMerger:U}=Y;if($===null||$===void 0)return G?Z:$;if(U){let H=U(Z,$);if(H!==void 0)return H}if(Array.isArray($)||Array.isArray(Z))return fY(Z,$,J,X);if(!Y8($)||!Y8(Z))return $;return nG(Z,$,Y,X)}function fY(Z,$,Y,X){if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray(Z)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(Z))switch(Y){case"replace":return $;case"concat":return mG(Z,$);case"smart":return cG(Z,$,X);default:return $}return $}function mG(Z,$){let Y=[...$];for(let X of Z)if(!Y.some((J)=>y7(J,X)))Y.push(X);return Y}function cG(Z,$,Y){if($.length===0)return Z;if(Z.length===0)return $;if(Y8($[0])&&Y8(Z[0]))return uG(Z,$,Y);if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}function uG(Z,$,Y){let X=[...$];for(let J of Z){if(!Y8(J)){X.push(J);continue}let G=["id","name","key","path","type"],U=!1;for(let H of G)if(H in J){if(X.find((A)=>Y8(A)&&(H in A)&&A[H]===J[H])){U=!0;break}}if(!U)X.push(J)}return X}function nG(Z,$,Y,X){let J=$;if(Y8(J)&&X.has(J))return X.get(J);let G={...Z};if(Y8(J))X.set(J,G);for(let U in J){if(!Object.prototype.hasOwnProperty.call(J,U))continue;let H=J[U],z=G[U];if(Y.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){G[U]=H;continue}if(Y8(H)&&Y8(z))G[U]=bY(z,H,Y,X);else if(Array.isArray(H)||Array.isArray(z))G[U]=fY(z,H,Y.arrayMergeMode||"smart",X);else G[U]=H}return G}function r7(Z,$,Y="replace"){return hY(Z,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function y7(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!y7(Z[Y],$[Y]))return!1;return!0}if(Y8(Z)&&Y8($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!y7(Z[J],$[J]))return!1}return!0}return!1}function Y8(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}class h${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Z,$,Y={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:G,trackPerformance:U=!0,verbose:H=!1}=Y;if(J){let A=B9.getWithFileCheck("file",Z);if(A){if(H)console.log(`Configuration loaded from cache: ${Z}`);return A}}let z=async()=>{if(!H$(Z))return null;try{let A=`?t=${Date.now()}`,W=await import(Z+A),Q=W.default||W,R="default"in W,O=Object.keys(W).length>0;if(!R&&!O)throw new v9(Z,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new v9(Z,Error("Configuration must export a valid object"),"unknown");let F={config:r7($,Q,X),source:{type:"file",path:Z,priority:100,timestamp:new Date}};if(J)B9.setWithFileCheck("file",F,Z,G);return F}catch(A){throw A instanceof Error?v8.configLoad(Z,A):v8.configLoad(Z,Error(String(A)))}};if(U)return h9.track("loadFromPath",z,{path:Z});return z()}async tryLoadFromPaths(Z,$,Y={}){for(let X of Z)try{let J=await this.loadFromPath(X,$,Y);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Y.verbose)console.warn(`Failed to load config from ${X}:`,J)}return null}generateConfigPaths(Z,$,Y){let X=this.generateNamePatterns(Z,Y),J=[];for(let G of X)for(let U of this.extensions)J.push(E7($,`${G}${U}`));return J}generateNamePatterns(Z,$){let Y=[];if(Y.push("config",".config"),Z)Y.push(Z,`.${Z}.config`,`${Z}.config`,`.${Z}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),Z)Y.push(`${Z}.${$}.config`,`.${Z}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(Z){return vY(async()=>{return H$(Z)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Z,$,Y){let X=[];if(!H$(Z))return X;if($||Y){let J=this.generateNamePatterns($||"",Y);for(let G of J)for(let U of this.extensions){let H=E7(Z,`${G}${U}`);if(await this.checkFileAccess(H))X.push(H)}}else try{let{readdirSync:J}=await import("fs"),G=J(Z);for(let U of G)if(this.looksLikeConfigFile(U)){let H=E7(Z,U);if(await this.checkFileAccess(H))X.push(H)}}catch{return[]}return X}looksLikeConfigFile(Z){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((Y)=>Y.test(Z))}async validateConfigFile(Z){let $=[];try{if(!H$(Z))return $.push("Configuration file does not exist"),$;let Y=await import(Z),X=Y.default||Y;if(X===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof X!=="object"||X===null)$.push("Configuration must be an object");else if(Array.isArray(X))$.push("Configuration cannot be an array at the root level");if(Z.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),G=J(Z,"utf8");JSON.parse(G)}catch(J){$.push(`Invalid JSON syntax: ${J}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(Z){try{let{statSync:$}=await import("fs");return $(Z).mtime}catch{return null}}async preloadConfigurations(Z,$={}){let Y=new Map;return await Promise.allSettled(Z.map(async(X)=>{try{let J=await this.loadFromPath(X,{},$);if(J)Y.set(X,J.config)}catch(J){if($.verbose)console.warn(`Failed to preload ${X}:`,J)}})),Y}}class a7{async validateConfiguration(Z,$,Y={}){let{stopOnFirstError:X=!1,validateRequired:J=!0,validateTypes:G=!0,customRules:U=[],trackPerformance:H=!0,verbose:z=!1}=Y,A=async()=>{let W=[],Q=[],R={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:U,trackPerformance:H,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(Z,$,R);else if(Array.isArray($))return this.validateWithRules(Z,[...$,...U],R);else return this.validateWithJSONSchema(Z,$,R)}catch(O){return W.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:W,warnings:Q}}};if(H)return await h9.track("validateConfiguration",A);return A()}async validateWithSchemaFile(Z,$,Y){try{if(!UG($))throw new y9($,[{path:"",message:"Schema file does not exist"}]);let X=await import($),J=X.default||X;if(Array.isArray(J))return this.validateWithRules(Z,J,Y);else return this.validateWithJSONSchema(Z,J,Y)}catch(X){throw new y9($,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema(Z,$,Y){let X=[],J=[];return this.validateObjectAgainstSchema(Z,$,"",X,J,Y),{isValid:X.length===0,errors:X,warnings:J}}validateObjectAgainstSchema(Z,$,Y,X,J,G){if(G.validateTypes&&$.type){let U=Array.isArray(Z)?"array":typeof Z,H=Array.isArray($.type)?$.type:[$.type];if(!H.includes(U)){if(X.push({path:Y,message:`Expected type ${H.join(" or ")}, got ${U}`,expected:H.join(" or "),actual:U,rule:"type"}),G.stopOnFirstError)return}}if($.enum&&!$.enum.includes(Z)){if(X.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"}),G.stopOnFirstError)return}if(typeof Z==="string"){if($.minLength!==void 0&&Z.length<$.minLength)X.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:Z.length,rule:"minLength"});if($.maxLength!==void 0&&Z.length>$.maxLength)X.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:Z.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(Z))X.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:Z,rule:"pattern"})}}if(typeof Z==="number"){if($.minimum!==void 0&&Z<$.minimum)X.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:Z,rule:"minimum"});if($.maximum!==void 0&&Z>$.maximum)X.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:Z,rule:"maximum"})}if(Array.isArray(Z)&&$.items)for(let U=0;U<Z.length;U++){let H=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Z[U],$.items,H,X,J,G),G.stopOnFirstError&&X.length>0)return}if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let U=Z;if(G.validateRequired&&$.required){for(let H of $.required)if(!(H in U)){if(X.push({path:Y?`${Y}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if($.properties){for(let[H,z]of Object.entries($.properties))if(H in U){let A=Y?`${Y}.${H}`:H;if(this.validateObjectAgainstSchema(U[H],z,A,X,J,G),G.stopOnFirstError&&X.length>0)return}}if($.additionalProperties===!1){let H=new Set(Object.keys($.properties||{}));for(let z of Object.keys(U))if(!H.has(z))J.push({path:Y?`${Y}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Z,$,Y){let X=[],J=[];for(let G of $)try{let U=this.getValueByPath(Z,G.path),H=this.validateWithRule(U,G,G.path);if(X.push(...H),Y.stopOnFirstError&&X.length>0)break}catch(U){X.push({path:G.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:J}}validateWithRule(Z,$,Y){let X=[];if($.required&&(Z===void 0||Z===null))return X.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),X;if(Z===void 0||Z===null)return X;if($.type){let J=Array.isArray(Z)?"array":typeof Z;if(J!==$.type)X.push({path:Y,message:$.message||`Expected type ${$.type}, got ${J}`,expected:$.type,actual:J,rule:"type"})}if($.min!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J<$.min)X.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:J,rule:"min"})}if($.max!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J>$.max)X.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:J,rule:"max"})}if($.pattern&&typeof Z==="string"){if(!$.pattern.test(Z))X.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:Z,rule:"pattern"})}if($.enum&&!$.enum.includes(Z))X.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"});if($.validator){let J=$.validator(Z);if(J)X.push({path:Y,message:$.message||J,rule:"custom"})}return X}getValueByPath(Z,$){if(!$)return Z;let Y=$.split("."),X=Z;for(let J of Y)if(X&&typeof X==="object"&&J in X)X=X[J];else return;return X}generateRulesFromInterface(Z){let $=[],Y=Z.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of Y){let[,J,G,U]=X;$.push({path:J,required:!G,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(Z){switch(Z.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:nY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class t7{fileLoader=new h$;envProcessor=new y$;validator=new a7;async loadConfig(Z){let $=Date.now(),{cache:Y,performance:X,schema:J,validate:G,...U}=Z;try{if(Y?.enabled){let z=this.checkCache(U.name||"",U);if(z)return z}let H;try{H=await this.loadConfigurationStrategies(U,!0,Y)}catch(z){let A=U.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(A)throw z;H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let W=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),Q=!W&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),R=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(A&&(R||W))throw z;if(Q&&(!A||!R))H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!A)H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(J||G)await this.validateConfiguration(H.config,J,G,U.name);if(Y?.enabled&&H)this.cacheResult(U.name||"",H,Y,U);if(X?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(X.onMetrics)X.onMetrics(z);if(X.slowThreshold&&z.duration>X.slowThreshold)U8.warn(`Slow configuration loading detected: ${z.duration}ms for ${U.name}`);H.metrics=z}return H}catch(H){let z=Date.now()-$;throw U8.error(`Configuration loading failed after ${z}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies(Z,$=!1,Y){let{name:X="",alias:J,cwd:G,configDir:U,defaultConfig:H,checkEnv:z=!0,arrayStrategy:A="replace",verbose:W=!1}=Z,Q=G||o8.cwd(),R=[],O=await this.loadLocalConfiguration(X,J,Q,U,H,A,W,z,Y);if(O)return R.push(...this.getLocalSearchPaths(X,J,Q,U)),this.finalizeResult(O,R,z,X,W);let N=await this.loadHomeConfiguration(X,J,H,A,W,z);if(N)return R.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(N,R,z,X,W);let _=await this.loadPackageJsonConfiguration(X,J,Q,H,A,W,z);if(_)return R.push(nZ(Q,"package.json")),this.finalizeResult(_,R,z,X,W);if(R.push(...this.getAllSearchPaths(X,J,Q,U)),$)throw v8.configNotFound(X,R,J);return{...await this.applyEnvironmentVariables(X,H,z,W),warnings:[`No configuration file found for "${X}"${J?` or alias "${J}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Z,$,Y,X,J,G,U,H,z){let A=H?k9(Z,J,U):J,W=this.getLocalDirectories(Y,X);for(let Q of W){if(U)U8.info(`Searching for configuration in: ${Q}`);let R=this.fileLoader.generateConfigPaths(Z,Q,$),O=await this.fileLoader.tryLoadFromPaths(R,A,{arrayStrategy:G,verbose:U,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(O){if(U)U8.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration(Z,$,Y,X,J,G){if(!Z)return null;let U=G?k9(Z,Y,J):Y,H=[nZ(H9(),".config",Z),nZ(H9(),".config"),H9()];for(let z of H){if(J)U8.info(`Checking home directory: ${z}`);let A=this.fileLoader.generateConfigPaths(Z,z,$),W=await this.fileLoader.tryLoadFromPaths(A,U,{arrayStrategy:X,verbose:J});if(W){if(J)U8.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration(Z,$,Y,X,J,G,U){let H=U?k9(Z,X,G):X;try{let z=nZ(Y,"package.json");if(!x7(z))return null;let A=await import(z),W=A[Z],Q=Z;if(!W&&$)W=A[$],Q=$;if(W&&typeof W==="object"&&!Array.isArray(W)){if(G)U8.success(`Configuration loaded from package.json: ${Q}`);return{config:r7(H,W,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)U8.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(Z,$,Y,X){if(!Y||!Z||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:k9(Z,$,X),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Z,$,Y,X,J){return{config:Z.config,source:Z.source,path:Z.source.path}}async validateConfiguration(Z,$,Y,X){let J=[];if(Y){let G=Y(Z);if(G)J.push(...G)}if($){let G=await this.validator.validateConfiguration(Z,$);if(!G.isValid)J.push(...G.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(J.length>0)throw v8.configValidation(X||"unknown",J,X)}checkCache(Z,$){let Y=this.generateCacheKey(Z,$);return B9.get(Y)||null}cacheResult(Z,$,Y,X){let J=this.generateCacheKey(Z,X);B9.set(J,$,void 0,Y.ttl)}generateCacheKey(Z,$){let Y=[Z];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(Z,$){return Array.from(new Set([Z,nZ(Z,"config"),nZ(Z,".config"),$?nZ(Z,$):void 0].filter(Boolean)))}getAllSearchPaths(Z,$,Y,X){let J=[];return J.push(...this.getLocalSearchPaths(Z,$,Y,X)),J.push(...this.getHomeSearchPaths(Z,$)),J.push(nZ(Y,"package.json")),J}getLocalSearchPaths(Z,$,Y,X){let J=this.getLocalDirectories(Y,X),G=[];for(let U of J)G.push(...this.fileLoader.generateConfigPaths(Z,U,$));return G}getHomeSearchPaths(Z,$){if(!Z)return[];let Y=[nZ(H9(),".config",Z),nZ(H9(),".config"),H9()],X=[];for(let J of Y)X.push(...this.fileLoader.generateConfigPaths(Z,J,$));return X}async loadConfigWithResult(Z){return this.loadConfig(Z)}}function jY(Z){let Y=!(Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"))&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")),X=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");return Y||X}async function iG(Z){return I8.loadConfig({...Z,__strictErrorHandling:!0})}async function gY(Z){let $="defaultConfig"in Z&&Z.defaultConfig!==void 0?Z.defaultConfig:{},Y="cache"in Z||"performance"in Z||"schema"in Z||"validate"in Z;try{let X;if(Y)X=await I8.loadConfig(Z);else X=await I8.loadConfig({...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return X?.config??$}catch(X){let J=X instanceof Error?X.name:"UnknownError",G=X instanceof Error?X.message:String(X);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||G.includes("config"))&&Z.verbose)U8.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let H=Y?{...Z,defaultConfig:$}:{...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Z?Z.checkEnv!==!1:!0)return(await I8.applyEnvironmentVariables(H.name||"",$,!0,H.verbose||!1))?.config??$;return $}}async function lG(Z={defaultConfig:{}}){if(typeof Z==="string"){let{cwd:$}=await import("process");try{return(await I8.loadConfig({name:Z,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&jY(Y)))return(await I8.applyEnvironmentVariables(Z,{},!0,!1)).config;throw Y}}try{return(await I8.loadConfig({...Z,cwd:Z.cwd||o8.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&jY($)))return(await I8.applyEnvironmentVariables(Z.name||"",Z.defaultConfig||{},Z.checkEnv!==!1,Z.verbose||!1)).config;throw $}}async function sG(Z,$,Y="replace"){let X=new h$;try{let J=await X.loadFromPath(Z,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function k9(Z,$,Y=!1){let X=new y$,J=Z.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(U,H=[]){let z={...U};for(let[A,W]of Object.entries(U)){let Q=[...H,A],R=[`${J}_${Q.join("_").toUpperCase()}`,`${J}_${Q.map((_)=>_.toUpperCase()).join("")}`,`${J}_${Q.map((_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,N;for(let _ of R)if(O=o8.env[_],O!==void 0){N=_;break}if(O!==void 0&&N)if(typeof W==="boolean")z[A]=["true","1","yes"].includes(O.toLowerCase());else if(typeof W==="number"){let _=Number(O);if(!Number.isNaN(_))z[A]=_}else if(Array.isArray(W))try{z[A]=JSON.parse(O)}catch{z[A]=O.split(",").map((_)=>_.trim())}else z[A]=O;else if(W&&typeof W==="object"&&!Array.isArray(W))z[A]=G(W,Q)}return z}return G($)}function oG(Z){let $=nZ(o8.cwd(),Z.configDir),Y=nZ(o8.cwd(),Z.generatedDir),X=nZ(Y,"config-types.ts");if(!x7(m0(X)))bJ(m0(X),{recursive:!0,mode:511});let J=x7($)?fJ($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],G=`// Generated by bunfig v${M5}
32
+ export type ConfigNames = ${J.length?`'${J.join("' | '")}'`:"string"}
33
+ `;gJ(X,G,{mode:438})}function rG(Z){let $=null,Y=null,X=()=>{if(!Y)Y=gY(Z).then((G)=>{return $=G,G},(G)=>{let U="defaultConfig"in Z?Z.defaultConfig:{};if($=U,"verbose"in Z&&Z.verbose)U8.warn("Config loading failed, using defaults:",[G instanceof Error?G:Error(String(G))]);return U});return Y},J="defaultConfig"in Z?Z.defaultConfig:{};return $=J,X(),new Proxy({},{get(G,U){if($)return $[U];let H=J[U];return X(),H},has(G,U){return U in($||J)},ownKeys(){return Object.keys($||J)},getOwnPropertyDescriptor(G,U){return Object.getOwnPropertyDescriptor($||J,U)},set(G,U,H){if(!$)$={...J};return $[U]=H,!0}})}function aG(Z){let $=XY(AG.cwd(),Z?.configDir||"./config");function Y(){if(!zG($))return[];let J=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),G=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=HG($).filter((z)=>J.has(I7(z))).map((z)=>({base:z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:z})),H=new Map;for(let{base:z,file:A}of U){let W=I7(A).toLowerCase(),Q=H.get(z);if(!Q){H.set(z,A);continue}let R=I7(Q).toLowerCase();if(G.indexOf(W)<G.indexOf(R))H.set(z,A)}return Array.from(H.entries()).map(([z,A])=>({base:z,file:A})).sort((z,A)=>z.base.localeCompare(A.base))}function X(){let J=Y(),G=J.map((A)=>A.base),U=G.length?G.map((A)=>`'${A}'`).join(" | "):"string",H=J.length?`{
34
+ ${J.map((A)=>{let W=XY($,A.file).replace(/\\/g,"/");return` '${A.base}': typeof import('${W}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${U}
37
+ export type ConfigByName = ${H}
38
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
+ export type ConfigOf = Config
40
+ `}return{name:"bunfig-plugin",setup(J){J.onResolve({filter:/^virtual:bunfig-types$/},(G)=>{return{path:G.path,namespace:"bunfig-virtual"}}),J.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:X(),loader:"ts"}})}}}function C5(Z,$={}){let Y=M$.cwd();while(Y.includes("storage"))Y=JY(Y,"..");let X=JY(Y,Z||"");if($?.relative)return jG(M$.cwd(),X);return X}function vZ(){if(E8.env.NODE_ENV==="test"||E8.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function N5(){if(E8.env.NODE_ENV==="test"||E8.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof E8<"u"){let Z=E8.type;if(Z==="renderer"||Z==="worker")return!1;return!!(E8.versions&&(E8.versions.node||E8.versions.bun))}return!1}class oY{async format(Z){let $=await N5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:Z.timestamp.toISOString(),level:Z.level,name:Z.name,message:Z.message,metadata:Y})}async getMetadata(Z){if(Z){let{hostname:$}=await import("os");return{pid:F9.pid,hostname:$(),environment:F9.env.NODE_ENV||"development",platform:F9.platform,version:F9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:F9.env.NODE_ENV||F9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class b${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(Z,$={}){this.name=Z,this.config={...T$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new oY,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??_Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},X=$.timestamp!==void 0;if(X)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:X||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),G=this.generateKey();this.currentKeyId=J,this.keys.set(J,G),this.encryptionKeys.set(J,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Z){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[Z]>=$[Y]}initializeFingersCrossedConfig(Z){if(!Z.fingersCrossedEnabled&&Z.fingersCrossed)return{...T7,...Z.fingersCrossed};if(!Z.fingersCrossedEnabled)return null;if(!Z.fingersCrossed)return{...T7};return{...T7,...Z.fingersCrossed}}normalizeOptions(Z){let $={format:"json",level:"info",logDirectory:T$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(Z).filter(([,X])=>X!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!vZ()&&this.config.writeToFile===!0}async writeToFile(Z){let Y=(async()=>{let J,G=0,U=3,H=1000;while(G<U)try{try{try{await LG(this.config.logDirectory,HY.F_OK|HY.W_OK)}catch(A){if(A instanceof Error&&"code"in A)if(A.code==="ENOENT")await FG(this.config.logDirectory,{recursive:!0,mode:493});else if(A.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw A;else throw A}}catch(A){throw console.error("Debug: [writeToFile] Failed to create log directory:",A),A}let z=this.validateEncryptionConfig()?(await this.encrypt(Z)).encrypted:R8.from(Z);try{if(!A$(this.currentLogFile))await C7(this.currentLogFile,"",{mode:420});if(J=zY(this.currentLogFile,"a",420),KG(J,z,{flag:"a"}),UY(J),J!==void 0)w7(J),J=void 0;if((await K9(this.currentLogFile)).size===0){if(await C7(this.currentLogFile,z,{flag:"w",mode:420}),(await K9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(A){let W=A;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(G<U-1){let Q=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${U}:`,Q);let R=H*2**G;await new Promise((O)=>setTimeout(O,R)),G++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{w7(J)}catch(A){console.error("Debug: [writeToFile] Error closing file descriptor:",A)}}}catch(z){if(G===U-1){let W=z,Q=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Q),z}G++;let A=H*2**(G-1);await new Promise((W)=>setTimeout(W,A))}})();this.pendingOperations.push(Y);let X=this.pendingOperations.length-1;try{await Y}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(X,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 L9(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 L9(this.config.logDirectory,`${this.name}.log`);let Z=new Date().toISOString().split("T")[0];return L9(this.config.logDirectory,`${this.name}-${Z}.log`)}setupRotation(){if(vZ())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Z=this.config.rotation,$;switch(Z.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,X=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,X),this.encryptionKeys.set(Y,{key:X,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,z])=>z.createdAt.getTime()-H.createdAt.getTime()),G=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,G);if(J.length>U)for(let[H]of J.slice(U))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return M7(16).toString("hex")}generateKey(){return M7(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Z=this.keys.get(this.currentKeyId);if(!Z)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Z,id:this.currentKeyId}}encrypt(Z){let{key:$}=this.getCurrentKey(),Y=M7(16),X=QG("aes-256-gcm",$,Y),J=R8.isBuffer(Z)?Z:R8.from(Z,"utf8"),G=X.update(J),U=X.final(),H=G.length+U.length,z=X.getAuthTag(),A=R8.allocUnsafe(16+H+16);return Y.copy(A,0),G.copy(A,16),U.copy(A,16+G.length),z.copy(A,16+H),{encrypted:A,iv:Y}}async compressData(Z){return new Promise(($,Y)=>{let X=WY(),J=[];X.on("data",(G)=>J.push(G)),X.on("end",()=>$(R8.from(R8.concat(J)))),X.on("error",Y),X.write(Z),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Z={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Z,...$}}return Z}async rotateLog(){if(vZ())return;if(!this.shouldWriteToFile())return;let Z=await K9(this.currentLogFile).catch(()=>null);if(!Z)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Z.size>=$.maxSize){let Y=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await W$(this.config.logDirectory),G=J.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,A)=>{let W=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(A.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),U=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Y}.${U}`;if(await K9(Y).catch(()=>null))try{if(await AY(Y,H),$.compress)try{let z=`${H}.gz`;await this.compressLogFile(H,z),await j$(H)}catch(z){console.error("Error compressing rotated file:",z)}if(G.length===0&&!J.some((z)=>z.endsWith(".log.1")))try{let z=`${Y}.1`;await C7(z,"")}catch(z){console.error("Error creating backup file:",z)}}catch(z){console.error(`Error during rotation: ${z instanceof Error?z.message:String(z)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${J}.log`);if(await K9(Y).catch(()=>null))await AY(Y,G)}if(this.currentLogFile=X,$.maxFiles){let G=(await W$(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,H)=>H.localeCompare(U));for(let U of G.slice($.maxFiles))await j$(L9(this.config.logDirectory,U))}}}async compressLogFile(Z,$){let Y=GY(Z),X=VG($),J=WY();await OG(Y,J,X)}async handleFingersCrossedBuffer(Z,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Z)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let X=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(Z){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Z]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Z)=>{if(Z instanceof Promise)return Z.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),A$(this.currentLogFile))try{let Z=zY(this.currentLogFile,"r+");UY(Z),w7(Z)}catch(Z){console.error(`Error flushing file: ${Z}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Z of this.pendingOperations)if(typeof Z.cancel==="function")Z.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Z){console.error("Error waiting for pending operations:",Z)}if(!vZ()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await W$(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await j$(L9(this.config.logDirectory,Y))}catch(X){console.error(`Failed to delete temp file ${Y}:`,X)}}catch(Z){console.error("Error cleaning up temporary files:",Z)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Z){if(!Z)return"";return`${this.tagFormat.prefix}${Z}${this.tagFormat.suffix}`}formatFileTimestamp(Z){return`[${Z.toISOString()}]`}formatConsoleTimestamp(Z){return this.shouldStyleConsole()?KZ.gray(Z.toLocaleTimeString()):Z.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||vZ())return!1;let Z=typeof _Z.env.NO_COLOR<"u",$=_Z.env.FORCE_COLOR==="0";if(Z||$)return!1;return!!(typeof _Z.stderr<"u"&&_Z.stderr.isTTY||typeof _Z.stdout<"u"&&_Z.stdout.isTTY)}formatConsoleMessage(Z){let{timestamp:$,icon:Y="",tag:X="",message:J,level:G,showTimestamp:U=!0}=Z,H=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(U)O.push($);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)O.push(X.replace(/[[\]]/g,""));return O.push(J),O.join(" ")}let z=_Z.stdout.columns||120,A="";if(G==="warning"||G==="error")A=`${Y} ${J}`;else if(G==="info"||G==="success")A=`${Y} ${X} ${J}`;else A=`${Y} ${X} ${KZ.cyan(J)}`;if(!U)return A.trim();let W=H(A).trim().length,Q=H($).length,R=Math.max(1,z-2-W-Q);return`${A.trim()}${" ".repeat(R)}${$}`}formatMessage(Z,$){if($.length===1&&Array.isArray($[0]))return Z.replace(/\{(\d+)\}/g,(G,U)=>{let H=Number.parseInt(U,10);return H<$[0].length?String($[0][H]):G});let Y=/%([sdijfo%])/g,X=0,J=Z.replace(Y,(G,U)=>{if(U==="%")return"%";if(X>=$.length)return G;let H=$[X++];switch(U){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 G}});if(X<$.length)J+=` ${$.slice(X).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return J}formatMarkdown(Z){if(!Z)return Z;let $=Z;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,X,J)=>{let G=KZ.underline(KZ.blue(X)),U=this.toAbsoluteFilePath(J);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(U)}`,z="\x1B]8;;",A="\x1B\\";return`\x1B]8;;${H}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),$=$.replace(/`([^`]+)`/g,(Y,X)=>KZ.bgGray(X)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,X)=>KZ.bold(X)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,X)=>KZ.italic(X)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,X)=>KZ.italic(X)),$=$.replace(/~([^~]+)~/g,(Y,X)=>KZ.strikethrough(X)),$}supportsHyperlinks(){if(vZ())return!1;let Z=_Z.env;if(!Z)return!1;if(Z.TERM_PROGRAM==="iTerm.app"||Z.TERM_PROGRAM==="vscode"||Z.TERM_PROGRAM==="WezTerm")return!0;if(Z.WT_SESSION)return!0;if(Z.TERM==="xterm-kitty")return!0;let $=Z.VTE_VERSION?Number.parseInt(Z.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(Z){try{let $=Z;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=_Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(BG($)||$.startsWith("./")||$.startsWith("../"))$=RG($);else return null;return A$($)?$:null}catch{return null}}buildOutputTexts(Z){let $=this.shouldStyleConsole()?this.formatMarkdown(Z):Z,Y=Z.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(Z,$,...Y){if(!this.shouldLog(Z))return;let X=new Date,J=this.formatConsoleTimestamp(X),G=this.formatFileTimestamp(X),U,H;if($ instanceof Error)U=$.message,H=$.stack;else U=this.formatMessage($,Y);let{consoleText:z,fileText:A}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let Q=this.options.showIcons===!1?"":x5[Z],R=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"",O;switch(Z){case"debug":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:KZ.gray(z),level:Z}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:KZ.green(z),level:Z}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:J,icon:Q,tag:R,message:z,level:Z}),console.error(O),H){let N=H.split(`
41
+ `);for(let _ of N)if(_.trim()&&!_.includes(U))console.error(this.formatConsoleMessage({timestamp:J,message:KZ.gray(` ${_}`),level:Z,showTimestamp:!1}))}break}}else if(!vZ()){if(console.error(`${G} ${this.environment}.${Z.toUpperCase()}: ${U}`),H)console.error(H)}let W=`${G} ${this.environment}.${Z.toUpperCase()}: ${A}
42
+ `;if(H)W+=`${H}
43
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress(Z,$=""){let Y={update:(H,z)=>{},finish:(H)=>{},interrupt:(H,z)=>{}};if(!this.enabled)return Y;let X=30;if(this.activeProgressBar={total:Math.max(1,Z||1),current:0,message:$||"",barLength:X,lastRenderedLine:""},this.shouldStyleConsole()&&!vZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(H,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,H),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!vZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,z="info")=>{if(!vZ()&&_Z.stdout.isTTY)_Z.stdout.write(`
44
+ `);if(this[z==="warning"?"warn":z](H),this.activeProgressBar&&this.shouldStyleConsole()&&!vZ()&&_Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Z){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:this.options.showIcons===!1?"":KZ.blue("\u25D0"),tag:Y,message:`${KZ.cyan(Z)}...`}))}return async(Y)=>{if(!this.enabled)return;let X=performance.now(),J=Math.round(X-$),G=`${Z} completed in ${J}ms`,U=new Date,H=this.formatConsoleTimestamp(U),A=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${G}`;if(Y)A+=` ${JSON.stringify(Y)}`;if(A+=`
45
+ `,A=A.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":KZ.green("\u2713"),tag:W,message:`${G}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!vZ())console.error(A.trim());if(this.shouldWriteToFile())await this.writeToFile(A)}}async debug(Z,...$){await this.log("debug",Z,...$)}async info(Z,...$){await this.log("info",Z,...$)}async success(Z,...$){await this.log("success",Z,...$)}async warn(Z,...$){await this.log("warning",Z,...$)}async error(Z,...$){await this.log("error",Z,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Z=this.config.rotation,{encrypt:$}=Z;return!!$}async only(Z){if(!this.enabled)return;return await Z()}isEnabled(){return this.enabled}setEnabled(Z){this.enabled=Z}extend(Z){let $=`${this.name}:${Z}`,Y=new b$($,{...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(Y),Y}createReadStream(){if(vZ())throw Error("createReadStream is not supported in browser environments");if(!A$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return GY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Z){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let X=R8.isBuffer(Z)?Z:R8.from(Z,"base64"),J=X.subarray(0,16),G=X.subarray(X.length-16),U=X.subarray(16,X.length-16),H=_G("aes-256-gcm",Y,J);H.setAuthTag(G);let z=H.update(U),A=H.final(),W=z.length+A.length,Q=R8.allocUnsafe(W);return z.copy(Q,0),A.copy(Q,z.length),Q.toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return vZ()}isServerMode(){return!vZ()}setTestEncryptionKey(Z,$){this.currentKeyId=Z,this.keys.set(Z,$)}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(Z){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($),{consoleText:J,fileText:G}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let H=J.split(`
46
+ `),z=Math.max(...H.map((R)=>R.length))+2,A=`\u250C${"\u2500".repeat(z)}\u2510`,W=`\u2514${"\u2500".repeat(z)}\u2518`,Q=H.map((R)=>{return this.formatConsoleMessage({timestamp:Y,message:KZ.cyan(R),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:KZ.cyan(A),showTimestamp:!1})),Q.forEach((R)=>console.error(R)),console.error(this.formatConsoleMessage({timestamp:Y,message:KZ.cyan(W),showTimestamp:!1}))}else if(!vZ())console.error(`${X} ${this.environment}.INFO: [BOX] ${G}`);let U=`${X} ${this.environment}.INFO: [BOX] ${G}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Z){if(vZ())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${KZ.cyan("?")} ${Z} (y/n) `);let Y=(X)=>{let J=X.toString().trim().toLowerCase();_Z.stdin.removeListener("data",Y);try{if(typeof _Z.stdin.setRawMode==="function")_Z.stdin.setRawMode(!1)}catch{}_Z.stdin.pause(),console.error(""),$(J==="y"||J==="yes")};try{if(typeof _Z.stdin.setRawMode==="function")_Z.stdin.setRawMode(!0)}catch{}_Z.stdin.resume(),_Z.stdin.once("data",Y)})}setFancy(Z){this.fancy=Z}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Z,...$){if(!this.enabled)return;let Y=Z;if($&&$.length>0){let z=/%([sdijfo%])/g,A=0;if(Y=Z.replace(z,(W,Q)=>{if(Q==="%")return"%";if(A>=$.length)return W;let R=$[A++];switch(Q){case"s":return String(R);case"d":case"i":return Number(R).toString();case"j":case"o":return JSON.stringify(R,null,2);default:return W}}),A<$.length)Y+=` ${$.slice(A).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:X,fileText:J}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?KZ.gray(this.formatTag(this.name)):"",A=this.options.showIcons===!1?"":`${KZ.blue("\u25D0")} `;console.error(`${A}${z} ${KZ.cyan(X)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar(Z,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!_Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Z.current/Z.total*100))),X=Math.round(Z.barLength*Y/100),J=Z.barLength-X,G=KZ.green("\u2501".repeat(X)),U=KZ.gray("\u2501".repeat(J)),H=`[${G}${U}]`,z=`${Y}%`.padStart(4),A=Z.message?` ${Z.message}`:"",W=this.options.showIcons===!1?"":$||Y===100?KZ.green("\u2713"):KZ.blue("\u25B6"),Q=this.options.showTags!==!1&&this.name?` ${KZ.gray(this.formatTag(this.name))}`:"",R=`\r${W}${Q} ${H} ${z}${A}`,O=_Z.stdout.columns||80,N=" ".repeat(Math.max(0,O-R.replace(this.ANSI_PATTERN,"").length));if(Z.lastRenderedLine=`${R}${N}`,_Z.stdout.write(Z.lastRenderedLine),$)_Z.stdout.write(`
49
+ `)}finishProgressBar(Z,$){if(!this.enabled||!this.fancy||vZ()||!_Z.stdout.isTTY){this.activeProgressBar=null;return}if(Z.current<Z.total)Z.current=Z.total;if($)Z.message=$;this.renderProgressBar(Z,!0),this.activeProgressBar=null}async clear(Z={}){if(vZ()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await W$(this.config.logDirectory),Y=[];for(let X of $){if(!(Z.name?new RegExp(Z.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let G=L9(this.config.logDirectory,X);if(Z.before)try{if((await K9(G)).mtime>=Z.before)continue}catch(U){console.error(`Failed to get stats for file ${G}:`,U);continue}Y.push(G)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let X of Y)try{await j$(X),console.warn(`Deleted log file: ${X}`)}catch(J){console.error(`Failed to delete log file ${X}:`,J)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function v5(Z,$={}){let{maxRetries:Y=3,retryDelay:X=1000,isRetryable:J=()=>!0,fallback:G}=$,U=Error("Unknown error occurred");for(let H=0;H<=Y;H++)try{return await Z()}catch(z){if(U=z instanceof Error?z:Error(String(z)),H===Y||!J(U))break;if(X>0)await new Promise((A)=>setTimeout(A,X))}if(G!==void 0)return G;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class Z0{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Z,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(Z.toLowerCase()),parse:(Z)=>{let $=Z.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(Z,$)=>$==="number"||!Number.isNaN(Number(Z))&&!Number.isNaN(Number.parseFloat(Z)),parse:(Z)=>{let $=Number(Z);if(Number.isNaN($))throw TypeError(`Cannot parse "${Z}" as number`);return $}},{name:"array",canParse:(Z,$)=>$==="array"||Z.startsWith("[")||Z.includes(","),parse:(Z)=>{try{let $=JSON.parse(Z);if(Array.isArray($))return $}catch{}return Z.split(",").map(($)=>$.trim())}},{name:"json",canParse:(Z,$)=>$==="object"||(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")),parse:(Z)=>{try{return JSON.parse(Z)}catch($){throw Error(`Cannot parse "${Z}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(Z,$,Y={}){let{prefix:X,useCamelCase:J=!0,useBackwardCompatibility:G=!0,customParsers:U={},verbose:H=!1,trackPerformance:z=!0}=Y,A=async()=>{if(!Z)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let W=X||this.generateEnvPrefix(Z),Q={...$};return this.processObject(Q,[],W,{useCamelCase:J,useBackwardCompatibility:G,customParsers:U,verbose:H,configName:Z}),{config:Q,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return n7.track("applyEnvironmentVariables",A,{configName:Z});return A()}generateEnvPrefix(Z){return Z.toUpperCase().replace(/-/g,"_")}formatEnvKey(Z,$){if(!$)return Z.toUpperCase();return Z.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=U.map((W)=>this.formatEnvKey(W,X.useCamelCase)),z=`${Y}_${H.join("_")}`,A=X.useBackwardCompatibility?`${Y}_${U.map((W)=>W.toUpperCase()).join("_")}`:null;if(X.verbose);if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.processObject(G,U,Y,X);else{let W=_$.env[z]||(A?_$.env[A]:void 0);if(W!==void 0){if(X.verbose){let Q=_$.env[z]?z:A}try{Z[J]=this.parseEnvironmentValue(W,typeof G,z,X.customParsers,X.configName)}catch(Q){if(Q instanceof e7)throw Q;throw s8.envVar(z,W,typeof G,X.configName)}}}}}parseEnvironmentValue(Z,$,Y,X,J){for(let[G,U]of Object.entries(X))try{return U(Z)}catch{continue}for(let G of this.defaultParsers)if(G.canParse(Z,$))try{return G.parse(Z)}catch{throw s8.envVar(Y,Z,`${$} (via ${G.name} parser)`,J)}return Z}getEnvironmentVariables(Z){let $={},Y=Z.toUpperCase();for(let[X,J]of Object.entries(_$.env))if(X.startsWith(Y)&&J!==void 0)$[X]=J;return $}validateEnvironmentVariable(Z,$,Y){let X=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Z))X.push(`Environment variable key "${Z}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Z,$,Y,{})}catch(J){X.push(`Cannot parse value "${$}" as ${Y}: ${J}`)}return{isValid:X.length===0,errors:X}}generateEnvVarDocs(Z,$,Y={}){let{prefix:X,format:J="text"}=Y,G=X||this.generateEnvPrefix(Z),U=[];switch(this.extractEnvVarInfo($,[],G,U),J){case"markdown":return this.formatAsMarkdown(U,Z);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Z)}}extractEnvVarInfo(Z,$,Y,X){for(let[J,G]of Object.entries(Z)){let U=[...$,J],H=`${Y}_${U.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof G==="object"&&G!==null&&!Array.isArray(G))this.extractEnvVarInfo(G,U,Y,X);else X.push({key:H,type:Array.isArray(G)?"array":typeof G,description:`Configuration for ${U.join(".")}`,example:this.generateExample(G)})}}generateExample(Z){if(Array.isArray(Z))return JSON.stringify(Z);if(typeof Z==="object"&&Z!==null)return JSON.stringify(Z);return String(Z)}formatAsText(Z,$){let Y=`Environment Variables for ${$}:
50
+
51
+ `;for(let X of Z)Y+=`${X.key}
52
+ `,Y+=` Type: ${X.type}
53
+ `,Y+=` Description: ${X.description}
54
+ `,Y+=` Example: ${X.example}
55
+
56
+ `;return Y}formatAsMarkdown(Z,$){let Y=`# Environment Variables for ${$}
57
+
58
+ `;Y+=`| Variable | Type | Description | Example |
59
+ `,Y+=`|----------|------|-------------|----------|
60
+ `;for(let X of Z)Y+=`| \`${X.key}\` | ${X.type} | ${X.description} | \`${X.example}\` |
61
+ `;return Y}}function y5(Z,$,Y={}){return XX(Z,$,Y,new WeakMap)}function XX(Z,$,Y,X){let{arrayMergeMode:J="replace",skipNullish:G=!1,customMerger:U}=Y;if($===null||$===void 0)return G?Z:$;if(U){let H=U(Z,$);if(H!==void 0)return H}if(Array.isArray($)||Array.isArray(Z))return JX(Z,$,J,X);if(!X8($)||!X8(Z))return $;return g5(Z,$,Y,X)}function JX(Z,$,Y,X){if(Array.isArray($)&&!Array.isArray(Z))return $;if(Array.isArray(Z)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(Z))switch(Y){case"replace":return $;case"concat":return h5(Z,$);case"smart":return b5(Z,$,X);default:return $}return $}function h5(Z,$){let Y=[...$];for(let X of Z)if(!Y.some((J)=>u7(J,X)))Y.push(X);return Y}function b5(Z,$,Y){if($.length===0)return Z;if(Z.length===0)return $;if(X8($[0])&&X8(Z[0]))return f5(Z,$,Y);if($.every((X)=>typeof X==="string")&&Z.every((X)=>typeof X==="string")){let X=[...$];for(let J of Z)if(!X.includes(J))X.push(J);return X}return $}function f5(Z,$,Y){let X=[...$];for(let J of Z){if(!X8(J)){X.push(J);continue}let G=["id","name","key","path","type"],U=!1;for(let H of G)if(H in J){if(X.find((A)=>X8(A)&&(H in A)&&A[H]===J[H])){U=!0;break}}if(!U)X.push(J)}return X}function g5(Z,$,Y,X){let J=$;if(X8(J)&&X.has(J))return X.get(J);let G={...Z};if(X8(J))X.set(J,G);for(let U in J){if(!Object.prototype.hasOwnProperty.call(J,U))continue;let H=J[U],z=G[U];if(Y.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){G[U]=H;continue}if(X8(H)&&X8(z))G[U]=XX(z,H,Y,X);else if(Array.isArray(H)||Array.isArray(z))G[U]=JX(z,H,Y.arrayMergeMode||"smart",X);else G[U]=H}return G}function GX(Z,$,Y="replace"){return y5(Z,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function u7(Z,$){if(Z===$)return!0;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;for(let Y=0;Y<Z.length;Y++)if(!u7(Z[Y],$[Y]))return!1;return!0}if(X8(Z)&&X8($)){let Y=Object.keys(Z),X=Object.keys($);if(Y.length!==X.length)return!1;for(let J of Y){if(!Object.prototype.hasOwnProperty.call($,J))return!1;if(!u7(Z[J],$[J]))return!1}return!0}return!1}function X8(Z){return Boolean(Z&&typeof Z==="object"&&!Array.isArray(Z))}class UX{extensions=SY;async loadFromPath(Z,$,Y={}){let{arrayStrategy:X="replace",useCache:J=!0,cacheTtl:G,trackPerformance:U=!0,verbose:H=!1}=Y;if(J){let A=O$.getWithFileCheck("file",Z);if(A){if(H)console.log(`Configuration loaded from cache: ${Z}`);return A}}let z=async()=>{if(!V$(Z))return null;try{let A=`?t=${Date.now()}`,W=await import(Z+A),Q=W.default||W,R="default"in W,O=Object.keys(W).length>0;if(!R&&!O)throw new k$(Z,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new k$(Z,Error("Configuration must export a valid object"),"unknown");let F={config:GX($,Q,X),source:{type:"file",path:Z,priority:100,timestamp:new Date}};if(J)O$.setWithFileCheck("file",F,Z,G);return F}catch(A){throw A instanceof Error?s8.configLoad(Z,A):s8.configLoad(Z,Error(String(A)))}};if(U)return n7.track("loadFromPath",z,{path:Z});return z()}async tryLoadFromPaths(Z,$,Y={}){for(let X of Z)try{let J=await this.loadFromPath(X,$,Y);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Y.verbose)console.warn(`Failed to load config from ${X}:`,J)}return null}generateConfigPaths(Z,$,Y){return xJ({name:Z,directory:$,alias:Y})}generateNamePatterns(Z,$){return NY({name:Z,alias:$})}checkFileAccess(Z){return v5(async()=>{return V$(Z)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Z,$,Y){let X=[];if(!V$(Z))return X;if($||Y){let J=this.generateNamePatterns($||"",Y);for(let G of J)for(let U of this.extensions){let H=MY(Z,`${G}${U}`);if(await this.checkFileAccess(H))X.push(H)}}else try{let{readdirSync:J}=await import("fs"),G=J(Z);for(let U of G)if(this.looksLikeConfigFile(U)){let H=MY(Z,U);if(await this.checkFileAccess(H))X.push(H)}}catch{return[]}return X}looksLikeConfigFile(Z){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((Y)=>Y.test(Z))}async validateConfigFile(Z){let $=[];try{if(!V$(Z))return $.push("Configuration file does not exist"),$;let Y=await import(Z),X=Y.default||Y;if(X===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof X!=="object"||X===null)$.push("Configuration must be an object");else if(Array.isArray(X))$.push("Configuration cannot be an array at the root level");if(Z.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),G=J(Z,"utf8");JSON.parse(G)}catch(J){$.push(`Invalid JSON syntax: ${J}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(Z){try{let{statSync:$}=await import("fs");return $(Z).mtime}catch{return null}}async preloadConfigurations(Z,$={}){let Y=new Map;return await Promise.allSettled(Z.map(async(X)=>{try{let J=await this.loadFromPath(X,{},$);if(J)Y.set(X,J.config)}catch(J){if($.verbose)console.warn(`Failed to preload ${X}:`,J)}})),Y}}class zX{async validateConfiguration(Z,$,Y={}){let{stopOnFirstError:X=!1,validateRequired:J=!0,validateTypes:G=!0,customRules:U=[],trackPerformance:H=!0,verbose:z=!1}=Y,A=async()=>{let W=[],Q=[],R={stopOnFirstError:X,validateRequired:J,validateTypes:G,customRules:U,trackPerformance:H,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(Z,$,R);else if(Array.isArray($))return this.validateWithRules(Z,[...$,...U],R);else return this.validateWithJSONSchema(Z,$,R)}catch(O){return W.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:W,warnings:Q}}};if(H)return await n7.track("validateConfiguration",A);return A()}async validateWithSchemaFile(Z,$,Y){try{if(!p5($))throw new x$($,[{path:"",message:"Schema file does not exist"}]);let X=await import($),J=X.default||X;if(Array.isArray(J))return this.validateWithRules(Z,J,Y);else return this.validateWithJSONSchema(Z,J,Y)}catch(X){throw new x$($,[{path:"",message:`Failed to load schema: ${X}`}])}}validateWithJSONSchema(Z,$,Y){let X=[],J=[];return this.validateObjectAgainstSchema(Z,$,"",X,J,Y),{isValid:X.length===0,errors:X,warnings:J}}validateObjectAgainstSchema(Z,$,Y,X,J,G){if(G.validateTypes&&$.type){let U=Array.isArray(Z)?"array":typeof Z,H=Array.isArray($.type)?$.type:[$.type];if(!H.includes(U)){if(X.push({path:Y,message:`Expected type ${H.join(" or ")}, got ${U}`,expected:H.join(" or "),actual:U,rule:"type"}),G.stopOnFirstError)return}}if($.enum&&!$.enum.includes(Z)){if(X.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"}),G.stopOnFirstError)return}if(typeof Z==="string"){if($.minLength!==void 0&&Z.length<$.minLength)X.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:Z.length,rule:"minLength"});if($.maxLength!==void 0&&Z.length>$.maxLength)X.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:Z.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(Z))X.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:Z,rule:"pattern"})}}if(typeof Z==="number"){if($.minimum!==void 0&&Z<$.minimum)X.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:Z,rule:"minimum"});if($.maximum!==void 0&&Z>$.maximum)X.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:Z,rule:"maximum"})}if(Array.isArray(Z)&&$.items)for(let U=0;U<Z.length;U++){let H=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Z[U],$.items,H,X,J,G),G.stopOnFirstError&&X.length>0)return}if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let U=Z;if(G.validateRequired&&$.required){for(let H of $.required)if(!(H in U)){if(X.push({path:Y?`${Y}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if($.properties){for(let[H,z]of Object.entries($.properties))if(H in U){let A=Y?`${Y}.${H}`:H;if(this.validateObjectAgainstSchema(U[H],z,A,X,J,G),G.stopOnFirstError&&X.length>0)return}}if($.additionalProperties===!1){let H=new Set(Object.keys($.properties||{}));for(let z of Object.keys(U))if(!H.has(z))J.push({path:Y?`${Y}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Z,$,Y){let X=[],J=[];for(let G of $)try{let U=this.getValueByPath(Z,G.path),H=this.validateWithRule(U,G,G.path);if(X.push(...H),Y.stopOnFirstError&&X.length>0)break}catch(U){X.push({path:G.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:X.length===0,errors:X,warnings:J}}validateWithRule(Z,$,Y){let X=[];if($.required&&(Z===void 0||Z===null))return X.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),X;if(Z===void 0||Z===null)return X;if($.type){let J=Array.isArray(Z)?"array":typeof Z;if(J!==$.type)X.push({path:Y,message:$.message||`Expected type ${$.type}, got ${J}`,expected:$.type,actual:J,rule:"type"})}if($.min!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J<$.min)X.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:J,rule:"min"})}if($.max!==void 0){let J=Array.isArray(Z)?Z.length:typeof Z==="string"?Z.length:typeof Z==="number"?Z:0;if(J>$.max)X.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:J,rule:"max"})}if($.pattern&&typeof Z==="string"){if(!$.pattern.test(Z))X.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:Z,rule:"pattern"})}if($.enum&&!$.enum.includes(Z))X.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:Z,rule:"enum"});if($.validator){let J=$.validator(Z);if(J)X.push({path:Y,message:$.message||J,rule:"custom"})}return X}getValueByPath(Z,$){if(!$)return Z;let Y=$.split("."),X=Z;for(let J of Y)if(X&&typeof X==="object"&&J in X)X=X[J];else return;return X}generateRulesFromInterface(Z){let $=[],Y=Z.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let X of Y){let[,J,G,U]=X;$.push({path:J,required:!G,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(Z){switch(Z.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:d5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function m5(Z){if(!Z)return"";let $=Array.isArray(Z)?Z.filter(Boolean):[Z];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class HX{fileLoader=new UX;envProcessor=new Z0;validator=new zX;async loadConfig(Z){let $=Date.now(),{cache:Y,performance:X,schema:J,validate:G,...U}=Z;try{if(Y?.enabled){let z=this.checkCache(U.name||"",U);if(z)return z}let H;try{H=await this.loadConfigurationStrategies(U,!0,Y)}catch(z){if(U.configFile)throw z;let A=U.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(A)throw z;H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let W=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),Q=!W&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),R=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(A&&(R||W))throw z;if(Q&&(!A||!R))H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!A)H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else H={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(J||G)await this.validateConfiguration(H.config,J,G,U.name);if(Y?.enabled&&H)this.cacheResult(U.name||"",H,Y,U);if(X?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(X.onMetrics)X.onMetrics(z);if(X.slowThreshold&&z.duration>X.slowThreshold)G8.warn(`Slow configuration loading detected: ${z.duration}ms for ${U.name}`);H.metrics=z}return H}catch(H){if(H instanceof Error&&H.name==="ConfigNotFoundError")throw H;let z=Date.now()-$;throw G8.error(`Configuration loading failed after ${z}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies(Z,$=!1,Y){let{name:X="",alias:J,configFile:G,cwd:U,configDir:H,defaultConfig:z,checkEnv:A=!0,arrayStrategy:W="replace",verbose:Q=!1}=Z,R=U||v$.cwd(),O=[];if(G){let K=V8(R,G);O.push(K);let I=A?q9(X,z,Q):z,B=await this.fileLoader.tryLoadFromPaths([K],I,{arrayStrategy:W,verbose:Q,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(!B)throw s8.configNotFound(X||G,O,J);if(Q)G8.success(`Configuration loaded from explicit path: ${K}`);return this.finalizeResult(B,O,A,X,Q)}let N=await this.loadLocalConfiguration(X,J,R,H,z,W,Q,A,Y);if(N)return O.push(...this.getLocalSearchPaths(X,J,R,H)),this.finalizeResult(N,O,A,X,Q);let _=await this.loadHomeConfiguration(X,J,z,W,Q,A);if(_)return O.push(...this.getHomeSearchPaths(X,J)),this.finalizeResult(_,O,A,X,Q);let F=await this.loadPackageJsonConfiguration(X,J,R,z,W,Q,A);if(F)return O.push(V8(R,"package.json")),this.finalizeResult(F,O,A,X,Q);if(O.push(...this.getAllSearchPaths(X,J,R,H)),$)throw s8.configNotFound(X,O,J);return{...await this.applyEnvironmentVariables(X,z,A,Q),warnings:[`No configuration file found for "${X}"${m5(J)}, using defaults with environment variables`]}}async loadLocalConfiguration(Z,$,Y,X,J,G,U,H,z){let A=H?q9(Z,J,U):J,W=this.getLocalDirectories(Y,X);for(let Q of W){if(U)G8.info(`Searching for configuration in: ${Q}`);let R=this.fileLoader.generateConfigPaths(Z,Q,$),O=await this.fileLoader.tryLoadFromPaths(R,A,{arrayStrategy:G,verbose:U,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(O){if(U)G8.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration(Z,$,Y,X,J,G){if(!Z)return null;let U=G?q9(Z,Y,J):Y,H=[V8(z9(),".config",Z),V8(z9(),".config"),z9()];for(let z of H){if(J)G8.info(`Checking home directory: ${z}`);let A=this.fileLoader.generateConfigPaths(Z,z,$),W=await this.fileLoader.tryLoadFromPaths(A,U,{arrayStrategy:X,verbose:J});if(W){if(J)G8.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration(Z,$,Y,X,J,G,U){let H=U?q9(Z,X,G):X;try{let z=V8(Y,"package.json");if(!yJ(z))return null;let A={};try{A=JSON.parse(hJ(z,"utf8"))}catch(R){if(G)G8.warn("Failed to parse package.json:",[R instanceof Error?R:Error(String(R))]);return null}let W=A[Z],Q=Z;if(!W&&$){let R=Array.isArray($)?$:[$];for(let O of R){if(!O)continue;if(A[O]){W=A[O],Q=O;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(G)G8.success(`Configuration loaded from package.json: ${Q}`);return{config:GX(H,W,J),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(G)G8.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(Z,$,Y,X){if(!Y||!Z||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:q9(Z,$,X),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Z,$,Y,X,J){return{config:Z.config,source:Z.source,path:Z.source.path}}async validateConfiguration(Z,$,Y,X){let J=[];if(Y){let G=Y(Z);if(G)J.push(...G)}if($){let G=await this.validator.validateConfiguration(Z,$);if(!G.isValid)J.push(...G.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(J.length>0)throw s8.configValidation(X||"unknown",J,X)}checkCache(Z,$){let Y=this.generateCacheKey(Z,$);return O$.get(Y)||null}cacheResult(Z,$,Y,X){let J=this.generateCacheKey(Z,X);O$.set(J,$,void 0,Y.ttl)}generateCacheKey(Z,$){let Y=[Z];if($.alias){let X=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${X}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configFile)Y.push(`configFile:${$.configFile}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(Z,$){return vJ({cwd:Z,configDir:$})}getAllSearchPaths(Z,$,Y,X){let J=[];return J.push(...this.getLocalSearchPaths(Z,$,Y,X)),J.push(...this.getHomeSearchPaths(Z,$)),J.push(V8(Y,"package.json")),J}getLocalSearchPaths(Z,$,Y,X){let J=this.getLocalDirectories(Y,X),G=[];for(let U of J)G.push(...this.fileLoader.generateConfigPaths(Z,U,$));return G}getHomeSearchPaths(Z,$){if(!Z)return[];let Y=[V8(z9(),".config",Z),V8(z9(),".config"),z9()],X=[];for(let J of Y)X.push(...this.fileLoader.generateConfigPaths(Z,J,$));return X}async loadConfigWithResult(Z){return this.loadConfig(Z)}}async function AX(Z){let $="defaultConfig"in Z&&Z.defaultConfig!==void 0?Z.defaultConfig:{},Y="cache"in Z||"performance"in Z||"schema"in Z||"validate"in Z;try{let X;if(Y)X=await k7.loadConfig(Z);else X=await k7.loadConfig({...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return X?.config??$}catch(X){if(Z.configFile)throw X;let J=X instanceof Error?X.name:"UnknownError",G=X instanceof Error?X.message:String(X);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||G.includes("config"))&&Z.verbose)G8.warn("Unexpected error loading config, using defaults:",[X instanceof Error?X:Error(String(X))]);let H=Y?{...Z,defaultConfig:$}:{...Z,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Z?Z.checkEnv!==!1:!0)return(await k7.applyEnvironmentVariables(H.name||"",$,!0,H.verbose||!1))?.config??$;return $}}function q9(Z,$,Y=!1){let X=new Z0,J=Z.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(U,H=[]){let z={...U};for(let[A,W]of Object.entries(U)){let Q=[...H,A],R=[`${J}_${Q.join("_").toUpperCase()}`,`${J}_${Q.map((_)=>_.toUpperCase()).join("")}`,`${J}_${Q.map((_)=>_.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,N;for(let _ of R)if(O=v$.env[_],O!==void 0){N=_;break}if(O!==void 0&&N)if(typeof W==="boolean")z[A]=["true","1","yes"].includes(O.toLowerCase());else if(typeof W==="number"){let _=Number(O);if(!Number.isNaN(_))z[A]=_}else if(Array.isArray(W))try{z[A]=JSON.parse(O)}catch{z[A]=O.split(",").map((_)=>_.trim())}else z[A]=O;else if(W&&typeof W==="object"&&!Array.isArray(W))z[A]=G(W,Q)}return z}return G($)}var O$,n7,SY,DG,EG=(Z)=>Z,MG=(Z,$)=>{for(var Y in $)DG(Z,Y,{get:$[Y],enumerable:!0,configurable:!0,set:IG.bind($,Y)})},wG=(Z,$)=>()=>(Z&&($=Z(Z=0)),$),TY,pY,B9,h9,dY,tG,eG,QY,L$,h7,gZ,EZ,Z5,_Y,$5,VY,Y5,X5,S7,J5,KY,LY,N7,G5,U5,z5,H5,F$,mY,A5,pZ,W5,j5,FY,B$,b7,xZ,VZ,Q5,BY,_5,RY,V5,K5,P7,L5,OY,DY,F5,q7,B5,R5,O5,D5,E5,R$,cY,I5,M5="0.15.6",aZ,P$,v9,f7,g7,q$,p7,d7,y9,m7,c7,v8,uY,nY,U8,I8,iY,lY,w5,S5,sY,T$,z4,hZ,KZ,H4,P5,A4,q5,W4,j4,EY,Q4,T5,k5,_4,IY,V4,K4,L4,F4,B4,T7,x5,R4,H8,rY,k$,aY,tY,e7,eY,ZX,x$,$X,YX,s8,d5,G8,k7,M4,w4;var WX=z8(()=>{O$=new wY,n7=new CY,SY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];DG=Object.defineProperty;TY={};MG(TY,{withErrorRecovery:()=>vY,tryLoadConfig:()=>sG,loadConfigWithResult:()=>iG,loadConfig:()=>gY,isRetryableError:()=>pG,isConfigNotFoundError:()=>gG,isBunfigError:()=>yY,globalPerformanceMonitor:()=>h9,globalCache:()=>B9,getEnvOrDefault:()=>dG,generateConfigTypes:()=>oG,defaultGeneratedDir:()=>lY,defaultConfigDir:()=>iY,deepMergeWithArrayStrategy:()=>r7,deepMerge:()=>hY,createLibraryConfig:()=>rG,config:()=>lG,bunfigPlugin:()=>aG,applyEnvVarsToConfig:()=>k9,TypeGenerationError:()=>d7,SchemaValidationError:()=>y9,PluginError:()=>c7,PerformanceMonitor:()=>l7,FileSystemError:()=>p7,ErrorFactory:()=>v8,EnvVarError:()=>q$,EnvProcessor:()=>y$,ConfigValidator:()=>a7,ConfigValidationError:()=>f7,ConfigNotFoundError:()=>P$,ConfigMergeError:()=>g7,ConfigLoader:()=>t7,ConfigLoadError:()=>v9,ConfigFileLoader:()=>h$,ConfigCache:()=>i7,CacheUtils:()=>dY,BunfigError:()=>aZ,BrowserConfigError:()=>m7,ArrayMergeStrategies:()=>uY});w5=wG(async()=>{pY=import.meta.require,B9=new i7,h9=new l7,dY={createKey:CG,isEquivalent:SG,estimateMemoryUsage:NG},tG=I$(v7.cwd(),"config"),eG=I$(v7.cwd(),"src/generated"),QY=E$.env.CLARITY_LOG_DIR||mJ(TG(),"logs"),L$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:QY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},h7=await kG(),gZ={red:(Z)=>`\x1B[31m${Z}\x1B[0m`,green:(Z)=>`\x1B[32m${Z}\x1B[0m`,yellow:(Z)=>`\x1B[33m${Z}\x1B[0m`,blue:(Z)=>`\x1B[34m${Z}\x1B[0m`,magenta:(Z)=>`\x1B[35m${Z}\x1B[0m`,cyan:(Z)=>`\x1B[36m${Z}\x1B[0m`,white:(Z)=>`\x1B[37m${Z}\x1B[0m`,gray:(Z)=>`\x1B[90m${Z}\x1B[0m`,bgRed:(Z)=>`\x1B[41m${Z}\x1B[0m`,bgYellow:(Z)=>`\x1B[43m${Z}\x1B[0m`,bold:(Z)=>`\x1B[1m${Z}\x1B[0m`,dim:(Z)=>`\x1B[2m${Z}\x1B[0m`,italic:(Z)=>`\x1B[3m${Z}\x1B[0m`,underline:(Z)=>`\x1B[4m${Z}\x1B[0m`,reset:"\x1B[0m"},EZ=gZ,Z5=gZ.red,_Y=gZ.green,$5=gZ.yellow,VY=gZ.blue,Y5=gZ.magenta,X5=gZ.cyan,S7=gZ.white,J5=gZ.gray,KY=gZ.bgRed,LY=gZ.bgYellow,N7=gZ.bold,G5=gZ.dim,U5=gZ.italic,z5=gZ.underline,H5=gZ.reset,F$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mY={debug:"\uD83D\uDD0D",info:VY("\u2139"),success:_Y("\u2713"),warning:LY(S7(N7(" WARN "))),error:KY(S7(N7(" ERROR ")))},A5=new C$("stacks"),pZ=new C$("bunfig",{showTags:!0}),W5=uZ(x9.cwd(),"config"),j5=uZ(x9.cwd(),"src/generated"),FY=D$.env.CLARITY_LOG_DIR||pJ(hG(),"logs"),B$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},b7=await bG(),xZ={red:(Z)=>`\x1B[31m${Z}\x1B[0m`,green:(Z)=>`\x1B[32m${Z}\x1B[0m`,yellow:(Z)=>`\x1B[33m${Z}\x1B[0m`,blue:(Z)=>`\x1B[34m${Z}\x1B[0m`,magenta:(Z)=>`\x1B[35m${Z}\x1B[0m`,cyan:(Z)=>`\x1B[36m${Z}\x1B[0m`,white:(Z)=>`\x1B[37m${Z}\x1B[0m`,gray:(Z)=>`\x1B[90m${Z}\x1B[0m`,bgRed:(Z)=>`\x1B[41m${Z}\x1B[0m`,bgYellow:(Z)=>`\x1B[43m${Z}\x1B[0m`,bgGray:(Z)=>`\x1B[100m${Z}\x1B[0m`,bold:(Z)=>`\x1B[1m${Z}\x1B[0m`,dim:(Z)=>`\x1B[2m${Z}\x1B[0m`,italic:(Z)=>`\x1B[3m${Z}\x1B[0m`,underline:(Z)=>`\x1B[4m${Z}\x1B[0m`,strikethrough:(Z)=>`\x1B[9m${Z}\x1B[0m`,reset:"\x1B[0m"},VZ=xZ,Q5=xZ.red,BY=xZ.green,_5=xZ.yellow,RY=xZ.blue,V5=xZ.magenta,K5=xZ.cyan,P7=xZ.white,L5=xZ.gray,OY=xZ.bgRed,DY=xZ.bgYellow,F5=xZ.bgGray,q7=xZ.bold,B5=xZ.dim,R5=xZ.italic,O5=xZ.underline,D5=xZ.strikethrough,E5=xZ.reset,R$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cY={debug:"\uD83D\uDD0D",info:RY("\u2139"),success:BY("\u2713"),warning:DY(P7(q7(" WARN "))),error:OY(P7(q7(" ERROR ")))},I5=new N$("stacks"),aZ=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,X])=>`${Y}: ${X}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},P$=class extends aZ{code="CONFIG_NOT_FOUND";constructor($,Y,X){let J=X?` or alias "${X}"`:"";super(`Configuration "${$}"${J} not found`,{configName:$,alias:X,searchPaths:Y,searchPathCount:Y.length})}},v9=class extends aZ{code="CONFIG_LOAD_ERROR";constructor($,Y,X){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},f7=class extends aZ{code="CONFIG_VALIDATION_ERROR";constructor($,Y,X){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:X,validationErrors:Y,errorCount:Y.length})}},g7=class extends aZ{code="CONFIG_MERGE_ERROR";constructor($,Y,X,J){super(`Failed to merge configuration from "${$}" with "${Y}": ${X.message}`,{sourcePath:$,targetPath:Y,configName:J,originalError:X.name,originalMessage:X.message});this.cause=X}},q$=class extends aZ{code="ENV_VAR_ERROR";constructor($,Y,X,J){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${X}`,{envKey:$,envValue:Y,expectedType:X,configName:J})}},p7=class extends aZ{code="FILE_SYSTEM_ERROR";constructor($,Y,X){super(`File system ${$} failed for "${Y}": ${X.message}`,{operation:$,path:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},d7=class extends aZ{code="TYPE_GENERATION_ERROR";constructor($,Y,X){super(`Failed to generate types from "${$}" to "${Y}": ${X.message}`,{configDir:$,outputPath:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},y9=class extends aZ{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,X){super(`Schema validation failed${X?` for config "${X}"`:""}`,{schemaPath:$,configName:X,validationErrors:Y,errorCount:Y.length})}},m7=class extends aZ{code="BROWSER_CONFIG_ERROR";constructor($,Y,X,J){super(`Failed to fetch configuration from "${$}": ${Y} ${X}`,{endpoint:$,status:Y,statusText:X,configName:J})}},c7=class extends aZ{code="PLUGIN_ERROR";constructor($,Y,X){super(`Plugin "${$}" failed during ${Y}: ${X.message}`,{pluginName:$,operation:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},v8={configNotFound(Z,$,Y){return new P$(Z,$,Y)},configLoad(Z,$,Y){return new v9(Z,$,Y)},configValidation(Z,$,Y){return new f7(Z,$,Y)},configMerge(Z,$,Y,X){return new g7(Z,$,Y,X)},envVar(Z,$,Y,X){return new q$(Z,$,Y,X)},fileSystem(Z,$,Y){return new p7(Z,$,Y)},typeGeneration(Z,$,Y){return new d7(Z,$,Y)},schemaValidation(Z,$,Y){return new y9(Z,$,Y)},browserConfig(Z,$,Y,X){return new m7(Z,$,Y,X)},plugin(Z,$,Y){return new c7(Z,$,Y)}},uY={replace:"replace",concat:"concat",smart:"smart"},nY=/^https?:\/\//,U8=new N$("bunfig",{showTags:!0}),I8=new t7,iY=nZ(o8.cwd(),"config"),lY=nZ(o8.cwd(),"src/generated")});S5=M$.env.CLARITY_LOG_DIR||WG(C5(),"logs"),sY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:S5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},T$={...sY},z4=(async()=>{try{let{loadConfig:Z}=await w5().then(()=>TY),$=await Z({name:"clarity",alias:"logging",defaultConfig:sY,cwd:M$.cwd()});if($)Object.assign(T$,$)}catch{}return T$})();hZ={red:(Z)=>`\x1B[31m${Z}\x1B[0m`,green:(Z)=>`\x1B[32m${Z}\x1B[0m`,yellow:(Z)=>`\x1B[33m${Z}\x1B[0m`,blue:(Z)=>`\x1B[34m${Z}\x1B[0m`,magenta:(Z)=>`\x1B[35m${Z}\x1B[0m`,cyan:(Z)=>`\x1B[36m${Z}\x1B[0m`,white:(Z)=>`\x1B[37m${Z}\x1B[0m`,gray:(Z)=>`\x1B[90m${Z}\x1B[0m`,bgRed:(Z)=>`\x1B[41m${Z}\x1B[0m`,bgYellow:(Z)=>`\x1B[43m${Z}\x1B[0m`,bgGray:(Z)=>`\x1B[100m${Z}\x1B[0m`,bold:(Z)=>`\x1B[1m${Z}\x1B[0m`,dim:(Z)=>`\x1B[2m${Z}\x1B[0m`,italic:(Z)=>`\x1B[3m${Z}\x1B[0m`,underline:(Z)=>`\x1B[4m${Z}\x1B[0m`,strikethrough:(Z)=>`\x1B[9m${Z}\x1B[0m`,reset:"\x1B[0m"},KZ=hZ,H4=hZ.red,P5=hZ.green,A4=hZ.yellow,q5=hZ.blue,W4=hZ.magenta,j4=hZ.cyan,EY=hZ.white,Q4=hZ.gray,T5=hZ.bgRed,k5=hZ.bgYellow,_4=hZ.bgGray,IY=hZ.bold,V4=hZ.dim,K4=hZ.italic,L4=hZ.underline,F4=hZ.strikethrough,B4=hZ.reset,T7={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},x5={debug:"\uD83D\uDD0D",info:q5("\u2139"),success:P5("\u2713"),warning:k5(EY(IY(" WARN "))),error:T5(EY(IY(" ERROR ")))};R4=new b$("stacks");H8=class H8 extends Error{timestamp;context;constructor(Z,$={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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 Z=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}};rY=class rY extends H8{code="CONFIG_NOT_FOUND";constructor(Z,$,Y){let X=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],J="";if(X.length===1)J=` or alias "${X[0]}"`;else if(X.length>1)J=` or aliases ${X.map((G)=>`"${G}"`).join(", ")}`;super(`Configuration "${Z}"${J} not found`,{configName:Z,alias:Y,searchPaths:$,searchPathCount:$.length})}};k$=class k$ extends H8{code="CONFIG_LOAD_ERROR";constructor(Z,$,Y){super(`Failed to load configuration from "${Z}": ${$.message}`,{configPath:Z,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};aY=class aY extends H8{code="CONFIG_VALIDATION_ERROR";constructor(Z,$,Y){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:Y,validationErrors:$,errorCount:$.length})}};tY=class tY extends H8{code="CONFIG_MERGE_ERROR";constructor(Z,$,Y,X){super(`Failed to merge configuration from "${Z}" with "${$}": ${Y.message}`,{sourcePath:Z,targetPath:$,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};e7=class e7 extends H8{code="ENV_VAR_ERROR";constructor(Z,$,Y,X){super(`Failed to parse environment variable "${Z}" with value "${$}" as ${Y}`,{envKey:Z,envValue:$,expectedType:Y,configName:X})}};eY=class eY extends H8{code="FILE_SYSTEM_ERROR";constructor(Z,$,Y){super(`File system ${Z} failed for "${$}": ${Y.message}`,{operation:Z,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};ZX=class ZX extends H8{code="TYPE_GENERATION_ERROR";constructor(Z,$,Y){super(`Failed to generate types from "${Z}" to "${$}": ${Y.message}`,{configDir:Z,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};x$=class x$ extends H8{code="SCHEMA_VALIDATION_ERROR";constructor(Z,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Z,configName:Y,validationErrors:$,errorCount:$.length})}};$X=class $X extends H8{code="BROWSER_CONFIG_ERROR";constructor(Z,$,Y,X){super(`Failed to fetch configuration from "${Z}": ${$} ${Y}`,{endpoint:Z,status:$,statusText:Y,configName:X})}};YX=class YX extends H8{code="PLUGIN_ERROR";constructor(Z,$,Y){super(`Plugin "${Z}" failed during ${$}: ${Y.message}`,{pluginName:Z,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};s8={configNotFound(Z,$,Y){return new rY(Z,$,Y)},configLoad(Z,$,Y){return new k$(Z,$,Y)},configValidation(Z,$,Y){return new aY(Z,$,Y)},configMerge(Z,$,Y,X){return new tY(Z,$,Y,X)},envVar(Z,$,Y,X){return new e7(Z,$,Y,X)},fileSystem(Z,$,Y){return new eY(Z,$,Y)},typeGeneration(Z,$,Y){return new ZX(Z,$,Y)},schemaValidation(Z,$,Y){return new x$(Z,$,Y)},browserConfig(Z,$,Y,X){return new $X(Z,$,Y,X)},plugin(Z,$,Y){return new YX(Z,$,Y)}};d5=/^https?:\/\//;G8=new b$("bunfig",{showTags:!0});k7=new HX;M4=V8(v$.cwd(),"config"),w4=V8(v$.cwd(),"src/generated")});import jX from"process";function YZ(Z=f.dialect){return Z==="mysql"||Z==="singlestore"||Z==="vitess"}function QX(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return!1;let $=Object.getPrototypeOf(Z);return $===Object.prototype||$===null}function $0(Z,$,Y=new Set){let X={...Z};Y.add($);for(let J of Object.keys($)){if(KX.has(J))continue;let G=$[J];if(QX(G)&&!Y.has(G)){let U=X[J];X[J]=$0(QX(U)?U:{},G,Y)}else X[J]=G}return Y.delete($),X}function g$(Z){if(Z)return Z;let $=jX.env.DB_DIALECT||jX.env.DB_CONNECTION;if($)return $;return f.dialect||"postgres"}function s(Z){if(f.dialect==="postgres")return`$${Z}`;return"?"}function PZ(Z,$=1){if(Z<=0)return"";if(f.dialect==="postgres"){let Y=`$${$}`;for(let X=1;X<Z;X++)Y+=`, $${$+X}`;return Y}return Z===1?"?":`?${", ?".repeat(Z-1)}`}async function p$(){if(!f$.fileLoaded){f$.fileLoaded=!0;let Z=await AX({name:"query-builder",alias:"qb",defaultConfig:VX}),$={};for(let[Y,X]of Object.entries(Z??{}))if(!f$.explicit.has(Y))$[Y]=X;LX($)}return f}function LX(Z){let $=$0(f,Z),Y=f;for(let X of Object.keys($)){if(KX.has(X))continue;Y[X]=$[X]}}function FX(Z){if(Z.dialect&&b9&&Z.dialect!==b9){let $=`${b9}->${Z.dialect}`;if(!_X.has($))_X.add($),console.warn(`[query-builder] Configuring dialect '${Z.dialect}' overrides the previously configured dialect '${b9}'. 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(Z.dialect)b9=Z.dialect;for(let $ of Object.keys(Z))f$.explicit.add($);LX(Z)}function P4(Z){return Z}var VX,KX,c5,f,u5,f$,b9=null,_X;var qZ=z8(()=>{WX();VX={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}},KX=new Set(["__proto__","constructor","prototype"]);c5=Symbol.for("bun-query-builder.config"),f=globalThis[c5]??=$0({},VX),u5=Symbol.for("bun-query-builder.config-state"),f$=globalThis[u5]??={explicit:new Set,fileLoaded:!1};_X=new Set});function i5(){let Z=f.sqlite?.pragmas;return Array.isArray(Z)?Z:n5}function f9(Z){for(let $ of i5())try{Z.run($)}catch{}}var n5;var d$=z8(()=>{qZ();n5=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:BX}=globalThis.Bun;import{Database as s5}from"bun:sqlite";import{mkdirSync as o5}from"fs";import{dirname as r5}from"path";import p9 from"process";function g9(Z){return Z}function l5(Z){return Z!==null&&typeof Z==="object"?Z:null}function RX(Z,$){if($.length===0||!/\$\d/.test(Z))return{sql:Z,params:$};let Y=[],X="",J=0;for(let G=0;G<Z.length;G++){let U=Z[G];if(U==="'"||U==='"'||U==="`"){let H=a5(Z,G,U);X+=Z.slice(G,H),G=H-1;continue}if(U==="-"&&Z[G+1]==="-"){let H=Z.indexOf(`
62
+ `,G),z=H===-1?Z.length:H;X+=Z.slice(G,z),G=z-1;continue}if(U==="/"&&Z[G+1]==="*"){let H=Z.indexOf("*/",G+2),z=H===-1?Z.length:H+2;X+=Z.slice(G,z),G=z-1;continue}if(U==="$"){let H=/^\d+/.exec(Z.slice(G+1))?.[0];if(H){let z=Number(H);if(J=Math.max(J,z),z>=1&&z<=$.length){Y.push($[z-1]),X+="?",G+=H.length;continue}}}X+=U}if(J>$.length)throw Error(`SQL references $${J} but only ${$.length} value${$.length===1?" was":"s were"} provided`);if(Y.length===0)return{sql:Z,params:$};return{sql:X,params:Y}}function a5(Z,$,Y){for(let X=$+1;X<Z.length;X++){if(Z[X]!==Y)continue;if(Z[X+1]===Y){X++;continue}return X+1}return Z.length}class IX{db;constructor(Z){if(Z!==":memory:"&&!Z.startsWith(":")){let $=r5(Z);if($&&$!==".")o5($,{recursive:!0})}this.db=new s5(Z),f9(this.db)}query(Z,$=[]){let Y=RX(Z,$);return this.db.prepare(Y.sql).all(...Y.params)}run(Z,$=[]){let Y=RX(Z,$);return this.db.prepare(Y.sql).run(...Y.params)}close(){this.db.close()}get database(){return this.db}}function OX(Z){return{__raw:!0,value:Z,toString:()=>Z}}function DX(Z){let $=Z.trimStart();for(;;)if($.startsWith("--")){let Y=$.indexOf(`
63
+ `);$=Y===-1?"":$.slice(Y+1).trimStart()}else if($.startsWith("/*")){let Y=$.indexOf("*/");$=Y===-1?"":$.slice(Y+2).trimStart()}else return $}function t5(Z){let $=[],Y="",X=!1,J=!1,G=!1,U=!1;for(let z=0;z<Z.length;z++){let A=Z[z],W=Z[z+1];if(!X&&!J&&!U&&A==="-"&&W==="-"){G=!0,Y+=A;continue}if(G&&(A===`
64
+ `||A==="\r")){G=!1,Y+=A;continue}if(!X&&!J&&!G&&A==="/"&&W==="*"){U=!0,Y+=A;continue}if(U&&A==="*"&&W==="/"){U=!1,Y+=A+W,z++;continue}if(G||U){Y+=A;continue}if(A==="'"&&!J){if(X&&W==="'"){Y+=A+W,z++;continue}X=!X,Y+=A;continue}if(A==='"'&&!X){J=!J,Y+=A;continue}if(A===";"&&!X&&!J){let Q=DX(Y.trim());if(Q)$.push(Q);Y="";continue}Y+=A}let H=DX(Y.trim());if(H)$.push(H);return $}function EX(Z){let $=new IX(Z);function Y(G,...U){let H=G[0],z=[];for(let A=0;A<U.length;A++){let W=U[A],Q=l5(W);if(Q&&typeof Q.sql==="string"&&Array.isArray(Q.values))H+=Q.sql+(G[A+1]||""),z.push(...Q.values);else if(Q&&(Q.__raw||Q.raw)){let R=Q.raw,O=Q.__raw?Q.value:typeof R==="string"?R:R();H+=O+(G[A+1]||"")}else if(Array.isArray(W)){let R=W.map(()=>"?").join(", ");H+=R+(G[A+1]||""),z.push(...W)}else H+=`?${G[A+1]||""}`,z.push(W)}return{sql:H,values:z,execute:()=>{try{let A=H.trim().toUpperCase();if(A.startsWith("SELECT")||A.startsWith("PRAGMA")||/\bRETURNING\b/.test(A)){let W=$.query(H,g9(z));return Promise.resolve(W)}else{let W=$.run(H,g9(z));return Promise.resolve(W)}}catch(A){return Promise.reject(A)}},raw:()=>H,toString:()=>H,cancel:()=>{}}}function X(G,...U){if(Array.isArray(G)&&"raw"in G)return Y(G,...U);if(typeof G==="string")return OX(G);return Y([""])}X.raw=(G)=>OX(G),X.unsafe=(G,U=[])=>{let H=()=>{try{let z=G.trim().toUpperCase();if(z.startsWith("SELECT")||z.startsWith("PRAGMA")||/\bRETURNING\b/.test(z)){let A=$.query(G,g9(U));return Promise.resolve(A)}else{let A=$.run(G,g9(U));return Promise.resolve(A)}}catch(z){return Promise.reject(z)}};return{sql:G,values:U,execute:H,then:(z,A)=>H().then(z,A),raw:()=>G,toString:()=>G,cancel:()=>{}}},X.close=()=>{return $.close(),Promise.resolve()},X.query=(G,U)=>{try{let H=$.query(G,g9(U||[]));return Promise.resolve(H)}catch(H){return Promise.reject(H)}},X.file=async(G,U)=>{try{let{readFileSync:H}=await import("fs"),z=H(G,"utf-8"),A=t5(z);for(let W of A){let Q=W.trim();if(!Q||Q.startsWith("--"))continue;let R=Q.toUpperCase();if(R.startsWith("SELECT")||R.startsWith("PRAGMA"))$.query(W);else $.run(W)}return Promise.resolve([])}catch(H){return Promise.reject(H)}};let J=0;return X.begin=async(G,U)=>{let H=typeof G==="function"?G:U;if(typeof H!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let z=J>0,A=`qb_sp_${J}`;if(z)$.run(`SAVEPOINT ${A}`);else $.run("BEGIN");J++;try{let W=await H(X);if(J--,z)$.run(`RELEASE SAVEPOINT ${A}`);else $.run("COMMIT");return W}catch(W){J--;try{if(z)$.run(`ROLLBACK TO SAVEPOINT ${A}`),$.run(`RELEASE SAVEPOINT ${A}`);else $.run("ROLLBACK")}catch{}throw W}},X.savepoint=X.begin,X.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},X._wrapper=$,X}function e5(Z){let $=Z.replace(/^(?:sqlite|sqlite3|file):/i,"");if($===Z)return Z;return($.startsWith("///")?$.slice(2):$.startsWith("//")?$.slice(2):$)||":memory:"}function m$(Z=f.database){let $=p9.env.DB_DATABASE||Z?.database||"";return String($).replace(/^['"]|['"]$/g,"")}function Z6(Z,$){if((Z==="postgres"||Z==="mysql"||Z==="singlestore"||Z==="vitess")&&p9.env.DB_CONNECTION===Z){let A=p9.env,W=(A.DB_DATABASE||$.database||"").replace(/^['"]|['"]$/g,""),Q=A.DB_USERNAME||$.username,R=A.DB_PASSWORD??$.password??"",O=A.DB_HOST||$.host||"localhost",N=A.DB_PORT||$.port,_=Z==="postgres"?"postgres":"mysql",F=A.DB_SSL==="true"||A.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${_}://${Q}:${R}@${O}${N?`:${N}`:""}/${W}${F}`}if($.url)return Z==="sqlite"?e5($.url):$.url;let{database:Y,username:X,password:J,host:G="localhost",port:U,ssl:H}=$,z=H||p9.env.DB_SSL==="true"||p9.env.DB_SSL==="1"?"?ssl=true":"";switch(Z){case"postgres":return`postgres://${X}:${J}@${G}${U?`:${U}`:""}/${Y}${z}`;case"mysql":case"singlestore":case"vitess":return`mysql://${X}:${J}@${G}${U?`:${U}`:""}/${Y}${z}`;case"sqlite":if(Y===":memory:")return":memory:";return Y||":memory:";default:throw Error(`Unsupported dialect: ${Z}`)}}function MX(Z){if(!Z)return{};let $={},Y=(X)=>Math.max(0,Math.round(X/1000));if(typeof Z.max==="number"&&Number.isFinite(Z.max))$.max=Z.max;if(typeof Z.idleTimeoutMs==="number"&&Number.isFinite(Z.idleTimeoutMs))$.idleTimeout=Y(Z.idleTimeoutMs);if(typeof Z.acquireTimeoutMs==="number"&&Number.isFinite(Z.acquireTimeoutMs))$.connectionTimeout=Y(Z.acquireTimeoutMs);if(typeof Z.maxLifetimeMs==="number"&&Number.isFinite(Z.maxLifetimeMs))$.maxLifetime=Y(Z.maxLifetimeMs);return $}function $6(){let Z=f.dialect,$=Z6(Z,f.database);try{if(Z==="sqlite")return EX($);let Y=MX(f.database.pool);return Object.keys(Y).length>0?new BX($,Y):new BX($)}catch(Y){if(console.error(`[query-builder] Failed to create database connection for dialect '${Z}': ${Y.message}`),Z==="sqlite")return EX(":memory:");throw Y}}function Y6(){let Z=f.database;return JSON.stringify({dialect:f.dialect,database:Z.database,username:Z.username,password:Z.password,host:Z.host,port:Z.port,url:Z.url,pool:MX(Z.pool)})}function y8(Z=!1){let $=Y6();if(Z||r8!==null&&Y0!==$||!r8){if(r8)wX();r8=$6(),Y0=$}return r8}function X6(){let Z=r8;return r8=null,Y0=null,Z}async function J6(Z){if(!Z||typeof Z.close!=="function")return;await Z.close()}function wX(){J6(X6()).catch(($)=>{console.error(`[query-builder] Failed to close database connection: ${$.message}`)})}async function X0(Z){try{return await Z(y8())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Y=y8(!0);return await Z(Y)}throw $}}function G6(){return new Proxy(function(){},{get(Z,$){let Y=y8(),X=Y[$];if(typeof X==="function")return X.bind(Y);return X},apply(Z,$,Y){return y8()(...Y)}})}var r8=null,Y0=null,e;var h8=z8(()=>{qZ();d$();e=G6()});function R9(Z){return Z==="integer"||Z==="bigint"||Z==="float"||Z==="double"||Z==="decimal"}function CX(Z){if(typeof Z!=="string")return;switch(Z.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 i$(Z){switch(Z){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}var J0=()=>{};function G0(Z){let $=String(Z).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if($.endsWith("y")&&!/[aeou]y$/.test($))return`${$.slice(0,-1)}ies`;if($.endsWith("s")||$.endsWith("x")||$.endsWith("ch")||$.endsWith("sh"))return`${$}es`;return`${$}s`}function b8(Z){return typeof Z?.table==="string"&&Z.table.length>0?Z.table:G0(String(Z?.name??""))}function A6(Z){return Z.endsWith("s")?Z.slice(0,-1):Z}function W6(Z){if(Z.endsWith("ies")&&Z.length>3){let $=Z.slice(0,-3),Y=$[$.length-1];if(Y&&!"aeiou".includes(Y))return`${$}y`}if(Z.endsWith("es")&&Z.length>2){let $=Z.slice(0,-2);if($.endsWith("s")||$.endsWith("x")||$.endsWith("ch")||$.endsWith("sh"))return $}if(Z.endsWith("s")&&!Z.endsWith("ss")&&!Z.endsWith("us")&&!Z.endsWith("is"))return Z.slice(0,-1);return Z}function f8(Z){if(Z==="none")return($)=>$;if(Z==="inflect")return W6;return A6}var g8=()=>{};function e8(Z){if(Z.length===0)return"";let $=[];for(let Y of Z)if(Y.conn==="OR"&&$.length>0)$[$.length-1].push(Y);else $.push([Y]);return $.map((Y,X)=>{let J=Y.map((U)=>U.sql).join(" OR "),G=Y.length>1&&$.length>1?`(${J})`:J;return X===0?G:`${Y[0].conn} ${G}`}).join(" ")}function tZ(Z,$,Y,X){if($.length===0)return Y?"1 = 1":"1 = 0";return`${Z} ${Y?"NOT IN":"IN"} (${X})`}function Q6(Z,$){if($!=="postgres")return Z;let Y="",X=0,J=0;while(J<Z.length){let G=Z[J];if(G==="'"){let U=SX(Z,J,"'");Y+=Z.slice(J,U),J=U;continue}if(G==='"'){let U=SX(Z,J,'"');Y+=Z.slice(J,U),J=U;continue}if(G==="$"){let U=Z.slice(J).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(U){let H=Z.indexOf(U,J+U.length),z=H===-1?Z.length:H+U.length;Y+=Z.slice(J,z),J=z;continue}}if(G==="?"){X++,Y+=`$${X}`,J++;continue}Y+=G,J++}return Y}function SX(Z,$,Y){let X=$+1;while(X<Z.length){if(Z[X]===Y){if(Z[X+1]===Y){X+=2;continue}return X+1}X++}return Z.length}var NX="1 = 0";var s$=()=>{};function D9(Z){if(typeof Z==="number")return{length:Z};return Z}function K0(Z){if(typeof Z==="number")return{max:Z};return Z}function bU(Z){return typeof Z==="function"}function fU(Z){return Z.replace(/[A-Z]/g,($)=>$.toLowerCase())}function Q1(Z,$){if(!$||typeof $.fractionDigits!=="number")return Z;return Number(Z.toFixed($.fractionDigits))}function d8(Z,$={}){if(!Z)return $;return new Proxy(Z,{get(Y,X){if(X in $)return $[X];let J=Y[X];if(J!==void 0)return J;let G=Y[fU(X)];if(bU(G))return G.bind(Y);return}})}function _1(Z){let $=(W)=>{let Q=Array.isArray(W)?W:[],R=Math.floor(Math.random()*Q.length);return Q[R]},Y=()=>Z.string,X=()=>Z.number,J=()=>Z.random,G=d8(Z.string,{alpha:(W)=>Y()?.alpha?.(D9(W)),alphanumeric:(W)=>Y()?.alphanumeric?.(D9(W)),numeric:(W)=>Y()?.numeric?.(D9(W)),sample:(W)=>Y()?.sample?.(D9(W)),hexadecimal:(W)=>Y()?.hexadecimal?.(D9(W))}),U=d8(Z.number,{int:(W)=>X()?.int?.(K0(W)),float:(W)=>{let Q=K0(W);return Q1(Number(X()?.float?.(Q)??0),Q)}}),H=d8(Z.helpers,{arrayElement:$,arrayElements:(W,Q)=>{let R=[...Array.isArray(W)?W:[]],O=typeof Q==="number"?Q:Math.max(1,Math.floor(Math.random()*R.length));for(let N=R.length-1;N>0;N-=1){let _=Math.floor(Math.random()*(N+1));[R[N],R[_]]=[R[_],R[N]]}return R.slice(0,Math.min(O,R.length))},shuffle:(W)=>{let Q=[...Array.isArray(W)?W:[]];for(let R=Q.length-1;R>0;R-=1){let O=Math.floor(Math.random()*(R+1));[Q[R],Q[O]]=[Q[O],Q[R]]}return Q},maybe:(W,Q)=>{let R=typeof Q?.probability==="number"?Q.probability:0.5;return Math.random()<R?W():void 0},slugify:(W)=>String(W??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),A={string:G,number:U,helpers:H,datatype:{boolean:(W)=>{let Q=typeof W==="number"?W:W?.probability;if(typeof Q==="number")return Math.random()<Q;return Boolean(J()?.boolean?.())},number:(W)=>Number(X()?.int?.(K0(W))??0),float:(W)=>Q1(Number(X()?.float?.(W)??0),W),uuid:()=>crypto.randomUUID(),string:(W)=>String(Y()?.alphanumeric?.({length:W??10})??""),hexadecimal:(W)=>String(Y()?.hexadecimal?.(D9(W))??""),array:(W)=>Array.from({length:W??3},()=>Y()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:Y()?.alphanumeric?.({length:8})})},location:d8(Z.address),address:d8(Z.address),vehicle:d8(Z.vehicle,{vrm:()=>Z.vehicle?.registration?.()}),company:d8(Z.company,{catchPhrase:()=>Z.company?.catchphrase?.(),buzzPhrase:()=>Z.company?.bs?.()??Z.company?.buzzword?.()})};return new Proxy(Z,{get(W,Q){if(Q in A)return A[Q];let R=W[Q];if(R&&typeof R==="object")return d8(R);return R}})}var L0=()=>{};function J7(Z){if(typeof Z==="string")return{model:Z};if(Z&&typeof Z==="object"&&typeof Z.model==="string"){let $=Z;return{model:$.model,foreignKey:$.foreignKey,onDelete:$.onDelete}}return null}function E9(Z){if(!Z)return[];return(Array.isArray(Z)?Z:typeof Z==="object"?Object.values(Z):[]).map(J7).filter((Y)=>Y!==null)}var G7=()=>{};import{Database as D0}from"bun:sqlite";function X9(){let Z=new Date().toISOString();return YZ(f.dialect)?Z.slice(0,19).replace("T"," "):Z}function S8(Z,$){if(typeof Z!=="string"||Z.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof Z}`);if(Z.length>64)throw TypeError(`[bun-query-builder] ${$}: identifier '${Z}' exceeds 64 chars`);if(!D1.test(Z))throw TypeError(`[bun-query-builder] ${$}: identifier '${Z}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function E1(Z,$){if(typeof Z!=="string"||Z.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof Z}`);let Y=Z.split(".");if(Y.length>2||Y.some((X)=>X.length===0||X.length>64||!D1.test(X)))throw TypeError(`[bun-query-builder] ${$}: invalid ORDER BY column '${Z}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function pU(Z,$){I0.set(Z,$),I9.clear()}function I1(){I0.clear(),I9.clear()}function eZ(Z){if(!U7)try{U7=(s9(),gU(P1)).getModel}catch{U7=()=>{return}}return U7(Z)??I0.get(Z)}function V1(Z){let $=z7.get(Z);if($!==void 0)return $;let Y=0,X=Z.replace(/\?/g,()=>`$${++Y}`);if(z7.size>=dU)z7.clear();return z7.set(Z,X),X}function K1(Z){if(Z==null)return 0;if(typeof Z.affectedRows==="number")return Z.affectedRows;if(typeof Z.count==="number")return Z.count;if(Array.isArray(Z))return Z.length;return 0}function L1(Z){if(Z==null||typeof Z!=="object")return null;if("insertId"in Z&&Z.insertId!=null)return Z.insertId;if("lastInsertRowid"in Z&&Z.lastInsertRowid!=null)return Z.lastInsertRowid;return null}class E0{sqliteDb;dialect="sqlite";constructor(Z){this.sqliteDb=Z}all(Z,$){return Promise.resolve(this.sqliteDb.query(Z).all(...$))}get(Z,$){return Promise.resolve(this.sqliteDb.query(Z).get(...$)??void 0)}run(Z,$){let Y=this.sqliteDb.run(Z,$);return Promise.resolve({changes:Y.changes,lastInsertId:Y.lastInsertRowid})}insert(Z,$){return this.run(Z,$)}}class M1{dialect;constructor(Z){this.dialect=Z}conn(){return y8()}text(Z){return this.dialect==="postgres"?V1(Z):Z}async all(Z,$){let Y=await this.conn().unsafe(this.text(Z),$);return Array.isArray(Y)?Y:[]}async get(Z,$){let Y=await this.conn().unsafe(this.text(Z),$);if(Array.isArray(Y))return Y[0]??void 0;return Y??void 0}async run(Z,$){let Y=await this.conn().unsafe(this.text(Z),$);return{changes:K1(Y),lastInsertId:L1(Y)}}async insert(Z,$,Y){if(this.dialect==="postgres"){let G=await this.conn().unsafe(`${V1(Z)} RETURNING ${Y}`,$),U=Array.isArray(G)?G[0]:G;return{changes:1,lastInsertId:U?U[Y]??null:null}}let X=await this.conn().unsafe(Z,$),J=L1(X);if(J==null){let G=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);J=(Array.isArray(G)?G[0]:G)?.id??null}return{changes:K1(X)||1,lastInsertId:J}}}function sW(Z){if(Z.database instanceof D0)Y9=Z.database;else Y9=new D0(Z.database||":memory:",{create:!0}),f9(Y9);N8=null,l9=null}function RZ(){if(Y9){if(!N8||l9!==Y9)N8=new E0(Y9),l9=Y9,F0="sqlite",B0=null;return N8}let Z=f.dialect,$=f.database?.database??null;if(N8&&l9===null&&F0===Z&&B0===$)return N8;if(l9=null,F0=Z,B0=$,Z==="sqlite"){let Y=new D0($||":memory:",{create:!0});f9(Y),N8=new E0(Y)}else N8=new M1(Z);return N8}function oW(){let Z=RZ();if(Z.sqliteDb)return Z.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${Z.dialect}'. Use the async model API instead.`)}function M9(Z){let $=Z.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function J9(Z){let $=Z.traits;return Boolean($?.useTimestamps||$?.timestampable)}function mU(Z){let $=F1.get(Z);if($)return $;let Y=new Set,X=Z.belongsToMany;if(X){if(Array.isArray(X)){for(let J of X)if(typeof J==="string")Y.add(J.toLowerCase());else if(J&&typeof J==="object"&&J.model)Y.add(J.model.toLowerCase())}else if(typeof X==="object")for(let J of Object.keys(X))Y.add(J)}return F1.set(Z,Y),Y}function w1(Z){let $={};for(let[Y,X]of Object.entries(Z))$[OZ(Y)]=X;return $}function cU(Z){for(let $ in Z)if(OZ($)!==$)return w1(Z);return Z}function uU(Z,$){if(Z[$])return Z[$];let Y=OZ($);if(Z[Y])return Z[Y];for(let X of Object.keys(Z))if(OZ(X)===Y)return Z[X];return}class rZ{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor(Z,$={}){this._definition=Z,this._attributes=cU({...$}),this._original=null;let Y=mU(Z);if(Y.size===0)return;let X=this;return new Proxy(this,{get(J,G,U){if(typeof G==="string"&&Y.has(G)&&!(G in J))return()=>{let H=C1(Z,G);if(!H||H.type!=="belongsToMany")throw Error(`[orm] relation '${G}' did not resolve to a belongsToMany on '${Z.name}'`);let z=eZ(H.relatedModelName),A=z?.getDefinition?.()||z?.definition;if(!A)throw Error(`[orm] related model '${H.relatedModelName}' is not registered`);return new S1(X,Z,H,A)};return Reflect.get(J,G,U)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(Z){let $=this._definition.get?.[Z];if($)try{let Y=$(this._attributes);if(Y!==void 0)return Y}catch{}return this._attributes[OZ(Z)]}getAttribute(Z){return this._attributes[OZ(Z)]}getAttributes(){return{...this._attributes}}set(Z,$){if(this._original===null)this._original={...this._attributes};this._attributes[OZ(Z)]=$}only(Z){let $={};for(let Y of Z)$[Y]=this._attributes[OZ(Y)];return $}except(Z){let $=new Set(Z.map((X)=>OZ(X))),Y={};for(let X of Object.keys(this._attributes))if(!$.has(X))Y[X]=this._attributes[X];return Y}getRelation(Z){return this._relations[Z]}setRelation(Z,$){this._relations[Z]=$}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let Z=this._definition.primaryKey||"id";return this._attributes[Z]}isDirty(Z){if(this._original===null)return!1;if(Z){let $=OZ(Z);return this._attributes[$]!==this._original[$]}return Object.keys(this._attributes).some(($)=>this._attributes[$]!==this._original[$])}isClean(Z){return!this.isDirty(Z)}getOriginal(Z){return this.getOriginalAttributes()[OZ(Z)]}getChanges(){if(this._original===null)return{};let Z={};for(let $ of Object.keys(this._attributes))if(this._attributes[$]!==this._original[$])Z[$]=this._attributes[$];return Z}fill(Z){let $=this._definition.attributes;for(let[Y,X]of Object.entries(Z)){let J=uU($,Y),G=!J&&OZ(Y).endsWith("_id");if(J?.fillable&&!J?.guarded||G){if(this._original===null)this._original={...this._attributes};this._attributes[OZ(Y)]=X}}return this}forceFill(Z){if(this._original===null)this._original={...this._attributes};let $=w1(Z);Object.assign(this._attributes,$);for(let Y of Object.keys($))this._forced.add(Y);return this}async save(){let Z=RZ(),$=this._definition.primaryKey||"id",Y=this._definition.hooks,X=this._definition.set||{};for(let[J,G]of Object.entries(X))if(this.isDirty(J))this._attributes[OZ(J)]=G(this._attributes);if(this._attributes[$]){await Y?.beforeUpdate?.(this,this.getChanges());let J=this.getChanges(),G=Object.keys(J);if(G.length>0){let U=G.map((z)=>`${z} = ?`).join(", "),H=[...Object.values(J),this._attributes[$]];if(J9(this._definition)){let z=X9();await Z.run(`UPDATE ${this._definition.table} SET ${U}, updated_at = ? WHERE ${$} = ?`,[...Object.values(J),z,this._attributes[$]])}else await Z.run(`UPDATE ${this._definition.table} SET ${U} WHERE ${$} = ?`,H)}await Y?.afterUpdate?.(this)}else{let J=this._definition.attributes,G={};for(let[A,W]of Object.entries(J)){if(W.guarded&&!this._forced.has(OZ(A)))continue;let Q=OZ(A);if(this._attributes[Q]!==void 0)G[Q]=this._attributes[Q]}for(let A of Object.keys(this._attributes))if(A.endsWith("_id")&&A!==$&&!(A in G))G[A]=this._attributes[A];if(J9(this._definition)){let A=X9();G.created_at=A,G.updated_at=A}if(this._definition.traits?.useUuid&&!G.uuid)G.uuid=crypto.randomUUID();await Y?.beforeCreate?.(G);let U=Object.keys(G),H=U.map(()=>"?").join(", "),z=await Z.insert(`INSERT INTO ${this._definition.table} (${U.join(", ")}) VALUES (${H})`,Object.values(G),$);for(let[A,W]of Object.entries(G))this._attributes[A]=W;if(z.lastInsertId!=null)this._attributes[$]=z.lastInsertId;await Y?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(Z){return this.fill(Z),this.save()}async fresh(){let Z=RZ(),$=this._definition.primaryKey||"id",Y=this._attributes[$];if(Y==null)return null;let X=await Z.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Y]);if(!X)return null;return new rZ(this._definition,X)}async delete(){let Z=RZ(),$=this._definition.primaryKey||"id",Y=this._attributes[$],X=this._definition.hooks;if(!Y)throw Error("Cannot delete a model without a primary key");if(await X?.beforeDelete?.(this),M9(this._definition)){let J=X9();await Z.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${$} = ?`,[J,Y]),this._attributes[m8]=J}else await Z.run(`DELETE FROM ${this._definition.table} WHERE ${$} = ?`,[Y]);return await X?.afterDelete?.(this),!0}async restore(){if(!M9(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let Z=this._definition.primaryKey||"id",$=this._attributes[Z];if(!$)throw Error("Cannot restore a model without a primary key");return await RZ().run(`UPDATE ${this._definition.table} SET ${m8} = ? WHERE ${Z} = ?`,[null,$]),this._attributes[m8]=null,this._original=null,this}trashed(){return this._attributes[m8]!=null}async refresh(){let Z=RZ(),$=this._definition.primaryKey||"id",Y=this._attributes[$];if(!Y)throw Error("Cannot refresh a model without a primary key");let X=await Z.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Y]);if(!X)return null;return this._attributes=X,this._original=null,this}replicate(){let Z=this._definition.primaryKey||"id",$={...this._attributes};return delete $[Z],delete $.uuid,delete $.created_at,delete $.updated_at,new rZ(this._definition,$)}toArray(){let Z={...this._attributes};for(let[$,Y]of Object.entries(this._relations))if(Array.isArray(Y))Z[$]=Y.map((X)=>X.toArray());else if(Y)Z[$]=Y.toArray();else Z[$]=null;return Z}toJSON(){let Z=new Set;for(let[Y,X]of Object.entries(this._definition.attributes))if(X.hidden)Z.add(Y);let $={};for(let[Y,X]of Object.entries(this._attributes))if(!Z.has(Y))$[Y]=X;for(let[Y,X]of Object.entries(this._relations))if(Array.isArray(X))$[Y]=X.map((J)=>J.toJSON());else if(X)$[Y]=X.toJSON();else $[Y]=null;return $}}function j8(Z){return OZ(Z)}function OZ(Z){let $=B1.get(Z);if($!==void 0)return $;return $=Z.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),B1.set(Z,$),$}function $9(Z){let $=R1.get(Z);if($!==void 0)return $;return $=G0(Z),R1.set(Z,$),$}function O1(Z,$){let Y=Z[$];if(!Y)return[];if(Array.isArray(Y))return Y.map((X)=>typeof X==="string"?X:String(X?.model??"")).filter(Boolean);if(typeof Y==="object")return Object.keys(Y);if(typeof Y==="string")return[Y];return[]}function lU(Z,$){let Y=Z.name??Z.table??"model",J=iU.filter((U)=>O1(Z,U).some((H)=>H.toLowerCase()===$.toLowerCase())).filter((U)=>!H7.includes(U));if(J.length>0)return`[orm] '${Y}' declares '${$}' as ${J.join("/")}, which eager loading does not support yet. Supported kinds: ${H7.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let G=H7.flatMap((U)=>O1(Z,U));return G.length>0?`[orm] '${Y}' has no relation '${$}'. Available: ${G.join(", ")}.`:`[orm] '${Y}' has no relation '${$}' \u2014 it declares no relations at all.`}function C1(Z,$){let{name:Y,table:X}=Z,J=Z.primaryKey||"id";function G(_){if(!_)return null;if(Array.isArray(_)){for(let F of _){let L=typeof F==="string"?F:F?.model||"";if(L&&L.toLowerCase()===$.toLowerCase())return L}return null}if(typeof _==="object"){for(let[F,L]of Object.entries(_))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof L==="string"?L:L?.model||L?.target||F}return null}function U(){let _=Z.belongsTo;if(!_)return null;let F=$.toLowerCase(),L=(K)=>{if(typeof K==="string")return{model:K};if(K&&typeof K==="object"&&typeof K.model==="string")return{model:K.model,foreignKey:K.foreignKey};return null};if(Array.isArray(_)){for(let K of _){let I=L(K);if(I&&I.model.toLowerCase()===F)return I}return null}if(typeof _==="object"){for(let[K,I]of Object.entries(_))if(K===$||K.toLowerCase()===F)return L(I)}return null}function H(){let _=Z.belongsToMany;if(!_)return null;if(Array.isArray(_)){for(let F of _)if(typeof F==="string"){if(F.toLowerCase()===$.toLowerCase())return{entry:F}}else if(F&&typeof F==="object"&&F.model){if(F.model.toLowerCase()===$.toLowerCase())return{entry:F}}return null}if(typeof _==="object"){for(let[F,L]of Object.entries(_))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:L}}return null}let z=G(Z.hasMany);if(z){let F=eZ(z)?.getTable?.()||$9(z),L=OZ(Y)+"_id";return{type:"hasMany",relatedModelName:z,relatedTable:F,foreignKey:L,localKey:J}}let A=G(Z.hasOne);if(A){let F=eZ(A)?.getTable?.()||$9(A),L=OZ(Y)+"_id";return{type:"hasOne",relatedModelName:A,relatedTable:F,foreignKey:L,localKey:J}}let W=U();if(W){let _=W.model,F=eZ(_),L=F?.getTable?.()||$9(_),K=F?.getDefinition?.()?.primaryKey||"id",I=W.foreignKey||`${OZ(_)}_id`;return{type:"belongsTo",relatedModelName:_,relatedTable:L,foreignKey:I,localKey:K}}let Q=H();if(Q){let _=typeof Q.entry==="object",F=_?Q.entry.model:Q.entry,K=eZ(F)?.getTable?.()||$9(F),I=_?Q.entry:null,B,v;if(I?.table)B=I.table;else if(I?.through){v=I.through;let M=eZ(I.through);if(!M)throw Error(`[orm] belongsToMany relation '${$}' on '${Y}' references unknown through model '${I.through}'. Make sure '${I.through}' is registered.`);B=M.getTable?.()||M.getDefinition?.()?.table||$9(I.through)}else{let M=i9(X),q=i9(K);B=[M,q].sort().join("_")}let P=I?.foreignKey||`${i9(X)}_id`,T=I?.relatedKey||`${i9(K)}_id`,w=[];if(I?.pivot?.columns)for(let M of Object.keys(I.pivot.columns))w.push(M);if(v){let M=eZ(v),q=M?.getDefinition?.()||M?.definition,C=q?.attributes??{},y=q?.primaryKey??"id";for(let c of Object.keys(C)){if(c===P||c===T||c===y)continue;if(!w.includes(c))w.push(c)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:K,foreignKey:P,localKey:J,pivotTable:B,pivotFkParent:P,pivotFkRelated:T,pivotColumns:w,pivotModelName:v,pivotTimestamps:Boolean(I?.pivot?.timestamps)}}let R=(_,F)=>{if(!_||typeof _!=="object"||Array.isArray(_))return null;let L=_[$]??_[Object.keys(_).find((q)=>q.toLowerCase()===$.toLowerCase())??""];if(!L||typeof L!=="object")return null;let{through:K,target:I}=L;if(!K||!I)return null;let B=eZ(K),v=B?.getDefinition?.()||B?.definition,P=B?.getTable?.()||v?.table||$9(K),T=v?.primaryKey||"id",M=eZ(I)?.getTable?.()||$9(I);return{type:F,relatedModelName:I,relatedTable:M,foreignKey:`${OZ(Y)}_id`,localKey:J,throughTable:P,throughForeignKey:`${OZ(Y)}_id`,throughLocalKey:T,targetForeignKey:`${i9(P)}_id`}},O=R(Z.hasManyThrough,"hasManyThrough");if(O)return O;let N=R(Z.hasOneThrough,"hasOneThrough");if(N)return N;return null}function O0(Z,$){let Y=new Set;for(let X of Z){let J=X.get($);if(J!=null)Y.add(J)}return[...Y]}function i9(Z){return f8(f.relations?.singularizeStrategy)(Z)}class S1{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(Z,$,Y,X){this._parent=Z,this._parentDef=$,this._resolved=Y,this._relatedDef=X}get parentId(){let Z=this._parentDef.primaryKey||"id";return this._parent.get(Z)}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(Z,$,Y){if(Y===void 0)this._wheres.push({sql:`${this.relatedTable}.${Z} = ?`,params:[$]});else this._wheres.push({sql:`${this.relatedTable}.${Z} ${String($)} ?`,params:[Y]});return this}wherePivot(Z,$,Y){if(Y===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${Z} = ?`,params:[$]});else this._pivotWheres.push({sql:`${this.pivotTable}.${Z} ${String($)} ?`,params:[Y]});return this}wherePivotIn(Z,$){if(!$.length)return this;let Y=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} IN (${Y})`,params:[...$]}),this}wherePivotNotIn(Z,$){if(!$.length)return this;let Y=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} NOT IN (${Y})`,params:[...$]}),this}wherePivotNull(Z){return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} IS NULL`,params:[]}),this}wherePivotNotNull(Z){return this._pivotWheres.push({sql:`${this.pivotTable}.${Z} IS NOT NULL`,params:[]}),this}orderBy(Z,$="asc"){if(E1(Z,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push(`${Z} ${$.toUpperCase()}`),this}limit(Z){if(!Number.isFinite(Z)||Z<0||!Number.isInteger(Z))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${Z}`);return this._limit=Z,this}offset(Z){if(!Number.isFinite(Z)||Z<0||!Number.isInteger(Z))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${Z}`);return this._offset=Z,this}relatedSelectColumns(){let Z=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),$=this._relatedDef.traits;if($?.useTimestamps||$?.timestampable)Z.add("created_at"),Z.add("updated_at");if($?.useSoftDeletes||$?.softDeletable)Z.add("deleted_at");if($?.useUuid)Z.add("uuid");return[...Z]}buildSelect(){let Z=[],Y=`SELECT ${this.relatedSelectColumns().map((X)=>`${this.relatedTable}.${X} AS ${R0}${X}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;Y+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,Y+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,Z.push(this.parentId);for(let X of this._pivotWheres)Y+=` AND ${X.sql}`,Z.push(...X.params);for(let X of this._wheres)Y+=` AND ${X.sql}`,Z.push(...X.params);if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return{sql:Y,params:Z}}hydrateRows(Z){let $=this.fkParent,Y=this.fkRelated;return Z.map((X)=>{let J={},G={};for(let[H,z]of Object.entries(X))if(H.startsWith(R0))J[H.slice(R0.length)]=z;else if(H!==$&&H!==Y)G[H]=z;let U=new rZ(this._relatedDef,J);return U.pivot=G,U})}async get(){let Z=RZ(),{sql:$,params:Y}=this.buildSelect(),X=await Z.all($,Y);return this.hydrateRows(X)}async first(){return this._limit=1,(await this.get())[0]}async count(){let Z=RZ(),$=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Y=[this.parentId];for(let J of this._pivotWheres)$+=` AND ${J.sql}`,Y.push(...J.params);let X=await Z.get($,Y);return Number(X?.count??0)}async exists(){return await this.count()>0}now(){return X9()}async attach(Z,$={}){let Y=RZ(),X=Array.isArray(Z)?Z:[Z];if(X.length===0)return 0;let J=this._resolved.pivotTimestamps?this.now():null,G=0;for(let U of X){let H={[this.fkParent]:this.parentId,[this.fkRelated]:U,...$};if(J){if(H.created_at===void 0)H.created_at=J;if(H.updated_at===void 0)H.updated_at=J}let z=Object.keys(H),A=z.map(()=>"?").join(", "),W=`INSERT INTO ${this.pivotTable} (${z.join(", ")}) VALUES (${A})`,Q=z.map((R)=>H[R]);await Y.run(W,Q),G++}return G}async detach(Z){let $=RZ(),Y=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,X=[this.parentId];if(Z!==void 0&&Z!==null){let J=Array.isArray(Z)?Z:[Z];if(J.length===0)return 0;let G=J.map(()=>"?").join(", ");Y+=` AND ${this.fkRelated} IN (${G})`,X.push(...J)}return(await $.run(Y,X)).changes}async updateExistingPivot(Z,$){let Y=RZ(),X={...$};if(this._resolved.pivotTimestamps&&X.updated_at===void 0)X.updated_at=this.now();let J=Object.keys(X);if(J.length===0)return 0;let G=J.map((z)=>`${z} = ?`).join(", "),U=`UPDATE ${this.pivotTable} SET ${G} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,H=[...J.map((z)=>X[z]),this.parentId,Z];return(await Y.run(U,H)).changes}async sync(Z){let $=RZ(),Y=new Map;for(let A of Z)if(A!=null&&typeof A==="object"&&"id"in A){let{id:W,...Q}=A;Y.set(W,Q)}else Y.set(A,{});let X=await $.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),J=new Set(X.map((A)=>A[this.fkRelated])),G=[],U=[],H=[],z=[...J].filter((A)=>!Y.has(A));if(z.length>0)await this.detach(z),U.push(...z);for(let[A,W]of Y)if(!J.has(A))await this.attach(A,W),G.push(A);else if(Object.keys(W).length>0)await this.updateExistingPivot(A,W),H.push(A);return{attached:G,detached:U,updated:H}}async toggle(Z){let $=RZ(),Y=Array.isArray(Z)?Z:[Z];if(Y.length===0)return{attached:[],detached:[]};let X=Y.map(()=>"?").join(", "),J=await $.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${X})`,[this.parentId,...Y]),G=new Set(J.map((z)=>z[this.fkRelated])),U=Y.filter((z)=>!G.has(z)),H=Y.filter((z)=>G.has(z));if(U.length>0)await this.attach(U);if(H.length>0)await this.detach(H);return{attached:U,detached:H}}}class HZ{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(Z){this._definition=Z}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(Z,$,Y){if(Y===void 0)this._wheres.push({column:Z,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:Z,operator:$,value:Y,boolean:"and"});return this}orWhere(Z,$,Y){if(Y===void 0)this._wheres.push({column:Z,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:Z,operator:$,value:Y,boolean:"or"});return this}whereIn(Z,$){return this._wheres.push({column:Z,operator:"in",value:$,boolean:"and"}),this}orWhereIn(Z,$){return this._wheres.push({column:Z,operator:"in",value:$,boolean:"or"}),this}whereNotIn(Z,$){return this._wheres.push({column:Z,operator:"not in",value:$,boolean:"and"}),this}orWhereNotIn(Z,$){return this._wheres.push({column:Z,operator:"not in",value:$,boolean:"or"}),this}whereNull(Z){return S8(Z,"whereNull(column)"),this._wheres.push({column:Z,operator:"=",value:null,boolean:"and"}),this}orWhereNull(Z){return S8(Z,"orWhereNull(column)"),this._wheres.push({column:Z,operator:"=",value:null,boolean:"or"}),this}whereNotNull(Z){return S8(Z,"whereNotNull(column)"),this._wheres.push({column:Z,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(Z){return S8(Z,"orWhereNotNull(column)"),this._wheres.push({column:Z,operator:"!=",value:null,boolean:"or"}),this}whereLike(Z,$){return this._wheres.push({column:Z,operator:"like",value:$,boolean:"and"}),this}orWhereLike(Z,$){return this._wheres.push({column:Z,operator:"like",value:$,boolean:"or"}),this}whereNotLike(Z,$){return this._wheres.push({column:Z,operator:"not like",value:$,boolean:"and"}),this}orWhereNotLike(Z,$){return this._wheres.push({column:Z,operator:"not like",value:$,boolean:"or"}),this}whereRaw(Z,...$){return this._wheres.push({raw:Z,rawParams:$,boolean:"and"}),this}orWhereRaw(Z,...$){return this._wheres.push({raw:Z,rawParams:$,boolean:"or"}),this}whereGroup(Z){return this._addGroup("and",Z)}orWhereGroup(Z){return this._addGroup("or",Z)}_addGroup(Z,$){let Y=new HZ(this._definition);if($(Y),Y._wheres.length===0)return this;let X=[],J=Y.buildWhereClauses(X);if(!J)return this;return this._wheres.push({raw:`(${J})`,rawParams:X,boolean:Z}),this}whereBetween(Z,$){return S8(Z,"whereBetween(column)"),this._wheres.push({column:Z,operator:">=",value:$[0],boolean:"and"}),this._wheres.push({column:Z,operator:"<=",value:$[1],boolean:"and"}),this}whereNotBetween(Z,$){S8(Z,"whereNotBetween(column)");let Y=j8(Z);return this._wheres.push({raw:`(${Y} < ? OR ${Y} > ?)`,rawParams:[$[0],$[1]],boolean:"and"}),this}when(Z,$){if(Z)return $(this);return this}orderBy(Z,$="asc"){if(E1(Z,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push({column:Z,direction:$}),this}orderByDesc(Z){return this.orderBy(Z,"desc")}orderByAsc(Z){return this.orderBy(Z,"asc")}limit(Z){return this._limit=Z,this}take(Z){return this.limit(Z)}offset(Z){return this._offset=Z,this}skip(Z){return this.offset(Z)}select(...Z){return this._select=Z,this}with(...Z){for(let $ of Z)if(!this._withRelations.includes($))this._withRelations.push($);return this}getWithRelations(){return this._withRelations}buildWhereClauses(Z){let $=[];for(let Y of this._wheres){let X;if(Y.raw){if(X=Y.raw,Y.rawParams&&Y.rawParams.length>0)Z.push(...Y.rawParams)}else if(Y.value===null){let J=j8(Y.column);X=Y.operator==="="?`${J} IS NULL`:`${J} IS NOT NULL`}else if(Y.operator==="in"||Y.operator==="not in"){let J=Y.value;X=tZ(j8(Y.column),J,Y.operator==="not in",J.map(()=>"?").join(", ")),Z.push(...J)}else X=`${j8(Y.column)} ${Y.operator} ?`,Z.push(Y.value);$.push({conn:Y.boolean==="or"?"OR":"AND",sql:X})}return e8($)}softDeleteClause(){if(this._trashed==="include"||!M9(this._definition))return"";return this._trashed==="only"?`${m8} IS NOT NULL`:`${m8} IS NULL`}assertNoUnappliedClauses(Z){let $=[];if(this._limit!==void 0)$.push("limit()");if(this._offset!==void 0)$.push("offset()");if(this._orderBy.length>0)$.push("orderBy()");if($.length>0)throw TypeError(`[orm] ${Z}() cannot apply ${$.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(Z){let $=this._wheres.length>0?this.buildWhereClauses(Z):"",Y=this.softDeleteClause();if($&&Y)return`(${$}) AND ${Y}`;return $||Y}buildQuery(){let Z=[],Y=`SELECT ${this._select.map((J)=>J==="*"?J:j8(J)).join(", ")} FROM ${this._definition.table}`,X=this.composeWhere(Z);if(X)Y+=` WHERE ${X}`;if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.map((J)=>`${j8(J.column)} ${J.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return{sql:Y,params:Z}}toSql(){return this.buildQuery()}async eagerLoadRelations(Z){if(Z.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map(($)=>this.eagerLoadRelation($,Z)))}async eagerLoadRelation(Z,$){let Y=RZ(),X=this._definition.primaryKey||"id",J=`${this._definition.name}:${Z}`,G=I9.get(J);if(G===void 0){if(G=C1(this._definition,Z),I9.size>=nU)I9.clear();I9.set(J,G)}if(!G)throw Error(lU(this._definition,Z));if(G.type==="hasMany"||G.type==="hasOne"){let U=O0($,X);if(U.length===0)return;let H=U.map(()=>"?").join(", "),z=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.foreignKey} IN (${H})`,U),A=eZ(G.relatedModelName),W=A?.getDefinition?.()||A?.definition||this._definition;if(G.type==="hasMany"){let Q=new Map;for(let R of z){let O=R[G.foreignKey];if(!Q.has(O))Q.set(O,[]);Q.get(O).push(R)}for(let R of $){let O=Q.get(R.get(X))||[];R.setRelation(Z,O.map((N)=>new rZ(W,N)))}}else{let Q=new Map;for(let R of z){let O=R[G.foreignKey];if(!Q.has(O))Q.set(O,R)}for(let R of $){let O=Q.get(R.get(X));R.setRelation(Z,O?new rZ(W,O):null)}}}if(G.type==="belongsTo"){let U=new Set;for(let O of $){let N=O._attributes[G.foreignKey];if(N!=null)U.add(N)}let H=[...U];if(H.length===0)return;let z=H.map(()=>"?").join(", "),A=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.localKey} IN (${z})`,H),W=eZ(G.relatedModelName),Q=W?.getDefinition?.()||W?.definition||this._definition,R=new Map;for(let O of A)R.set(O[G.localKey],O);for(let O of $){let N=O._attributes[G.foreignKey],_=R.get(N);O.setRelation(Z,_?new rZ(Q,_):null)}}if(G.type==="belongsToMany"){let U=O0($,X);if(U.length===0)return;if(!G.pivotTable||!G.pivotFkParent||!G.pivotFkRelated)return;let H=U.map(()=>"?").join(", "),z=await Y.all(`SELECT * FROM ${G.pivotTable} WHERE ${G.pivotFkParent} IN (${H})`,U);if(z.length===0){for(let K of $)K.setRelation(Z,[]);return}let A=new Set;for(let K of z){let I=K[G.pivotFkRelated];if(I!=null)A.add(I)}let W=[...A],Q=eZ(G.relatedModelName),R=Q?.getDefinition?.()||Q?.definition||this._definition,O=R?.primaryKey||"id",N=[];if(W.length>0){let K=W.map(()=>"?").join(", ");N=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${O} IN (${K})`,W)}let _=new Map;for(let K of N)_.set(K[O],K);let F=new Map;for(let K of z){let I=K[G.pivotFkParent];if(!F.has(I))F.set(I,[]);F.get(I).push(K)}let L=new Set([G.pivotFkParent,G.pivotFkRelated]);for(let K of $){let I=K.get(X),v=(F.get(I)||[]).map((P)=>{let T=_.get(P[G.pivotFkRelated]);if(!T)return null;let w=new rZ(R,T),M={};for(let[q,C]of Object.entries(P))if(!L.has(q))M[q]=C;return w.pivot=M,w}).filter((P)=>P!==null);K.setRelation(Z,v)}}if(G.type==="hasManyThrough"||G.type==="hasOneThrough"){let U=O0($,X);if(U.length===0)return;let H=G.throughLocalKey||"id",z=U.map(()=>"?").join(", "),A=await Y.all(`SELECT ${H}, ${G.throughForeignKey} FROM ${G.throughTable} WHERE ${G.throughForeignKey} IN (${z})`,U);if(A.length===0){for(let L of $)L.setRelation(Z,G.type==="hasManyThrough"?[]:null);return}let W=new Map;for(let L of A)W.set(L[H],L[G.throughForeignKey]);let Q=[...new Set(A.map((L)=>L[H]))],R=Q.map(()=>"?").join(", "),O=await Y.all(`SELECT * FROM ${G.relatedTable} WHERE ${G.targetForeignKey} IN (${R})`,Q),N=eZ(G.relatedModelName),_=N?.getDefinition?.()||N?.definition||this._definition,F=new Map;for(let L of O){let K=W.get(L[G.targetForeignKey]);if(K==null)continue;if(!F.has(K))F.set(K,[]);F.get(K).push(new rZ(_,L))}for(let L of $){let K=F.get(L.get(X))||[];L.setRelation(Z,G.type==="hasManyThrough"?K:K[0]??null)}}}async get(){let Z=RZ(),{sql:$,params:Y}=this.buildQuery(),J=(await Z.all($,Y)).map((G)=>new rZ(this._definition,G));if(this._withRelations.length>0)await this.eagerLoadRelations(J);return J}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let Z=await this.first();if(!Z)throw Error(`No ${this._definition.name} found`);return Z}async last(){let Z=this._definition.primaryKey||"id";return this._orderBy=[{column:Z,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let Z=RZ(),$=[],Y=`SELECT COUNT(*) as count FROM ${this._definition.table}`,X=this.composeWhere($);if(X)Y+=` WHERE ${X}`;let J=await Z.get(Y,$);return Number(J?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let Z=await this.get();if(Z.length===0)throw Error(`No ${this._definition.name} found`);if(Z.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return Z[0]}async increment(Z,$=1){S8(Z,"increment(column)"),this.assertNoUnappliedClauses("increment");let Y=RZ(),X=[$],J=j8(Z),G=`UPDATE ${this._definition.table} SET ${J} = ${J} + ?`;if(J9(this._definition))G+=", updated_at = ?",X.push(X9());let U=this.composeWhere(X);if(U)G+=` WHERE ${U}`;return(await Y.run(G,X)).changes}decrement(Z,$=1){return this.increment(Z,-$)}async chunk(Z,$){let Y=0;while(!0){let X=new HZ(this._definition);X._wheres=[...this._wheres],X._orderBy=[...this._orderBy],X._select=[...this._select],X._withRelations=[...this._withRelations],X._trashed=this._trashed,X._limit=Z,X._offset=Y*Z;let J=await X.get();if(J.length===0)break;if(await $(J)===!1)break;if(J.length<Z)break;Y++}}async paginate(Z=1,$=15){let Y=await this.count(),X=Math.ceil(Y/$);this._limit=$,this._offset=(Z-1)*$;let J=await this.get();return{data:J,total:Y,page:Z,perPage:$,lastPage:X,hasMorePages:Z<X,isEmpty:J.length===0,from:J.length>0?(Z-1)*$+1:null,to:J.length>0?(Z-1)*$+J.length:null}}async pluck(Z){S8(Z,"pluck(column)");let $=RZ(),Y=[],X=j8(Z),J=`SELECT ${X} FROM ${this._definition.table}`,G=this.composeWhere(Y);if(G)J+=` WHERE ${G}`;if(this._orderBy.length>0)J+=` ORDER BY ${this._orderBy.map((H)=>`${j8(H.column)} ${H.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)J+=` LIMIT ${this._limit}`;if(this._offset!==void 0)J+=` OFFSET ${this._offset}`;return(await $.all(J,Y)).map((H)=>H[X])}async aggregate(Z,$){S8($,`${Z}(column)`);let Y=RZ(),X=[],J=`SELECT ${Z}(${j8($)}) as v FROM ${this._definition.table}`,G=this.composeWhere(X);if(G)J+=` WHERE ${G}`;let H=(await Y.get(J,X))?.v;if(H==null)return null;if(typeof H==="string"){let z=Number(H);return H.trim()!==""&&!Number.isNaN(z)?z:H}return H}max(Z){return this.aggregate("MAX",Z)}min(Z){return this.aggregate("MIN",Z)}async avg(Z){return Number(await this.aggregate("AVG",Z)??0)||0}async sum(Z){return Number(await this.aggregate("SUM",Z)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let Z=RZ(),$=[],Y=`DELETE FROM ${this._definition.table}`,X=this.composeWhere($);if(X)Y+=` WHERE ${X}`;return(await Z.run(Y,$)).changes}async update(Z){this.assertNoUnappliedClauses("update");let $=RZ(),Y=Object.entries(Z),X=Y.map(([H])=>`${j8(H)} = ?`).join(", "),J=Y.map(([,H])=>H);if(J9(this._definition))J.push(X9());let G=`UPDATE ${this._definition.table} SET ${X}${J9(this._definition)?", updated_at = ?":""}`,U=this.composeWhere(J);if(U)G+=` WHERE ${U}`;return(await $.run(G,J)).changes}}function sU(Z){let $={query:()=>new HZ(Z),where(Y,X,J){return new HZ(Z).where(Y,X,J)},orWhere(Y,X,J){return new HZ(Z).orWhere(Y,X,J)},whereIn(Y,X){return new HZ(Z).whereIn(Y,X)},whereNotIn(Y,X){return new HZ(Z).whereNotIn(Y,X)},whereNull(Y){return new HZ(Z).whereNull(Y)},whereNotNull(Y){return new HZ(Z).whereNotNull(Y)},whereLike(Y,X){return new HZ(Z).whereLike(Y,X)},orderBy(Y,X="asc"){return new HZ(Z).orderBy(Y,X)},orderByDesc(Y){return new HZ(Z).orderByDesc(Y)},select(...Y){return new HZ(Z).select(...Y)},with(...Y){return new HZ(Z).with(...Y)},limit:(Y)=>new HZ(Z).limit(Y),take:(Y)=>new HZ(Z).take(Y),skip:(Y)=>new HZ(Z).skip(Y),withTrashed:()=>new HZ(Z).withTrashed(),onlyTrashed:()=>new HZ(Z).onlyTrashed(),async find(Y){let X=RZ(),J=Z.primaryKey||"id",G=M9(Z)?` AND ${m8} IS NULL`:"",U=await X.get(`SELECT * FROM ${Z.table} WHERE ${J} = ?${G}`,[Y]);return U?new rZ(Z,U):void 0},async findOrFail(Y){let X=await $.find(Y);if(!X)throw Error(`${Z.name} with id ${Y} not found`);return X},async findMany(Y){let X=RZ(),J=Z.primaryKey||"id",G=M9(Z)?` AND ${m8} IS NULL`:"";return(await X.all(`SELECT * FROM ${Z.table} WHERE ${J} IN (${Y.map(()=>"?").join(", ")})${G}`,Y)).map((H)=>new rZ(Z,H))},all:()=>new HZ(Z).get(),first:()=>new HZ(Z).first(),firstOrFail:()=>new HZ(Z).firstOrFail(),last:()=>new HZ(Z).last(),count:()=>new HZ(Z).count(),exists:()=>new HZ(Z).exists(),doesntExist:()=>new HZ(Z).doesntExist(),paginate:(Y,X)=>new HZ(Z).paginate(Y,X),whereBetween(Y,X){return new HZ(Z).whereBetween(Y,X)},whereNotBetween(Y,X){return new HZ(Z).whereNotBetween(Y,X)},async create(Y){let X=new rZ(Z,Y);return await X.save(),X},async createMany(Y){let X=[];for(let J of Y)X.push(await this.create(J));return X},async updateOrCreate(Y,X){let J=new HZ(Z);for(let[U,H]of Object.entries(Y))J=J.where(U,H);let G=await J.first();if(G)return await G.update(X),G;return this.create({...Y,...X})},async firstOrCreate(Y,X){let J=new HZ(Z);for(let[U,H]of Object.entries(Y))J=J.where(U,H);return await J.first()||this.create({...Y,...X})},async destroy(Y){let X=RZ(),J=Z.primaryKey||"id";return(await X.run(`DELETE FROM ${Z.table} WHERE ${J} = ?`,[Y])).changes>0},remove(Y){return this.destroy(Y)},async truncate(){await RZ().run(`DELETE FROM ${Z.table}`,[])},getDefinition:()=>Z,getTable:()=>Z.table,make(Y={}){return new rZ(Z,Y)},latest:(Y="created_at")=>new HZ(Z).orderByDesc(Y),oldest:(Y="created_at")=>new HZ(Z).orderBy(Y,"asc"),max:(Y)=>new HZ(Z).max(Y),min:(Y)=>new HZ(Z).min(Y),avg:(Y)=>new HZ(Z).avg(Y),sum:(Y)=>new HZ(Z).sum(Y),pluck(Y){return new HZ(Z).pluck(Y)}};return new Proxy($,{get(Y,X){if(typeof X==="string"&&X.startsWith("where")&&X.length>5){let J=X.slice(5),G=J.charAt(0).toLowerCase()+J.slice(1);if(G in Z.attributes||G==="id"||G===Z.primaryKey)return(U)=>new HZ(Z).where(G,U)}return Reflect.get(Y,X)}})}function N1(Z){let $=sU(Z);if(Z?.name)pU(Z.name,$);return $}async function rW(Z){let $=RZ(),Y=OZ(Z.primaryKey||"id"),X=[],J=new Set([Y]);if(X.push(Z.autoIncrement!==!1?`${Y} INTEGER PRIMARY KEY AUTOINCREMENT`:`${Y} INTEGER PRIMARY KEY`),Z.traits?.useUuid)X.push("uuid TEXT UNIQUE"),J.add("uuid");for(let[G,U]of Object.entries(Z.attributes)){let H=OZ(G);if(J.has(H))continue;J.add(H);let z=CX(U.type),A=i$(z);if(H.endsWith("_id")&&(z===void 0||R9(z)))A="INTEGER";let W=`${H} ${A}`;if(U.unique)W+=" UNIQUE";if(typeof U.foreignKey==="object"&&U.foreignKey!==null){let Q=U.foreignKey;if(W+=` REFERENCES ${Q.table}(${Q.column??"id"})`,Q.onDelete)W+=` ON DELETE ${Q.onDelete.toUpperCase()}`;if(Q.onUpdate)W+=` ON UPDATE ${Q.onUpdate.toUpperCase()}`}X.push(W)}for(let G of E9(Z.belongsTo)){let U=G.foreignKey??`${OZ(G.model)}_id`;if(J.has(U))continue;J.add(U),X.push(`${U} INTEGER`)}if(J9(Z))for(let G of["created_at","updated_at"]){if(J.has(G))continue;J.add(G),X.push(`${G} TEXT`)}if(M9(Z)&&!J.has("deleted_at"))J.add("deleted_at"),X.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${Z.table} (${X.join(", ")})`,[])}async function aW(Z,$,Y){let X=RZ(),J=Z.traits?.useSeeder,G=$??(typeof J==="object"&&J?J.count:10);if(!Y)try{let U=await import("./chunk-wwssp8h1.js");Y=_1(U.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let U=0;U<G;U++){let H={};for(let[A,W]of Object.entries(Z.attributes))if(W.factory)H[OZ(A)]=W.factory(Y);if(J9(Z)){let A=X9();H.created_at=A,H.updated_at=A}if(Z.traits?.useUuid)H.uuid=crypto.randomUUID();let z=Object.keys(H);await X.run(`INSERT INTO ${Z.table} (${z.join(", ")}) VALUES (${z.map(()=>"?").join(", ")})`,Object.values(H))}}var D1,U7=null,I0,z7,dU=500,Y9=null,N8=null,l9=null,F0=null,B0=null,m8="deleted_at",R0="__btm_rel__",F1,B1,R1,I9,nU=1000,H7,iU;var M0=z8(()=>{J0();qZ();h8();d$();L0();G7();g8();s$();D1=/^[A-Z_][A-Z0-9_]*$/i;I0=new Map;z7=new Map;F1=new WeakMap;B1=new Map,R1=new Map,I9=new Map;H7=["hasMany","hasOne","belongsTo","belongsToMany"],iU=[...H7,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var P1={};oU(P1,{registerModel:()=>w0,registerBrowserModels:()=>aU,hasModel:()=>y1,getModelRegistry:()=>v1,getModel:()=>k1,getAllModels:()=>x1,defineModel:()=>b1,clearModelRegistry:()=>h1});function k1(Z){return w9.get(Z)}function x1(){return[...w9.values()]}function v1(){return Object.fromEntries(w9)}function y1(Z){return w9.has(Z)}function h1(){w9.clear(),I1()}function w0(Z,$){return w9.set(Z,$),$}function rU(){return typeof window<"u"&&typeof document<"u"}function b1(Z){let $;if(rU())$=q1(Z);else{let Y=N1(Z);$=Object.assign(Y,{definition:Z,getDefinition:()=>Z,getTable:()=>Z.table,getName:()=>Z.name})}return w0(Z.name,$),$}function aU(Z){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...Z}}var w9;var s9=z8(()=>{T1();M0();w9=new Map});qZ();h8();import{existsSync as T8,mkdirSync as KJ,mkdtempSync as M2,readdirSync as LJ,readFileSync as a9,rmSync as FJ,unlinkSync as v0,writeFileSync as BJ}from"fs";import{tmpdir as w2}from"os";import{join as Z8}from"path";import y0 from"process";qZ();function U6(Z){let $=2166136261;for(let Y=0;Y<Z.length;Y++)$^=Z.charCodeAt(Y),$=Math.imul($,16777619)>>>0;return $.toString(36).padStart(7,"0").slice(-7)}function z6(Z,$=63){if(Z.length<=$)return Z;let Y=`_${U6(Z)}`;return Z.slice(0,$-Y.length)+Y}function A8(Z,$){let Y=`${Z}_`,X=$.startsWith(Y)?$:`${Y}${$}`;return z6(X)}class yZ{quoteIdentifier(Z){return`\`${Z.replace(/`/g,"``")}\``}getColumnType(Z){switch(Z.type){case"string":return`varchar(${Z.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(Z.enumValues&&Z.enumValues.length>0)return`ENUM(${Z.enumValues.map((Y)=>`'${Y.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(Z){return this.getColumnType(Z)}getAutoIncrementClause(Z){if(Z.isPrimaryKey&&(Z.type==="integer"||Z.type==="bigint"))return"auto_increment";return""}getDefaultValue(Z){if(!Z.hasDefault||Z.defaultValue===void 0)return"";let $=Z.defaultValue;if(typeof $==="string"){let Y=$.toUpperCase();if(Y==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(Y))return`default ${Y}`;let J=`'${$.replace(/'/g,"''")}'`;if(Z.type==="text"||Z.type==="json"||Z.type==="enum"&&!Z.enumValues?.length)return`default (${J})`;return`default ${J}`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?1:0}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(Z,$){return""}foreignKeyClauses(Z){return Z.columns.filter(($)=>$.references).map(($)=>{let Y=$.references,X=`${Z.table}_${$.name}_fk`,J=`CONSTRAINT ${this.quoteIdentifier(X)} FOREIGN KEY (${this.quoteIdentifier($.name)}) REFERENCES ${this.quoteIdentifier(Y.table)}(${this.quoteIdentifier(Y.column)})`;if(Y.onDelete)J+=` ON DELETE ${Y.onDelete.toUpperCase()}`;if(Y.onUpdate)J+=` ON UPDATE ${Y.onUpdate.toUpperCase()}`;return J})}createTable(Z){let $=[...Z.columns.map((Y)=>this.renderColumn(Y)),...this.foreignKeyClauses(Z)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
65
+ ${$.join(`,
66
+ `)}
67
+ ) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth(Z){let $=this.getColumnType(Z).toLowerCase();if($.includes("text")||$.includes("blob")||$==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let Y=$.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(Y!==void 0)return{bytes:Number(Y)*yZ.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts(Z,$,Y){let X=$.columns.map((G)=>{let U=Y?.find((A)=>A.name===G),H=U?this.keyPartWidth(U):{bytes:0,indexableWhole:!0},z=!H.indexableWhole;return{name:G,prefixed:z,bytes:z?yZ.KEY_PREFIX_CHARACTERS*yZ.BYTES_PER_CHARACTER:H.bytes,narrowable:!H.indexableWhole||H.bytes>yZ.KEY_PREFIX_CHARACTERS*yZ.BYTES_PER_CHARACTER}}),J=()=>X.reduce((G,U)=>G+U.bytes,0);while(J()>yZ.MAX_KEY_BYTES){let G=X.filter((U)=>U.narrowable&&!U.prefixed).sort((U,H)=>H.bytes-U.bytes)[0];if(!G)throw Error(`[migrations] Index '${$.name}' on table '${Z}' needs ${J()} bytes of key, over MySQL's ${yZ.MAX_KEY_BYTES}. Every column in it is already at its ${yZ.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);G.prefixed=!0,G.bytes=yZ.KEY_PREFIX_CHARACTERS*yZ.BYTES_PER_CHARACTER}return X.map((G)=>G.prefixed?`${this.quoteIdentifier(G.name)}(${yZ.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(G.name))}createIndex(Z,$,Y){if($.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${$.name}' on table '${Z}' uses WHERE clause: ${$.where}`);let X=$.type==="unique"?"UNIQUE ":"",J=A8(Z,$.name),G=this.keyParts(Z,$,Y).join(", ");return`CREATE ${X}INDEX ${this.quoteIdentifier(J)} ON ${this.quoteIdentifier(Z)} (${G});`}addForeignKey(Z,$,Y,X,J,G,U=[]){let H=`${Z}_${$}_fk`,z=`ALTER TABLE ${this.quoteIdentifier(Z)} ADD CONSTRAINT ${this.quoteIdentifier(H)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Y)}(${this.quoteIdentifier(X)})`;if(J)z+=` ON DELETE ${J.toUpperCase()}`;if(G)z+=` ON UPDATE ${G.toUpperCase()}`;let A=[...new Set(U)].map((W)=>`ALTER TABLE ${this.quoteIdentifier(Z)} DROP FOREIGN KEY ${this.quoteIdentifier(W)};`).join(`
68
+ `);return A?`${A}
69
+ ${z};`:`${z};`}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} ADD COLUMN ${X.join(" ")};`}modifyColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} MODIFY COLUMN ${X.join(" ")};`}renameColumn(Z,$,Y){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Y)};`}renameTable(Z,$){return`RENAME TABLE ${this.quoteIdentifier(Z)} TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable(Z){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(Z)}`}dropColumn(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(Z,$){let Y=A8(Z,$);return`DROP INDEX ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(Z)};`}dropEnumType(Z){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
70
+ id INT AUTO_INCREMENT PRIMARY KEY,
71
+ migration VARCHAR(255) NOT NULL UNIQUE,
72
+ executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
73
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(Z,$){return`JSON_UNQUOTE(JSON_EXTRACT(${Z}, CONCAT('$.', ${$})))`}dateBucket(Z,$,Y=0){let X=Y===0?Z:`DATE_ADD(${Z}, INTERVAL ${Y} HOUR)`;switch($){case"hour":return`DATE_FORMAT(${X}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${X}, INTERVAL WEEKDAY(${X}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${X}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${X}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${X}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral(Z){return Z?"TRUE":"FALSE"}renderColumn(Z){let $=this.getColumnType(Z),Y=[this.quoteIdentifier(Z.name),$];if(Z.isPrimaryKey){Y.push("PRIMARY KEY");let J=this.getAutoIncrementClause(Z);if(J)Y.push(J)}if(!Z.isNullable&&!Z.isPrimaryKey)Y.push("not null");let X=this.getDefaultValue(Z);if(X)Y.push(X);return Y.join(" ")}}class c${quoteIdentifier(Z){return`"${Z.replace(/"/g,'""')}"`}getColumnType(Z){switch(Z.type){case"string":return`varchar(${Z.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";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"timestamp";case"timestamptz":return"timestamptz";case"json":return"jsonb";case"enum":if(Z.enumValues&&Z.enumValues.length>0)return Z.enumTypeName?this.quoteIdentifier(Z.enumTypeName):"text";return"text";default:return"text"}}getPrimaryKeyType(Z){switch(Z.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(Z)}}getAutoIncrementClause(Z){return""}getDefaultValue(Z){if(!Z.hasDefault||Z.defaultValue===void 0)return"";let $=Z.defaultValue;if(typeof $==="string"){let Y=$.toUpperCase();if(Y==="UTC_TIMESTAMP")return"default (now() AT TIME ZONE 'utc')";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(Y))return`default ${Y}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?"true":"false"}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(Z,$){let Y=$.map((X)=>`'${X.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(Z)} AS ENUM (${Y});`}createTable(Z){let $=Z.columns.map((Y)=>this.renderColumn(Y)).join(`,
74
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
75
+ ${$}
76
+ );`}createIndex(Z,$){let Y=$.type==="unique"?"UNIQUE ":"",X=A8(Z,$.name),J=$.columns.map((U)=>this.quoteIdentifier(U)).join(", "),G=$.where?` WHERE ${$.where}`:"";return`CREATE ${Y}INDEX IF NOT EXISTS ${this.quoteIdentifier(X)} ON ${this.quoteIdentifier(Z)} (${J})${G};`}addForeignKey(Z,$,Y,X,J,G,U=[]){let H=`${Z}_${$}_fk`,z=`ALTER TABLE ${this.quoteIdentifier(Z)} ADD CONSTRAINT ${this.quoteIdentifier(H)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Y)}(${this.quoteIdentifier(X)})`;if(J)z+=` ON DELETE ${J.toUpperCase()}`;if(G)z+=` ON UPDATE ${G.toUpperCase()}`;let A=[...new Set(U)].map((W)=>`ALTER TABLE ${this.quoteIdentifier(Z)} DROP CONSTRAINT ${this.quoteIdentifier(W)};`).join(`
77
+ `);return A?`${A}
78
+ ${z};`:`${z};`}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} ADD COLUMN ${X.join(" ")};`}modifyColumn(Z,$){let Y=this.getColumnType($),X=this.quoteIdentifier(Z),J=this.quoteIdentifier($.name),G=[`ALTER TABLE ${X} ALTER COLUMN ${J} DROP DEFAULT;`,`ALTER TABLE ${X} ALTER COLUMN ${J} TYPE ${Y} USING ${J}::${Y};`];if(!$.isPrimaryKey)G.push(`ALTER TABLE ${X} ALTER COLUMN ${J} ${$.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let U=this.getDefaultValue($);if(U)G.push(`ALTER TABLE ${X} ALTER COLUMN ${J} SET ${U};`);return G.join(`
79
+ `)}renameColumn(Z,$,Y){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Y)};`}renameTable(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable(Z){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(Z)} CASCADE`}dropColumn(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(Z,$){let Y=A8(Z,$);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Y)};`}dropEnumType(Z){return`DROP TYPE IF EXISTS ${this.quoteIdentifier(Z)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
80
+ id SERIAL PRIMARY KEY,
81
+ migration VARCHAR(255) NOT NULL UNIQUE,
82
+ executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
83
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract(Z,$){return`(${Z}::jsonb ->> ${$})`}dateBucket(Z,$,Y=0){let X=Y===0?`${Z}::timestamp`:`(${Z}::timestamp ${Y>=0?"+":"-"} interval '${Math.abs(Y)} hours')`,J=$==="week"?`date_trunc('week', ${X})`:X;switch($){case"hour":return`to_char(${J}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${J}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${J}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${J}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral(Z){return Z?"TRUE":"FALSE"}renderColumn(Z){let $=Z.isPrimaryKey?this.getPrimaryKeyType(Z):this.getColumnType(Z),Y=[this.quoteIdentifier(Z.name),$];if(Z.isPrimaryKey)Y.push("PRIMARY KEY");if(!Z.isNullable&&!Z.isPrimaryKey)Y.push("not null");let X=this.getDefaultValue(Z);if(X)Y.push(X);if(Z.references){let J=`REFERENCES ${this.quoteIdentifier(Z.references.table)}(${this.quoteIdentifier(Z.references.column)})`;if(Z.references.onDelete)J+=` ON DELETE ${Z.references.onDelete.toUpperCase()}`;if(Z.references.onUpdate)J+=` ON UPDATE ${Z.references.onUpdate.toUpperCase()}`;Y.push(J)}return Y.join(" ")}}class u$ extends yZ{createTable(Z){let $=Z.columns.map((G)=>this.renderColumn(G)).join(`,
84
+ `),Y=[];if(Z.tableKind!=="reference"){let G=Z.shardKey?.length?Z.shardKey:Z.columns.filter((U)=>U.isPrimaryKey).map((U)=>U.name);if(G&&G.length>0)Y.push(`SHARD KEY (${G.map((U)=>this.quoteIdentifier(U)).join(", ")})`)}if(Z.tableKind!=="rowstore"&&Z.tableKind!=="reference"){let G=Z.sortKey?.length?Z.sortKey:void 0;Y.push(`SORT KEY (${(G??[]).map((U)=>this.quoteIdentifier(U)).join(", ")})`)}let X=[$,...Y].join(`,
85
+ `);return`CREATE${this.tableKindSuffix(Z.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
86
+ ${X}
87
+ );`}tableKindSuffix(Z){switch(Z){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex(Z,$,Y){if($.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${$.name}' on table '${Z}' uses WHERE clause: ${$.where}`);return super.createIndex(Z,$,Y)}}class n$ extends yZ{sharded;constructor(Z=!0){super();this.sharded=Z}getAutoIncrementClause(Z){return this.sharded?"":super.getAutoIncrementClause(Z)}renderColumn(Z){if(!this.sharded||!Z.references)return super.renderColumn(Z);let{references:$,...Y}=Z;return super.renderColumn(Y)}foreignKeyClauses(Z){return this.sharded?[]:super.foreignKeyClauses(Z)}createTable(Z){return super.createTable(Z)}addForeignKey(...Z){return this.sharded?"":super.addForeignKey(...Z)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
88
+ migration VARCHAR(255) NOT NULL PRIMARY KEY,
89
+ executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
90
+ )`}}J0();class l${quoteIdentifier(Z){return`"${Z.replace(/"/g,'""')}"`}getColumnType(Z){if(Z.name.endsWith("_id")&&R9(Z.type))return"INTEGER";if(Z.type==="enum"){if(Z.enumValues&&Z.enumValues.length>0){let $=Z.enumValues.map((Y)=>`'${Y.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(Z.name)} IN (${$}))`}return"TEXT"}return i$(Z.type)}getPrimaryKeyType(Z){return this.getColumnType(Z)}getAutoIncrementClause(Z){if(Z.isPrimaryKey&&(Z.type==="integer"||Z.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(Z){if(!Z.hasDefault||Z.defaultValue===void 0)return"";let $=Z.defaultValue;if(typeof $==="string"){if($.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes($.toUpperCase()))return`default ${$.toUpperCase()}`;return`default '${$.replace(/'/g,"''")}'`}else if(typeof $==="number"||typeof $==="bigint")return`default ${$}`;else if(typeof $==="boolean")return`default ${$?1:0}`;else if($ instanceof Date)return`default '${$.toISOString()}'`;return""}createEnumType(Z,$){return""}createTable(Z){let $=Z.columns.map((Y)=>this.renderColumn(Y)).join(`,
91
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(Z.table)} (
92
+ ${$}
93
+ );`}createIndex(Z,$){let Y=$.type==="unique"?"UNIQUE ":"",X=A8(Z,$.name),J=$.columns.map((U)=>this.quoteIdentifier(U)).join(", "),G=$.where?` WHERE ${$.where}`:"";return`CREATE ${Y}INDEX IF NOT EXISTS ${this.quoteIdentifier(X)} ON ${this.quoteIdentifier(Z)} (${J})${G};`}addForeignKey(Z,$,Y,X,J,G){return""}addColumn(Z,$){let Y=this.getColumnType($),X=[this.quoteIdentifier($.name),Y];if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let J=this.getDefaultValue($);if(J)X.push(J);return`ALTER TABLE ${this.quoteIdentifier(Z)} ADD COLUMN ${X.join(" ")};`}modifyColumn(Z,$){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(Z)}.${this.quoteIdentifier($.name)}`}renameColumn(Z,$,Y){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Y)};`}renameTable(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(Z){let{target:$,tempName:Y,columnSource:X}=Z,J=(A)=>this.quoteIdentifier(A),G=$.columns.map((A)=>this.renderColumn(A)).join(`,
94
+ `),U=`CREATE TABLE ${J(Y)} (
95
+ ${G}
96
+ );`,H=$.columns.map((A)=>A.name).filter((A)=>X[A]!==void 0),z=["PRAGMA foreign_keys=OFF;","BEGIN;",U];if(H.length>0){let A=H.map(J).join(", "),W=H.map((Q)=>J(X[Q])).join(", ");z.push(`INSERT INTO ${J(Y)} (${A}) SELECT ${W} FROM ${J($.table)};`)}z.push(`DROP TABLE ${J($.table)};`),z.push(`ALTER TABLE ${J(Y)} RENAME TO ${J($.table)};`);for(let A of $.indexes)z.push(this.createIndex($.table,A));return z.push("PRAGMA foreign_key_check;"),z.push("COMMIT;"),z.push("PRAGMA foreign_keys=ON;"),z.join(`
97
+ `)}dropTable(Z){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(Z)}`}dropColumn(Z,$){return`ALTER TABLE ${this.quoteIdentifier(Z)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(Z,$){let Y=A8(Z,$);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Y)};`}dropEnumType(Z){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
98
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
99
+ migration TEXT NOT NULL UNIQUE,
100
+ executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
101
+ )`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract(Z,$){return`json_extract(${Z}, '$.' || ${$})`}dateBucket(Z,$,Y=0){let X=Y===0?Z:`datetime(${Z}, '${Y>=0?"+":"-"}${Math.abs(Y)} hours')`;switch($){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${X})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${X}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${X})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${X})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${X})`}}booleanLiteral(Z){return Z?"TRUE":"FALSE"}renderColumn(Z){let $=this.getColumnType(Z),Y=[this.quoteIdentifier(Z.name),$];if(Z.isPrimaryKey){Y.push("PRIMARY KEY");let J=this.getAutoIncrementClause(Z);if(J)Y.push(J)}if(!Z.isNullable&&!Z.isPrimaryKey)Y.push("not null");let X=this.getDefaultValue(Z);if(X)Y.push(X);if(Z.references){if(Y.push(`REFERENCES ${this.quoteIdentifier(Z.references.table)}(${this.quoteIdentifier(Z.references.column)})`),Z.references.onDelete)Y.push(`ON DELETE ${Z.references.onDelete.toUpperCase()}`);if(Z.references.onUpdate)Y.push(`ON UPDATE ${Z.references.onUpdate.toUpperCase()}`)}return Y.join(" ")}}function K8(Z,$={}){switch(Z){case"postgres":return new c$;case"mysql":return new yZ;case"singlestore":return new u$;case"vitess":return new n$($.vitessSharded??f.vitess?.sharded??!0);case"sqlite":return new l$;default:throw Error(`Unsupported dialect: ${Z}`)}}h8();async function H6(Z={}){let $=Z.iterations||1000,Y=Z.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${$}`),console.log(`-- Operations: ${Y.join(", ")}`),console.log();let X=XZ();console.log("-- Setting up test table...");try{await e.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await e.unsafe(`
102
+ CREATE TABLE bench_users (
103
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
104
+ name TEXT NOT NULL,
105
+ email TEXT NOT NULL,
106
+ active INTEGER DEFAULT 1,
107
+ created_at TEXT
108
+ )
109
+ `).execute();for(let U=0;U<100;U++)await e.unsafe(`
110
+ INSERT INTO bench_users (name, email, created_at)
111
+ VALUES (?, ?, ?)
112
+ `,[`User ${U}`,`user${U}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(U){throw console.error("-- Failed to setup test table:",U),U}let J=[];if(Y.includes("select")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.selectFrom("bench_users").where({active:1}).limit(10).execute(),U.push(performance.now()-z)}J.push({operation:"SELECT with WHERE + LIMIT",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("select")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.selectFrom("bench_users").where({id:1}).first(),U.push(performance.now()-z)}J.push({operation:"SELECT by ID (first)",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("count")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.selectFrom("bench_users").count(),U.push(performance.now()-z)}J.push({operation:"COUNT",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("insert")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.insertInto("bench_users").values({name:`Bench User ${H}`,email:`bench${H}@example.com`,created_at:new Date().toISOString()}).execute(),U.push(performance.now()-z)}J.push({operation:"INSERT",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("update")){let U=[];for(let H=0;H<$;H++){let z=performance.now();await X.updateTable("bench_users").set({active:0}).where({id:1}).execute(),U.push(performance.now()-z)}J.push({operation:"UPDATE by ID",avgTime:U.reduce((H,z)=>H+z,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}if(Y.includes("delete")){let U=[],H=[];for(let z=0;z<$;z++){let A=await X.insertInto("bench_users").values({name:"To Delete",email:`delete${z}@example.com`,created_at:new Date().toISOString()}).execute();H.push(A)}for(let z=0;z<$;z++){let A=performance.now();await X.deleteFrom("bench_users").where({id:H[z]}).execute(),U.push(performance.now()-A)}J.push({operation:"DELETE by ID",avgTime:U.reduce((z,A)=>z+A,0)/U.length,minTime:Math.min(...U),maxTime:Math.max(...U),iterations:$})}console.log("-- Benchmark Results"),console.log();let G=Math.max(...J.map((U)=>U.operation.length));console.log("Operation".padEnd(G+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(G+2+12+12+12+12));for(let U of J){let H=U.operation.padEnd(G+2),z=U.avgTime.toFixed(3).padStart(12),A=U.minTime.toFixed(3).padStart(12),W=U.maxTime.toFixed(3).padStart(12),Q=(1000/U.avgTime).toFixed(0).padStart(12);console.log(`${H}${z}${A}${W}${Q}`)}console.log();try{await e.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(U){console.error("-- Warning: Failed to cleanup test table:",U)}}qZ();h8();qZ();g8();function j6(Z){return f8(f.relations?.singularizeStrategy)(Z)}function t8(Z,$,Y,X={}){let J=X.singularize??j6,U=Z.relations?.[$]?.belongsToMany?.[Y];if(U==null)return null;let H=typeof U==="object",z=H?U:null,A=H?z.model:U,W=Z.modelToTable[A]||A,Q,R;if(z?.table)Q=z.table;else if(z?.through){if(R=z.through,Q=Z.modelToTable[z.through],!Q)throw Error(`[query-builder] belongsToMany relation '${Y}' on '${$}' references unknown through model '${z.through}'. Make sure '${z.through}' is registered via defineModels({...}).`)}else{let K=J($),I=J(W);Q=[K,I].sort().join("_")}let O=z?.foreignKey??`${J($)}_id`,N=z?.relatedKey??`${J(W)}_id`,_={};if(z?.pivot?.columns)Object.assign(_,z.pivot.columns);if(R&&X.models){let K=X.models[R],I=K?.definition??K?.getDefinition?.()??K,B=I?.attributes??{};for(let[v,P]of Object.entries(B)){if(v===O||v===N||v===(I?.primaryKey??"id"))continue;_[v]={default:P?.default,nullable:P?.nullable,validation:P?.validation}}}let F=Boolean(z?.pivot?.timestamps),L=Object.keys(_);return{pivotTable:Q,fkParent:O,fkRelated:N,pivotColumns:L,pivotColumnDefs:_,pivotModelName:R,timestamps:F,relatedModelName:A,relatedTable:W,hasConfig:H}}function*OH(Z,$={}){let Y=Z.relations;if(!Y)return;for(let[X,J]of Object.entries(Y)){let G=J?.belongsToMany;if(!G)continue;for(let U of Object.keys(G)){let H=t8(Z,X,U,$);if(H)yield{parentTable:X,relationKey:U,resolved:H}}}}g8();s$();function w8(Z){return typeof Z==="object"&&Z!==null&&"raw"in Z&&typeof Z.raw==="string"}function o$(Z){return typeof Z==="object"&&Z!==null&&"sql"in Z&&typeof Z.sql==="string"&&(!("parameters"in Z)||Array.isArray(Z.parameters))}function r$(Z,$){let Y=Z.parameters??[];if(f.dialect!=="postgres"||Y.length===0)return{text:Z.sql,parameters:Y};let X=0,J=Z.sql.replace(/\?/g,(G)=>{if(X>=Y.length)return G;return s($+X++)});if(X!==Y.length)throw TypeError(`[query-builder] SQL expression declares ${Y.length} parameters but contains only ${X} placeholders`);return{text:J,parameters:Y}}function NH(Z,...$){if(typeof Z==="string")return{raw:Z};let Y=Z[0];for(let X=0;X<$.length;X++)Y+=M8($[X])+Z[X+1];return{raw:Y}}function oZ(Z){return YZ(f.dialect)?`\`${Z.replace(/`/g,"``")}\``:`"${Z.replace(/"/g,'""')}"`}function a$(Z,$=1){let Y=Object.keys(Z[0]??{}),X=[],J=$,G=Z.map((U)=>{return`(${Y.map((z)=>{return X.push(U[z]),s(J++)}).join(", ")})`});return{colsSql:Y.map(oZ).join(", "),valuesSql:G.join(", "),params:X,nextIndex:J}}function d9(Z){return Boolean(Z&&(Z.onSlowQuery||Z.slowQueryThresholdMs!=null&&Z.slowQueryThresholdMs>=0))}function PX(Z){if(typeof Z==="string")return Z;if(w8(Z))return Z.raw;if(Z&&typeof Z==="object"){let $=Z;if(typeof $.raw==="function")return String($.raw());if(typeof $.sql==="string")return $.sql;let Y=String(Z);if(Y!=="[object Object]")return Y}throw TypeError(`[query-builder] select(): unsupported column ${String(Z)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function _6(Z){let $=/\(|\)|\bORDER\s+BY\b/gi,Y=0,X;while(X=$.exec(Z))if(X[0]==="(")Y++;else if(X[0]===")")Y=Math.max(0,Y-1);else if(Y===0)return!0;return!1}var WZ={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},qX=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function i(Z,$){if(!WZ.IDENTIFIER.test(Z)){let Y=$?` in ${$}`:"";throw Error(`[query-builder] Invalid identifier${Y}: '${Z}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function TZ(Z,$){if(typeof Z!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof Z}`);let Y=Z.toLowerCase();if(!qX.has(Y))throw TypeError(`[query-builder] ${$}: refusing to use '${Z}' as a SQL operator \u2014 not in the allowed set (${[...qX].join(", ")})`);return Z}function J8(Z,$){if(typeof Z!=="string"||Z.length===0)throw TypeError(`[query-builder] ${$}: identifier must be a non-empty string, got ${typeof Z}`);if(Z.length>129)throw TypeError(`[query-builder] ${$}: identifier '${Z}' too long`);let Y=Z.split(".");if(Y.length>2)throw TypeError(`[query-builder] ${$}: identifier '${Z}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let X of Y)if(!/^[A-Z_][A-Z0-9_]*$/i.test(X))throw TypeError(`[query-builder] ${$}: identifier segment '${X}' contains characters outside [A-Za-z0-9_]`)}function Z9(Z,$){if(typeof Z==="string")return V6($),Z;if(Z===null||Z===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${Z}`);if(w8(Z))return Z.raw;if(typeof Z==="object"){let Y=Z;if(typeof Y.raw==="string")return Y.raw;if(typeof Y.raw==="function"){let J=Y.raw();if(typeof J==="string")return J}if(typeof Y.sql==="string")return Y.sql;let X=String(Z);if(X!=="[object Object]"&&X!=="[object Promise]")return X}throw TypeError(`[query-builder] ${$}: 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 TX=new Set;function V6(Z){if(TX.has(Z))return;TX.add(Z),console.warn(`[query-builder] ${Z}: 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 K6(Z,$=f.dialect){return YZ($)?Z.replace(/\\/g,"\\\\").replace(/'/g,"''"):Z.replace(/'/g,"''")}function M8(Z){if(Z===null)return"NULL";if(typeof Z==="number"&&Number.isFinite(Z))return String(Z);if(typeof Z==="boolean")return Z?"1":"0";if(typeof Z==="string")return`'${K6(Z)}'`;if(Z instanceof Date)return`'${Z.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof Z}`)}function L6(Z,$){let Y=Array.isArray(Z)?Z:Z?[Z]:[],X=[];if(Y.length)X.push(`PARTITION BY ${Y.join(", ")}`);if($&&$.length)X.push(`ORDER BY ${$.map(([J,G])=>`${J} ${G==="desc"?"DESC":"ASC"}`).join(", ")}`);return X.length?`OVER (${X.join(" ")})`:"OVER ()"}class kX{cache=new Map;maxSize=100;get(Z){let $=this.cache.get(Z);if(!$)return null;if(Date.now()>$.expiresAt)return this.cache.delete(Z),null;return this.cache.delete(Z),this.cache.set(Z,$),$.data}set(Z,$,Y){if(this.cache.has(Z))this.cache.delete(Z);if(this.cache.size>=this.maxSize){let X=Date.now(),J=!1;for(let[G,U]of this.cache)if(X>U.expiresAt){if(this.cache.delete(G),J=!0,this.cache.size<this.maxSize)break}if(!J){let G=this.cache.keys().next().value;if(G!==void 0)this.cache.delete(G)}}this.cache.set(Z,{data:$,expiresAt:Date.now()+Y})}clear(){this.cache.clear()}setMaxSize(Z){this.maxSize=Math.max(0,Math.floor(Z));while(this.cache.size>this.maxSize){let $=this.cache.keys().next().value;if($===void 0)break;this.cache.delete($)}}}var e$=new kX;function F6(Z){let $=String(Z?.message||"").toLowerCase();return $.includes("deadlock")||$.includes("serialization failure")||$.includes("could not serialize access")||$.includes("deadlock found when trying to get lock")||$.includes("lock wait timeout exceeded")||$.includes("database is locked")||$.includes("busy")}function B6(Z,$){if(!$||$.length===0)return!1;let Y=Z&&(Z.code||Z.sqlState||Z.sqlstate);if(!Y)return!1;return $.includes(Y)}function R6(Z){return new Promise(($)=>setTimeout($,Z))}var t$=new Map,O6=500;function m9(Z){let $=t$.get(Z);if($!==void 0)return $;let Y=D6(Z);if(t$.size>=O6)t$.clear();return t$.set(Z,Y),Y}function D6(Z){let $=[{key:"GROUP_BY",tokens:/^GROUP\s+BY\b/i},{key:"ORDER_BY",tokens:/^ORDER\s+BY\b/i},{key:"HAVING",tokens:/^HAVING\b/i},{key:"OFFSET",tokens:/^OFFSET\b/i},{key:"LIMIT",tokens:/^LIMIT\b/i},{key:"WHERE",tokens:/^WHERE\b/i}],Y=[],X=0,J=!1,G="";for(let W=0;W<Z.length;W++){let Q=Z[W];if(J){if(Q===G){if(Z[W+1]===G){W++;continue}J=!1}continue}if(Q==="'"||Q==='"'||Q==="`"){J=!0,G=Q;continue}if(Q==="("){X++;continue}if(Q===")"){X--;continue}if(X!==0)continue;if(W===0||!/\s/.test(Z[W-1]))continue;let R=Z.charCodeAt(W)&-33;if(R!==71&&R!==79&&R!==72&&R!==76&&R!==87)continue;let O=Z.slice(W);for(let{key:N,tokens:_}of $){let F=O.match(_);if(!F)continue;Y.push({key:N,start:W}),W+=F[0].length-1;break}}if(Y.length<=1)return Z;let U=Z.slice(0,Y[0].start).trimEnd(),H={};for(let W=0;W<Y.length;W++){let Q=Y[W].start,R=W+1<Y.length?Y[W+1].start:Z.length,O=Z.slice(Q,R).trim();if(!H[Y[W].key])H[Y[W].key]=[];H[Y[W].key].push(O)}let A=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((W)=>H[W]).map((W)=>H[W].join(" ")).join(" ");return A?`${U} ${A}`:U}function E6(Z,$){let Y=Math.max(1,$?.baseMs??50),X=Math.max(1,$?.factor??2),J=Math.max(Y,$?.maxMs??2000),G=Math.min(J,Y*X**Math.max(0,Z-1));if($?.jitter)G=Math.min(J,G*(0.9+Math.random()*0.2));return Math.floor(G)}function XZ(Z){let $=Z?.sql??y8(),Y=Z?.meta,X=Z?.schema;function J(_){if(typeof _==="number")return _;let F=String(_),L=7;for(let K=0;K<F.length;K++)L=L*31+F.charCodeAt(K)|0;return Math.abs(L)}function G(){if(!Z?.hooks)return f.hooks;return{...f.hooks,...Z.hooks}}let U=new Map;function H(_){if(Array.isArray(_)){let[B,v,P]=_;i(B,"where(column)");let T=String(B);switch(v){case"in":if(Array.isArray(P)){let w=PZ(P.length);return $.unsafe(`${T} IN (${w})`,P)}return $.unsafe(`${T} IN (${s(1)})`,[P]);case"not in":if(Array.isArray(P)){let w=PZ(P.length);return $.unsafe(`${T} NOT IN (${w})`,P)}return $.unsafe(`${T} NOT IN (${s(1)})`,[P]);case"like":return $.unsafe(`${T} LIKE ${s(1)}`,[P]);case"is":case"is not":{if(P!==null&&P!==void 0)throw TypeError(`[query-builder] where(..., '${v}', ?): operator '${v}' only accepts NULL/undefined as value, got ${typeof P} (${String(P)})`);return $.unsafe(`${T} IS ${v==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${T} <> ${s(1)}`,[P]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${T} ${v} ${s(1)}`,[P]);default:throw TypeError(`[query-builder] where(..., '${String(v)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in _)return _.raw;let F=Object.keys(_);if(F.length===0)return $.unsafe("");let L=[],K=[],I=1;for(let B of F){i(B,"where(object key)");let v=_[B];if(Array.isArray(v)){let P=PZ(v.length,I);L.push(`${B} IN (${P})`),K.push(...v),I+=v.length}else L.push(`${B} = ${s(I++)}`),K.push(v)}return $.unsafe(L.join(" AND "),K)}function z(_,F,L){if(!L)return F;let K=H(L);return $`${F} WHERE ${K}`}function A(_){let F=f.debug?.captureText;if(f.debug)f.debug.captureText=!0;let L=String(_);if(f.debug)f.debug.captureText=F;return L}function W(_){if(!_||typeof _!=="object")return;if(Array.isArray(_.values))return _.values;if(Array.isArray(_.parameters))return _.parameters;if(Array.isArray(_.params))return _.params;return}function Q(_,F,L){let K=G(),I=K?.slowQueryThresholdMs,B=I!=null&&I>=0,v=Boolean(K?.onSlowQuery||B),P=K&&(K.onQueryStart||K.onQueryEnd||K.onQueryError||K.startSpan||v),T=L?.timeoutMs&&L.timeoutMs>0||L?.signal;if(!P&&!T)return _.execute();let w=A(_),M=W(_),q=Date.now(),C;try{if(K?.onQueryStart?.({sql:w,params:M,kind:F}),K?.startSpan)C=K.startSpan({sql:w,params:M,kind:F})}catch{}let y=!1,c=(m,n)=>{if(y)return;y=!0;let h=Date.now()-q;try{if(m)K?.onQueryError?.({sql:w,params:M,error:m,durationMs:h,kind:F});else if(K?.onQueryEnd?.({sql:w,params:M,durationMs:h,rowCount:n,kind:F}),B&&h>=I)if(K?.onSlowQuery)K.onSlowQuery({sql:w,params:M,durationMs:h,kind:F});else console.warn(`[query-builder] slow query (${h}ms >= ${I}ms): ${w}`)}catch{}try{C?.end(m)}catch{}},l=_.execute(),r=[l],x;if(L?.timeoutMs&&L.timeoutMs>0){let m=new Promise((n,h)=>{x=setTimeout(()=>{try{_.cancel?.()}catch{}let ZZ=Error(`Query timed out after ${L.timeoutMs}ms`);ZZ.code="EBQBTIMEOUT",h(ZZ)},L.timeoutMs)});r.push(m)}if(L?.signal){if(L.signal.aborted){try{_.cancel?.()}catch{}let n=Error("Query aborted");return n.code="EBQBABORT",c(n),Promise.reject(n)}let m=()=>{try{_.cancel?.()}catch{}};L.signal.addEventListener("abort",m,{once:!0}),l.finally(()=>{L.signal?.removeEventListener("abort",m)})}return Promise.race(r).then((m)=>{clearTimeout(x);let n=Array.isArray(m)?m.length:typeof m==="number"?m:void 0;return c(void 0,n),m}).catch((m)=>{throw clearTimeout(x),c(m),m})}function R(_){if(typeof _==="number")return Number.isFinite(_)?_:0;if(typeof _==="bigint")return Number(_);if(!_||typeof _!=="object")return 0;let F=_;for(let L of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(F[L]!==void 0&&F[L]!==null)return R(F[L]);if(Array.isArray(_))return _.reduce((L,K)=>L+R(K),0);return 0}function O(_,F){let L=F??A(_);return{sql:L,toString:()=>L,execute:()=>_.execute(),values:()=>_.values(),raw:()=>_.raw()}}function N(_,F){let L=$,K=F&&F.length>0?`SELECT ${F.join(", ")} FROM ${String(_)}`:`SELECT * FROM ${String(_)}`,I=[],B=[],v=!1,P=null,T=()=>{if(P===null){let j=m9(y());P=B.length>0?$.unsafe(j,B):$.unsafe(j)}return P},w=(j,V)=>{I.push({conn:j,sql:V}),P=null},M=(j,V)=>{w(j==="OR"?"OR":"AND",V)},q=/\(|\)|\b(?:GROUP\s+BY|HAVING|ORDER\s+BY|LIMIT|OFFSET|WINDOW|UNION|INTERSECT|EXCEPT|FOR\s+UPDATE|FOR\s+SHARE|LOCK\s+IN\s+SHARE\s+MODE)\b/gi,C=(j)=>{q.lastIndex=0;let V=0,D;while(D=q.exec(j))if(D[0]==="(")V++;else if(D[0]===")")V=Math.max(0,V-1);else if(V===0)return D.index;return-1},y=(j)=>{let V=e8(j?[...I,j]:I);if(!V)return K;if(v){let E=WZ.WHERE.test(K)?"AND":"WHERE";return`${K} ${E} ${V}`}let D=C(K);return D>=0?`${K.slice(0,D)}WHERE ${V} ${K.slice(D)}`:`${K} WHERE ${V}`},c=(j,V)=>{let D=N(_);V(D);let E=D.__whereState?.();if(!E||!E.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=B.length,k=S>0&&f.dialect==="postgres"?E.body.replace(/\$(\d+)/g,(g,p)=>`$${Number(p)+S}`):E.body;B.push(...E.params),w(j,`(${k})`)},l=(j,V,D,E,S,k)=>{if(typeof E==="string"&&S!==void 0){i(String(E),`${D}(column)`),TZ(S,`${D}(operator)`);let g=B.length+1;return B.push(k),w(V,`${String(E)} ${String(S)} ${s(g)}`),j}if(Array.isArray(E)){let[g,p,u]=E,b=String(g);i(b,`${D}(column)`);let d=TZ(p,`${D}(operator)`);if(d==="in"||d==="not in"){let o=Array.isArray(u)?u:[u],JZ=PZ(o.length,B.length+1),SZ=tZ(b,o,d==="not in",JZ);B.push(...o),w(V,SZ)}else{let o=B.length+1;B.push(u),w(V,`${b} ${d} ${s(o)}`)}return j}if(typeof E==="function")return c(V,E),j;if(E&&typeof E==="object"&&!("raw"in E)){let g=[];for(let p of Object.keys(E)){i(p,`${D}(column)`);let u=E[p];if(Array.isArray(u)){let b=PZ(u.length,B.length+1);g.push(tZ(p,u,!1,b)),B.push(...u)}else{let b=B.length+1;g.push(`${p} = ${s(b)}`),B.push(u)}}if(g.length>0)w(V,g.length>1?`(${g.join(" AND ")})`:g[0]);return j}if(E&&typeof E.raw<"u")return w(V,E.raw),j;return j},r=(j,V)=>{if(I.length>0)K=y(),I.length=0;v=!0;let D=V.__rawState?.();if(D){let E=B.length,S=f.dialect==="postgres"?D.sql.replace(/\$(\d+)/g,(k,g)=>`$${Number(g)+E}`):D.sql;K+=` ${j} ${S}`,B.push(...D.params)}else K+=` ${j} ${String(V.toSQL())}`;P=null},x=(j)=>{let V=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,D=0,E=-1,S;while(S=V.exec(K))if(S[0]==="(")D++;else if(S[0]===")")D=Math.max(0,D-1);else if(D===0){E=S.index;break}K=E>=0?`${K.slice(0,E)}${j} ${K.slice(E)}`:`${K} ${j}`,P=null},m=new Set,n,h,ZZ=!1,a=!1,DZ=!1,jZ=new Map,mZ=new Set,k8=60000,FZ=(j)=>f8(f.relations.singularizeStrategy)(j),$8=(j)=>{if(!Y)return null;return t8(Y,String(_),j,{singularize:FZ,models:Y.models})},i8=(j)=>{if(!j||typeof j!=="object"||mZ.size===0)return j;let V;for(let D of Object.keys(j))if(D.startsWith("pivot_")){if(!V)V={};V[D.slice(6)]=j[D],delete j[D]}if(V)j.pivot=V;return j},l8=(j)=>{if(mZ.size===0||!j)return j;if(Array.isArray(j))for(let V=0;V<j.length;V++)i8(j[V]);else i8(j);return j},F8=(j)=>{if(!Y)return;if(m.has(j.pivotTable))return;let V=String(_),D=Y.primaryKeys[V]??"id";i(j.pivotTable,"wherePivot auto-join (pivot table)"),i(j.fkParent,"wherePivot auto-join (parent FK)"),i(V,"wherePivot auto-join (parent table)"),i(D,"wherePivot auto-join (parent PK)"),P=L`${T()} LEFT JOIN ${L(j.pivotTable)} ON ${L(`${j.pivotTable}.${j.fkParent}`)} = ${L(`${V}.${D}`)}`,K=`${K} LEFT JOIN ${j.pivotTable} ON ${j.pivotTable}.${j.fkParent} = ${V}.${D}`,m.add(j.pivotTable)},N9=(j)=>{if(WZ.SELECT_STAR.test(K))K=K.replace(WZ.SELECT_STAR,`SELECT *, ${j}`);else if(WZ.SELECT.test(K))K=K.replace(WZ.SELECT_FROM,`SELECT $1, ${j} FROM`);let V=String(T());if(WZ.SELECT_STAR.test(V)){let D=V.replace(WZ.SELECT_STAR,`SELECT *, ${j}`);P=$.unsafe(D)}else if(WZ.SELECT.test(V)){if(WZ.SELECT_FROM.exec(V)){let E=V.replace(WZ.SELECT_FROM,`SELECT $1, ${j} FROM`);P=$.unsafe(E)}}},Q8=(j,V,D,E)=>{N9(`${j} ${L6(D,E)} AS ${V}`)},t9=(j,V,D,E)=>{i(j,"relationship subquery (parent table)"),i(V,"relationship subquery (target table)"),i(D,"relationship subquery (primary key)");let S=`${j.endsWith("s")?j.slice(0,-1):j}_id`;i(S,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${V} WHERE ${V}.${S} = ${j}.${D}`;if(E){let p=E({where:(u,b,d)=>{return i(u,"relationship subquery condition"),`${V}.${u} ${TZ(b,"whereHas callback")} ${M8(d)}`}});if(p)k+=` AND ${p}`}return k},e9=(j,V,D,E)=>{i(j,"relationship subquery (parent table)"),i(V,"relationship subquery (target table)"),i(D,"relationship subquery (primary key)");let S=`${V.endsWith("s")?V.slice(0,-1):V}_id`;i(S,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${V} WHERE ${V}.${D} = ${j}.${S}`;if(E){let p=E({where:(u,b,d)=>{return i(u,"relationship subquery condition"),`${V}.${u} ${TZ(b,"whereHas callback")} ${M8(d)}`}});if(p)k+=` AND ${p}`}return k},Z$=(j,V,D,E,S,k)=>{i(j,"relationship subquery (parent table)"),i(V,"relationship subquery (target table)"),i(D,"relationship subquery (primary key)"),i(E,"relationship subquery (target primary key)");let g=k&&Y?t8(Y,j,k,{singularize:FZ,models:Y.models}):null,p=FZ(j),u=FZ(V),b=g?.pivotTable??[p,u].sort().join("_"),d=g?.fkParent??`${p}_id`,o=g?.fkRelated??`${u}_id`;i(b,"relationship subquery (pivot table)"),i(d,"relationship subquery (foreign key A)"),i(o,"relationship subquery (foreign key B)");let JZ=`SELECT 1 FROM ${b} JOIN ${V} ON ${V}.${E} = ${b}.${o} WHERE ${b}.${d} = ${j}.${D}`;if(S){let t=S({where:(NZ,cZ,iZ)=>{return i(NZ,"relationship subquery condition"),`${V}.${NZ} ${TZ(cZ,"whereHas callback")} ${M8(iZ)}`}});if(t)JZ+=` AND ${t}`}return JZ},MJ=(j,V,D)=>{i(j,"withCount (parent table)"),i(V,"withCount (target table)"),i(D,"withCount (primary key)");let E=`${j.endsWith("s")?j.slice(0,-1):j}_id`;return i(E,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${V} WHERE ${V}.${E} = ${j}.${D})`},wJ=(j,V,D,E)=>{i(j,"withCount (parent table)"),i(V,"withCount (target table)"),i(D,"withCount (primary key)");let S=E&&Y?t8(Y,j,E,{singularize:FZ,models:Y.models}):null,k=FZ(j),g=FZ(V),p=S?.pivotTable??[k,g].sort().join("_"),u=S?.fkParent??`${k}_id`;return i(p,"withCount (pivot table)"),i(u,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${p} WHERE ${p}.${u} = ${j}.${D})`},$$=(j,V,D)=>{if(!Y)return;i(D,`with${j[0]}${j.slice(1).toLowerCase()} (column)`);let E=String(_),S=Y.relations?.[E];if(!S)return;let k=Object.entries(S).find(([t,NZ])=>NZ&&typeof NZ==="object"&&(V in NZ));if(!k)return;let[g,p]=k,u=p[V],b=typeof u==="string"?u:u?.model||u?.target||u,d=Y.modelToTable[b]||b,o=Y.primaryKeys[E]??"id";i(d,`with${j} (target table)`);let JZ=`${j}(${d}.${D})`,SZ;if(g==="hasMany"||g==="hasOne"){let t=`${E.endsWith("s")?E.slice(0,-1):E}_id`;i(t,`with${j} (foreign key)`),SZ=`(SELECT ${JZ} FROM ${d} WHERE ${d}.${t} = ${E}.${o})`}else if(g==="belongsToMany"){let t=Y?t8(Y,E,V,{singularize:FZ,models:Y.models}):null,NZ=FZ(E),cZ=FZ(d),iZ=t?.pivotTable??[NZ,cZ].sort().join("_"),dZ=t?.fkParent??`${NZ}_id`,GZ=t?.fkRelated??`${cZ}_id`,P9=Y.primaryKeys[d]??"id";i(iZ,`with${j} (pivot table)`),i(dZ,`with${j} (foreign key)`),i(GZ,`with${j} (related key)`),SZ=`(SELECT ${JZ} FROM ${iZ} JOIN ${d} ON ${d}.${P9} = ${iZ}.${GZ} WHERE ${iZ}.${dZ} = ${E}.${o})`}else return;N9(`${SZ} AS ${V}_${j.toLowerCase()}_${D}`)},b0=()=>{if(jZ.size===0)return;let j=[];for(let[V,D]of jZ.entries()){let E=$8(V);if(!E)continue;for(let k of D)i(k,"withPivot");let S=D.map((k)=>`${E.pivotTable}.${k} AS pivot_${k}`);j.push(...S)}if(j.length>0){let V=j.join(", ");N9(V)}};return new Proxy({distinct(){return K=K.replace(/^SELECT\s+/i,"SELECT DISTINCT "),P=null,this},distinctOn(...j){let V=j.map(String).join(", ");return K=K.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${V}) `),P=null,this},selectRaw(j){let V=Z9(j,"selectRaw(fragment)"),D=K.indexOf(" FROM ");if(D!==-1)K=`${K.substring(0,D)}, ${V}${K.substring(D)}`;else K+=`, ${V}`;return P=null,this},rowNumber(j="row_number",V,D){let E=[];if(V){let p=Array.isArray(V)?V:[V];E.push(`PARTITION BY ${p.join(", ")}`)}if(D&&D.length)E.push(`ORDER BY ${D.map(([p,u])=>`${p} ${u==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`ROW_NUMBER() ${E.length?`OVER (${E.join(" ")})`:"OVER ()"} AS ${j}`,g=K.indexOf(" FROM ");if(g!==-1)K=`${K.substring(0,g)}, ${k}${K.substring(g)}`;else K+=`, ${k}`;return P=null,this},denseRank(j="dense_rank",V,D){let E=Array.isArray(V)?V:V?[V]:[],S=[];if(E.length)S.push(`PARTITION BY ${E.join(", ")}`);if(D&&D.length)S.push(`ORDER BY ${D.map(([u,b])=>`${u} ${b==="desc"?"DESC":"ASC"}`).join(", ")}`);let g=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${j}`,p=K.indexOf(" FROM ");if(p!==-1)K=`${K.substring(0,p)}, ${g}${K.substring(p)}`;else K+=`, ${g}`;return P=null,this},rank(j="rank",V,D){let E=Array.isArray(V)?V:V?[V]:[],S=[];if(E.length)S.push(`PARTITION BY ${E.join(", ")}`);if(D&&D.length)S.push(`ORDER BY ${D.map(([u,b])=>`${u} ${b==="desc"?"DESC":"ASC"}`).join(", ")}`);let g=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${j}`,p=K.indexOf(" FROM ");if(p!==-1)K=`${K.substring(0,p)}, ${g}${K.substring(p)}`;else K+=`, ${g}`;return P=null,this},over(j,V,D={}){return Q8(j,V,D.partitionBy,D.orderBy),this},lag(j,V={}){let D=[j,String(V.offset??1)];if(V.defaultValue!==void 0)D.push(String(V.defaultValue));return Q8(`LAG(${D.join(", ")})`,V.alias??`${j}_lag`,V.partitionBy,V.orderBy),this},lead(j,V={}){let D=[j,String(V.offset??1)];if(V.defaultValue!==void 0)D.push(String(V.defaultValue));return Q8(`LEAD(${D.join(", ")})`,V.alias??`${j}_lead`,V.partitionBy,V.orderBy),this},sumOver(j,V={}){return Q8(`SUM(${j})`,V.alias??`${j}_sum`,V.partitionBy,V.orderBy),this},avgOver(j,V={}){return Q8(`AVG(${j})`,V.alias??`${j}_avg`,V.partitionBy,V.orderBy),this},countOver(j="*",V={}){return Q8(`COUNT(${j})`,V.alias??"count_over",V.partitionBy,V.orderBy),this},minOver(j,V={}){return Q8(`MIN(${j})`,V.alias??`${j}_min`,V.partitionBy,V.orderBy),this},maxOver(j,V={}){return Q8(`MAX(${j})`,V.alias??`${j}_max`,V.partitionBy,V.orderBy),this},firstValue(j,V={}){return Q8(`FIRST_VALUE(${j})`,V.alias??`${j}_first`,V.partitionBy,V.orderBy),this},lastValue(j,V={}){return Q8(`LAST_VALUE(${j})`,V.alias??`${j}_last`,V.partitionBy,V.orderBy),this},selectAll(){return this},select(j){if(!j)return this;let V=Array.isArray(j)?j:[j];if(V.length===0)return this;let D=V.map(PX),E=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(K),S=E?E[1]:"",k=K.indexOf(" FROM ");if(k!==-1)K=`SELECT ${S}${D.join(", ")}${K.substring(k)}`;else K=`SELECT ${S}${D.join(", ")} FROM ${_}`;return P=null,this},addSelect(...j){if(!j.length)return this;let V=j.map(PX),D=K.indexOf(" FROM ");if(D!==-1)K=`${K.substring(0,D)}, ${V.join(", ")}${K.substring(D)}`;else K+=`, ${V.join(", ")}`;return P=null,this},with(...j){if(!Y||!j||j.length===0)return this;let V=[];for(let b of j){if(!b)continue;if(typeof b==="string")V.push({name:b});else if(typeof b==="object"&&!Array.isArray(b))for(let[d,o]of Object.entries(b))if(typeof o==="function")V.push({name:d,callback:o});else V.push({name:d})}if(V.length===0)return this;let D=f.relations.maxEagerLoad??50;if(V.length>D)throw Error(`[query-builder] Too many relationships to eager load (${V.length}). Maximum allowed: ${D}`);let E=String(_),S=new Set,k=new Set,g=new Map,p=(b)=>{let d=Y.relations?.[b];if(!d)return[];return[...Object.keys(d.hasOne||{}),...Object.keys(d.hasMany||{}),...Object.keys(d.belongsTo||{}),...Object.keys(d.belongsToMany||{}),...Object.keys(d.hasOneThrough||{}),...Object.keys(d.hasManyThrough||{}),...Object.keys(d.morphOne||{}),...Object.keys(d.morphMany||{}),...Object.keys(d.morphToMany||{}),...Object.keys(d.morphedByMany||{})]},u=(b,d,o=0,JZ)=>{let SZ=f.relations.maxDepth??10;if(o>=SZ)throw Error(`[query-builder] Maximum relationship depth (${SZ}) exceeded at '${d}'. Consider using separate queries or increasing maxDepth.`);let t=Y.relations?.[b];if(!t)return b;let NZ=(UZ)=>{if(f.softDeletes?.enabled&&f.softDeletes?.defaultFilter){let zZ=f.softDeletes.column||"deleted_at";return` AND ${UZ}.${zZ} IS NULL`}return""},cZ=(UZ)=>{if(!JZ)return"";let zZ=[],IZ=(AZ,lZ,_8)=>{i(String(AZ),"with() constraint column");let U9=TZ(lZ,"with() constraint operator");zZ.push(`${UZ}.${String(AZ)} ${U9} ${M8(_8)}`)},BZ=(AZ)=>()=>{throw Error(`[query-builder] with('${d}', ...): ${AZ} 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.)`)},wZ={where:(AZ,lZ,_8)=>{if(Array.isArray(AZ))IZ(AZ[0],AZ[1],AZ[2]);else if(AZ&&typeof AZ==="object")for(let U9 of Object.keys(AZ))IZ(U9,"=",AZ[U9]);else if(lZ!==void 0&&_8!==void 0)IZ(AZ,lZ,_8);else if(lZ!==void 0)IZ(AZ,"=",lZ);return wZ},whereIn:(AZ,lZ)=>{return i(String(AZ),"with() constraint column"),zZ.push(`${UZ}.${String(AZ)} IN (${lZ.map(M8).join(", ")})`),wZ},whereNull:(AZ)=>{return i(String(AZ),"with() constraint column"),zZ.push(`${UZ}.${String(AZ)} IS NULL`),wZ},whereNotNull:(AZ)=>{return i(String(AZ),"with() constraint column"),zZ.push(`${UZ}.${String(AZ)} IS NOT NULL`),wZ},orderBy:BZ("orderBy()"),limit:BZ("limit()"),offset:BZ("offset()"),take:BZ("take()")};return JZ(wZ),zZ.length?` AND ${zZ.join(" AND ")}`:""},iZ=()=>{let UZ=(BZ)=>{let wZ=BZ?.[d];return wZ?Y.modelToTable[wZ]:void 0},zZ=(BZ)=>{let wZ=BZ?.[d],AZ=typeof wZ==="string"?wZ:wZ?.model;return AZ?Y.modelToTable[AZ]:void 0},IZ=(BZ)=>{let wZ=BZ?.[d];return wZ?.target?Y.modelToTable[wZ.target]:void 0};return UZ(t?.hasOne)||UZ(t?.hasMany)||UZ(t?.belongsTo)||zZ(t?.belongsToMany)||IZ(t?.hasOneThrough)||IZ(t?.hasManyThrough)||UZ(t?.morphOne)||UZ(t?.morphMany)||UZ(t?.morphToMany)||UZ(t?.morphedByMany)},dZ=iZ()??(Y.modelToTable[d]||Y.tableToModel[d]?Y.modelToTable[d]??d:d),GZ=String(dZ);if(!dZ||!iZ()&&!Y.modelToTable[d]&&!Y.tableToModel[d]){let UZ=p(b);if(UZ.length>0&&!UZ.includes(d)){let zZ=` Available relationships: ${UZ.join(", ")}`;throw Error(`[query-builder] Relationship '${d}' not found on table '${b}'.${zZ}`)}}if(f.relations.detectCycles!==!1){let UZ=`${b}->${GZ}`;if(S.has(UZ))throw Error(`[query-builder] Circular relationship detected: ${UZ}. This would cause an infinite loop.`);S.add(UZ)}if(!GZ||GZ===b)return b;let P9=t?.hasOneThrough?.[d]||t?.hasManyThrough?.[d];if(P9){let{through:UZ,target:zZ}=P9,IZ=Y.modelToTable[UZ]||UZ,BZ=Y.modelToTable[zZ]||zZ,wZ=Y.primaryKeys[b]??"id",AZ=Y.primaryKeys[IZ]??"id",lZ=`${FZ(b)}_id`,_8=`${FZ(IZ)}_id`;return x(`LEFT JOIN ${IZ} ON ${IZ}.${lZ} = ${b}.${wZ} LEFT JOIN ${BZ} ON ${BZ}.${_8} = ${IZ}.${AZ}`),m.add(IZ),m.add(BZ),BZ}if(Boolean(t?.belongsToMany?.[d])){let UZ=t8(Y,b,d,{singularize:FZ,models:Y.models}),zZ=UZ?.pivotTable??[FZ(b),FZ(GZ)].sort().join("_"),IZ=Y.primaryKeys[b]??"id",BZ=Y.primaryKeys[GZ]??"id",wZ=UZ?.fkParent??`${FZ(b)}_id`,AZ=UZ?.fkRelated??`${FZ(GZ)}_id`;return x(`LEFT JOIN ${zZ} ON ${zZ}.${wZ} = ${b}.${IZ} LEFT JOIN ${GZ} ON ${GZ}.${BZ} = ${zZ}.${AZ}${cZ(GZ)}`),m.add(zZ),m.add(GZ),GZ}if(Boolean(t?.morphToMany?.[d])){let UZ=d,zZ=`${FZ(GZ)}_${UZ}`,IZ=Y.primaryKeys[b]??"id",BZ=Y.primaryKeys[GZ]??"id",wZ=`${UZ}_type`,AZ=`${UZ}_id`,lZ=`${FZ(GZ)}_id`,_8=M8(Y.tableToModel[b]||b);return x(`LEFT JOIN ${zZ} ON ${zZ}.${AZ} = ${b}.${IZ} AND ${zZ}.${wZ} = ${_8} LEFT JOIN ${GZ} ON ${GZ}.${BZ} = ${zZ}.${lZ}`),m.add(zZ),m.add(GZ),GZ}if(Boolean(t?.morphedByMany?.[d])){let UZ=t.morphedByMany?.[d]||d,zZ=Y.modelToTable[UZ]||UZ,IZ=FZ(b),BZ=`${FZ(zZ)}_${IZ}`,wZ=Y.primaryKeys[b]??"id",AZ=Y.primaryKeys[zZ]??"id",lZ=`${IZ}_type`,_8=`${IZ}_id`,U9=`${FZ(zZ)}_id`,TJ=M8(Y.tableToModel[zZ]||zZ);return x(`LEFT JOIN ${BZ} ON ${BZ}.${U9} = ${b}.${wZ} LEFT JOIN ${zZ} ON ${zZ}.${AZ} = ${BZ}.${_8} AND ${BZ}.${lZ} = ${TJ}`),m.add(BZ),m.add(zZ),zZ}if(Boolean(t?.belongsTo?.[d])){let UZ=`${FZ(GZ)}_id`,zZ=Y.primaryKeys[GZ]??"id";return x(`LEFT JOIN ${GZ} ON ${b}.${UZ} = ${GZ}.${zZ}${cZ(GZ)}`),m.add(GZ),GZ}let CJ=Boolean(t?.morphOne?.[d]),SJ=Boolean(t?.morphMany?.[d]);if(CJ||SJ){let UZ=`${d}_type`,zZ=`${d}_id`,IZ=Y.primaryKeys[b]??"id",BZ=M8(Y.tableToModel[b]||b);return x(`LEFT JOIN ${GZ} ON ${GZ}.${zZ} = ${b}.${IZ} AND ${GZ}.${UZ} = ${BZ}`),m.add(GZ),GZ}let NJ=`${FZ(b)}_id`,PJ=Y.primaryKeys[b]??"id",qJ=`${NZ(GZ)}${cZ(GZ)}`;return x(`LEFT JOIN ${GZ} ON ${GZ}.${NJ} = ${b}.${PJ}${qJ}`),m.add(GZ),GZ};for(let b of V){let d=b.name.trim();if(b.callback)g.set(d,b.callback);let o=d.split("."),JZ=E,SZ=0;for(let t of o){if(!t||t.trim().length===0)continue;let NZ=t.trim(),cZ=g.get(NZ);JZ=u(JZ,NZ,SZ,cZ)||JZ,SZ++}k.add(d)}if(jZ.size>0){let b=[];for(let[d,o]of jZ.entries()){let JZ=$8(d);if(!JZ)continue;let SZ=o.map((t)=>`${JZ.pivotTable}.${t} AS pivot_${t}`);b.push(...SZ)}if(b.length>0){let d=b.join(", ");N9(d)}}return P=null,this},whereHas(j,V){if(!Y)return this;let D=String(_),E=Y.relations?.[D];if(!E)throw Error(`[query-builder] No relationships defined for table '${D}'`);let S=Object.entries(E).find(([o,JZ])=>JZ&&typeof JZ==="object"&&(j in JZ));if(!S)throw Error(`[query-builder] Relationship '${j}' not found on table '${D}'`);let[k,g]=S,p=g[j],u=typeof p==="string"?p:p?.model||p?.target||p,b=Y.modelToTable[u]||u,d;if(k==="hasMany"||k==="hasOne"){let o=Y.primaryKeys[D]??"id";d=t9(D,b,o,V)}else if(k==="belongsTo"){let o=Y.primaryKeys[b]??"id";d=e9(D,b,o,V)}else if(k==="belongsToMany"){let o=Y.primaryKeys[D]??"id",JZ=Y.primaryKeys[b]??"id";d=Z$(D,b,o,JZ,V,j)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereHas`);return M("WHERE",`EXISTS (${d})`),this},whereDoesntHave(j,V){if(!Y)return this;let D=String(_),E=Y.relations?.[D];if(!E)throw Error(`[query-builder] No relationships defined for table '${D}'`);let S=Object.entries(E).find(([o,JZ])=>JZ&&typeof JZ==="object"&&(j in JZ));if(!S)throw Error(`[query-builder] Relationship '${j}' not found on table '${D}'`);let[k,g]=S,p=g[j],u=typeof p==="string"?p:p?.model||p?.target||p,b=Y.modelToTable[u]||u,d;if(k==="hasMany"||k==="hasOne"){let o=Y.primaryKeys[D]??"id";d=t9(D,b,o,V)}else if(k==="belongsTo"){let o=Y.primaryKeys[b]??"id";d=e9(D,b,o,V)}else if(k==="belongsToMany"){let o=Y.primaryKeys[D]??"id",JZ=Y.primaryKeys[b]??"id";d=Z$(D,b,o,JZ,V,j)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereDoesntHave`);return M("WHERE",`NOT EXISTS (${d})`),this},has(j){if(!Y)return this;let V=String(_),D=Y.relations?.[V];if(!D)throw Error(`[query-builder] No relationships defined for table '${V}'`);let E=Object.entries(D).find(([d,o])=>o&&typeof o==="object"&&(j in o));if(!E)throw Error(`[query-builder] Relationship '${j}' not found on table '${V}'`);let[S,k]=E,g=k[j],p=typeof g==="string"?g:g?.model||g?.target||g,u=Y.modelToTable[p]||p,b;if(S==="hasMany"||S==="hasOne"){let d=Y.primaryKeys[V]??"id";b=t9(V,u,d)}else if(S==="belongsTo"){let d=Y.primaryKeys[u]??"id";b=e9(V,u,d)}else if(S==="belongsToMany"){let d=Y.primaryKeys[V]??"id",o=Y.primaryKeys[u]??"id";b=Z$(V,u,d,o,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return M("WHERE",`EXISTS (${b})`),this},doesntHave(j){if(!Y)return this;let V=String(_),D=Y.relations?.[V];if(!D)throw Error(`[query-builder] No relationships defined for table '${V}'`);let E=Object.entries(D).find(([d,o])=>o&&typeof o==="object"&&(j in o));if(!E)throw Error(`[query-builder] Relationship '${j}' not found on table '${V}'`);let[S,k]=E,g=k[j],p=typeof g==="string"?g:g?.model||g?.target||g,u=Y.modelToTable[p]||p,b;if(S==="hasMany"||S==="hasOne"){let d=Y.primaryKeys[V]??"id";b=t9(V,u,d)}else if(S==="belongsTo"){let d=Y.primaryKeys[u]??"id";b=e9(V,u,d)}else if(S==="belongsToMany"){let d=Y.primaryKeys[V]??"id",o=Y.primaryKeys[u]??"id";b=Z$(V,u,d,o,void 0,j)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return M("WHERE",`NOT EXISTS (${b})`),this},withCount(...j){if(!Y||!j||j.length===0)return this;let V=String(_);for(let D of j){let E=Y.relations?.[V];if(!E)continue;let S=Object.entries(E).find(([SZ,t])=>t&&typeof t==="object"&&(D in t));if(!S)continue;let[k,g]=S,p=g[D],u=typeof p==="string"?p:p?.model||p?.target||p,b=Y.modelToTable[u]||u,d=Y.primaryKeys[V]??"id",o;if(k==="hasMany"||k==="hasOne")o=MJ(V,b,d);else if(k==="belongsToMany")o=wJ(V,b,d,D);else continue;let JZ=`${D}_count`;N9(`${o} AS ${JZ}`)}return this},withSum(j,V){return $$("SUM",j,V),this},withAvg(j,V){return $$("AVG",j,V),this},withMax(j,V){return $$("MAX",j,V),this},withMin(j,V){return $$("MIN",j,V),this},applyPivotColumns(){return b0(),this},withPivot(j,...V){if(!Y)return this;let D=String(_),E=$8(j);if(!E)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${D}'`);let S=V&&V.length>0?V:E.hasConfig?E.pivotColumns:[];if(S.length===0)return this;if(jZ.set(j,S),E.hasConfig)mZ.add(j);return b0(),this},wherePivot(j,V,D,E){if(!Y)return this;let S=$8(j);if(!S)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);i(S.pivotTable,"wherePivot (pivot table)"),i(V,"wherePivot (column)"),F8(S);let k=E===void 0?"=":String(D),g=E===void 0?D:E,p=B.length+1,u=`${S.pivotTable}.${V} ${k} ${s(p)}`;if(B.push(g),w("AND",u),S.hasConfig)mZ.add(j);return this},wherePivotIn(j,V,D){if(!Y||!Array.isArray(D))return this;let E=$8(j);if(!E)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);i(E.pivotTable,"wherePivotIn (pivot table)"),i(V,"wherePivotIn (column)"),F8(E);let S=PZ(D.length,B.length+1),k=tZ(`${E.pivotTable}.${V}`,D,!1,S);if(B.push(...D),w("AND",k),E.hasConfig)mZ.add(j);return this},wherePivotNotIn(j,V,D){if(!Y||!Array.isArray(D)||D.length===0)return this;let E=$8(j);if(!E)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);i(E.pivotTable,"wherePivotNotIn (pivot table)"),i(V,"wherePivotNotIn (column)"),F8(E);let S=PZ(D.length,B.length+1),k=`${E.pivotTable}.${V} NOT IN (${S})`;if(B.push(...D),w("AND",k),E.hasConfig)mZ.add(j);return this},wherePivotNull(j,V){if(!Y)return this;let D=$8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);if(i(D.pivotTable,"wherePivotNull (pivot table)"),i(V,"wherePivotNull (column)"),F8(D),w("AND",`${D.pivotTable}.${V} IS NULL`),D.hasConfig)mZ.add(j);return this},wherePivotNotNull(j,V){if(!Y)return this;let D=$8(j);if(!D)throw Error(`[query-builder] Relationship '${j}' is not a belongsToMany relationship on table '${String(_)}'`);if(i(D.pivotTable,"wherePivotNotNull (pivot table)"),i(V,"wherePivotNotNull (column)"),F8(D),w("AND",`${D.pivotTable}.${V} IS NOT NULL`),D.hasConfig)mZ.add(j);return this},where(j,V,D){if(typeof j==="string"&&V!==void 0){i(String(j),"where(column)"),TZ(V,"where(operator)");let E=String(V).toLowerCase();if(E==="in"||E==="not in"){let k=Array.isArray(D)?D:[D],g=PZ(k.length,B.length+1),p=tZ(String(j),k,E==="not in",g);return B.push(...k),w("AND",p),this}let S=B.length+1;return B.push(D),w("AND",`${String(j)} ${String(V)} ${s(S)}`),this}if(Array.isArray(j)){let[E,S,k]=j,g=String(E);i(g,"where(column)");let p=TZ(S,"where(operator)");if(p==="in"||p==="not in"){let u=Array.isArray(k)?k:[k],b=PZ(u.length,B.length+1),d=tZ(g,u,p==="not in",b);B.push(...u),w("AND",d)}else{let u=B.length+1;B.push(k),w("AND",`${g} ${p} ${s(u)}`)}return this}if(j&&typeof j==="object"&&!w8(j)){let E=j,S=Object.keys(E),k=[];for(let g of S){i(g,"where(column)");let p=E[g];if(Array.isArray(p)){let u=PZ(p.length,B.length+1);k.push(tZ(g,p,!1,u)),B.push(...p)}else{let u=B.length+1;k.push(`${g} = ${s(u)}`),B.push(p)}}if(k.length>0)w("AND",k.length>1?`(${k.join(" AND ")})`:k[0]);return this}if(w8(j))return w("AND",j.raw),this;if(typeof j==="function")return c("AND",j),this;if(j===void 0||j===null)throw TypeError("where() was called with no condition.");if(typeof j==="string")throw TypeError(`where(${JSON.stringify(j)}) 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 j}.`)},whereNull(j){return i(String(j),"whereNull(column)"),w("AND",`${String(j)} IS NULL`),this},whereNotNull(j){return i(String(j),"whereNotNull(column)"),w("AND",`${String(j)} IS NOT NULL`),this},orWhereNull(j){return i(String(j),"orWhereNull(column)"),w("OR",`${String(j)} IS NULL`),this},orWhereNotNull(j){return i(String(j),"orWhereNotNull(column)"),w("OR",`${String(j)} IS NOT NULL`),this},whereBetween(j,V,D){i(String(j),"whereBetween(column)");let E=B.length+1;return B.push(V,D),w("AND",`${String(j)} BETWEEN ${s(E)} AND ${s(E+1)}`),this},orWhereBetween(j,V,D){i(String(j),"orWhereBetween(column)");let E=B.length+1;return B.push(V,D),w("OR",`${String(j)} BETWEEN ${s(E)} AND ${s(E+1)}`),this},whereExists(j){return w("AND",`EXISTS (${j.toSQL()})`),this},orWhereExists(j){return w("OR",`EXISTS (${j.toSQL()})`),this},whereGroup(j){return c("AND",j),this},orWhereGroup(j){return c("OR",j),this},__whereState(){return{body:e8(I),params:[...B]}},whereJsonContains(j,V){i(String(j),"whereJsonContains(column)");let D=f.dialect,E=B.length+1;if(D==="postgres"){let k=typeof V==="number"||typeof V==="boolean"?`to_jsonb(${s(E)})`:s(E);if(f.sql?.jsonContainsMode==="function")w("AND",`jsonb_contains(${j}, ${k})`);else w("AND",`${j} @> ${k}`);B.push(V)}else if(YZ(D))w("AND",`JSON_CONTAINS(${j}, ${s(E)})`),B.push(JSON.stringify(V));else if(Array.isArray(V)){let S=V.map((k,g)=>`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${s(E+g)})`);w("AND",`(${S.join(" AND ")})`);for(let k of V)B.push(k)}else if(V!==null&&typeof V==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else w("AND",`EXISTS (SELECT 1 FROM json_each(${j}) WHERE json_each.value = ${s(E)})`),B.push(V);return this},whereJsonPath(j,V,D){if(TZ(V,"whereJsonPath(op)"),typeof j!=="string"||j.length===0||j.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof j==="string"?`'${j.slice(0,32)}...'`:typeof j}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(j))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${j}' \u2014 contains characters outside the allowed JSON-path set`);let E=f.dialect,S=B.length+1;if(E==="postgres")w("AND",`${j} ${V} ${s(S)}`);else if(YZ(E))w("AND",`JSON_EXTRACT(${j}) ${V} ${s(S)}`);else w("AND",`json_extract(${j}) ${V} ${s(S)}`);return B.push(D),this},whereLike(j,V,D=!1){let E=s(B.length+1);return M("WHERE",`${D?String(j):`LOWER(${String(j)})`} LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},whereILike(j,V){let D=s(B.length+1);if(f.dialect==="postgres")M("WHERE",`${String(j)} ILIKE ${D}`);else M("WHERE",`LOWER(${String(j)}) LIKE LOWER(${D})`);return B.push(V),P=null,this},orWhereLike(j,V,D=!1){let E=s(B.length+1);return M("OR",`${D?String(j):`LOWER(${String(j)})`} LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},orWhereILike(j,V){let D=s(B.length+1);if(f.dialect==="postgres")M("OR",`${String(j)} ILIKE ${D}`);else M("OR",`LOWER(${String(j)}) LIKE LOWER(${D})`);return B.push(V),P=null,this},whereNotLike(j,V,D=!1){let E=s(B.length+1);return M("WHERE",`${D?String(j):`LOWER(${String(j)})`} NOT LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},whereNotILike(j,V){let D=s(B.length+1);if(f.dialect==="postgres")M("WHERE",`${String(j)} NOT ILIKE ${D}`);else M("WHERE",`LOWER(${String(j)}) NOT LIKE LOWER(${D})`);return B.push(V),P=null,this},orWhereNotLike(j,V,D=!1){let E=s(B.length+1);return M("OR",`${D?String(j):`LOWER(${String(j)})`} NOT LIKE ${D?E:`LOWER(${E})`}`),B.push(V),P=null,this},orWhereNotILike(j,V){let D=s(B.length+1);if(f.dialect==="postgres")M("OR",`${String(j)} NOT ILIKE ${D}`);else M("OR",`LOWER(${String(j)}) NOT LIKE LOWER(${D})`);return B.push(V),P=null,this},whereAny(j,V,D){if(j.length===0)return w("AND",`(${NX})`),this;let E=B.length+1,S=j.map((k,g)=>`${k} ${V} ${s(E+g)}`);for(let k=0;k<j.length;k++)B.push(D);return w("AND",`(${S.join(" OR ")})`),this},whereAll(j,V,D){if(j.length===0)return this;let E=B.length+1,S=j.map((k,g)=>`${k} ${V} ${s(E+g)}`);for(let k=0;k<j.length;k++)B.push(D);return w("AND",`(${S.join(" AND ")})`),this},whereNone(j,V,D){if(j.length===0)return this;let E=B.length+1,S=j.map((k,g)=>`${k} ${V} ${s(E+g)}`);for(let k=0;k<j.length;k++)B.push(D);return w("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(j,V,D){i(String(j),"whereNotBetween(column)");let E=B.length+1;return B.push(V,D),w("AND",`${j} NOT BETWEEN ${s(E)} AND ${s(E+1)}`),this},whereDate(j,V,D){i(j,"whereDate(column)");let E=D instanceof Date?D.toISOString():typeof D==="string"?D:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof D}`)})(),S=B.length+1;return B.push(E),w("AND",`${j} ${V} ${s(S)}`),this},whereRaw(j){return w("AND",Z9(j,"whereRaw(fragment)")),this},orWhereRaw(j){return w("OR",Z9(j,"orWhereRaw(fragment)")),this},whereColumn(j,V,D){return i(j,"whereColumn(left)"),i(D,"whereColumn(right)"),w("AND",`${j} ${V} ${D}`),this},orWhereColumn(j,V,D){return i(j,"orWhereColumn(left)"),i(D,"orWhereColumn(right)"),w("OR",`${j} ${V} ${D}`),this},whereIn(j,V){if(i(String(j),"whereIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!1,D);B.push(...V),w("AND",E)}else w("AND",`${j} IN (${String(V.toSQL())})`);return this},orWhereIn(j,V){if(i(String(j),"orWhereIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!1,D);B.push(...V),w("OR",E)}else w("OR",`${j} IN (${String(V.toSQL())})`);return this},whereNotIn(j,V){if(i(String(j),"whereNotIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!0,D);B.push(...V),w("AND",E)}else w("AND",`${j} NOT IN (${String(V.toSQL())})`);return this},orWhereNotIn(j,V){if(i(String(j),"orWhereNotIn(column)"),Array.isArray(V)){let D=PZ(V.length,B.length+1),E=tZ(j,V,!0,D);B.push(...V),w("OR",E)}else w("OR",`${j} NOT IN (${String(V.toSQL())})`);return this},whereNested(j){let V=j.toSQL?String(j.toSQL()):String(j);return w("AND",`(${V})`),this},orWhereNested(j){let V=j.toSQL?String(j.toSQL()):String(j);return w("OR",`(${V})`),this},andWhere(j,V,D){return l(this,"AND","andWhere",j,V,D)},orWhere(j,V,D){return l(this,"OR","orWhere",j,V,D)},orderBy(j,V="asc"){let D=V==="asc"?"ASC":"DESC";return K=WZ.ORDER_BY.test(K)?`${K}, ${j} ${D}`:`${K} ORDER BY ${j} ${D}`,P=null,this},orderByDesc(j){return K=WZ.ORDER_BY.test(K)?`${K}, ${j} DESC`:`${K} ORDER BY ${j} DESC`,P=null,this},inRandomOrder(){let j=f.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return K=WZ.ORDER_BY.test(K)?`${K}, ${j}`:`${K} ORDER BY ${j}`,P=null,this},reorder(j,V="asc"){return K=K.replace(/ORDER BY[\s\S]*$/i,""),K+=` ORDER BY ${j} ${V==="asc"?"ASC":"DESC"}`,P=null,this},latest(j){let V=j??f.timestamps.defaultOrderColumn;return K=WZ.ORDER_BY.test(K)?`${K}, ${V} DESC`:`${K} ORDER BY ${V} DESC`,P=null,this},oldest(j){let V=j??f.timestamps.defaultOrderColumn;return K=WZ.ORDER_BY.test(K)?`${K}, ${V} ASC`:`${K} ORDER BY ${V} ASC`,P=null,this},limit(j){if(!Number.isFinite(j)||j<0||!Number.isInteger(j))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${j}`);return K=WZ.LIMIT.test(K)?K.replace(WZ.LIMIT,` LIMIT ${j}`):`${K} LIMIT ${j}`,P=null,this},offset(j){if(!Number.isFinite(j)||j<0||!Number.isInteger(j))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${j}`);return K=WZ.OFFSET.test(K)?K.replace(WZ.OFFSET,` OFFSET ${j}`):`${K} OFFSET ${j}`,P=null,this},join(j,V,D,E){return i(j,"join(table)"),J8(V,"join(onLeft)"),J8(E,"join(onRight)"),TZ(D,"join(operator)"),x(`JOIN ${j} ON ${V} ${D} ${E}`),m.add(j),this},joinSub(j,V,D,E,S){return i(V,"joinSub(alias)"),J8(D,"joinSub(onLeft)"),J8(S,"joinSub(onRight)"),TZ(E,"joinSub(operator)"),x(`JOIN (${String(j.toSQL())}) AS ${V} ON ${D} ${E} ${S}`),m.add(V),this},innerJoin(j,V,D,E){return i(j,"innerJoin(table)"),J8(V,"innerJoin(onLeft)"),J8(E,"innerJoin(onRight)"),TZ(D,"innerJoin(operator)"),x(`INNER JOIN ${j} ON ${V} ${D} ${E}`),m.add(j),this},leftJoin(j,V,D,E){return i(j,"leftJoin(table)"),J8(V,"leftJoin(onLeft)"),J8(E,"leftJoin(onRight)"),TZ(D,"leftJoin(operator)"),x(`LEFT JOIN ${j} ON ${V} ${D} ${E}`),m.add(j),this},leftJoinSub(j,V,D,E,S){return i(V,"leftJoinSub(alias)"),J8(D,"leftJoinSub(onLeft)"),J8(S,"leftJoinSub(onRight)"),TZ(E,"leftJoinSub(operator)"),x(`LEFT JOIN (${String(j.toSQL())}) AS ${V} ON ${D} ${E} ${S}`),m.add(V),this},rightJoin(j,V,D,E){return i(j,"rightJoin(table)"),J8(V,"rightJoin(onLeft)"),J8(E,"rightJoin(onRight)"),TZ(D,"rightJoin(operator)"),x(`RIGHT JOIN ${j} ON ${V} ${D} ${E}`),m.add(j),this},crossJoin(j){return i(j,"crossJoin(table)"),x(`CROSS JOIN ${j}`),m.add(j),this},crossJoinSub(j,V){return i(V,"crossJoinSub(alias)"),x(`CROSS JOIN (${String(j.toSQL())}) AS ${V}`),m.add(V),this},selectAllRelations(){if(!X)return this;let j=String(_),V=Object.keys(X[j]?.columns??{}),D=[];if(V.length>0)D.push(L`${L(j)}.*`);for(let E of m){let S=Object.keys(X[E]?.columns??{});for(let k of S){let g=f.aliasing.relationColumnAliasFormat==="camelCase"?`${E}_${k}`.replace(/_([a-z])/g,(p,u)=>u.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${E}.${k}`:`${E}_${k}`;D.push(L`${L(`${E}.${k}`)} AS ${L(g)}`)}}if(D.length>0){let E=V.length>0?`${j}.*`:"",S=[];for(let p of m){let u=Object.keys(X[p]?.columns??{});for(let b of u){let d=f.aliasing.relationColumnAliasFormat==="camelCase"?`${p}_${b}`.replace(/_([a-z])/g,(o,JZ)=>JZ.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${p}.${b}`:`${p}_${b}`;S.push(`${p}.${b} AS ${d}`)}}let k=[E,...S].filter(Boolean).join(", "),g=K.indexOf(" FROM ");if(g!==-1)K=`SELECT ${k}${K.substring(g)}`;else K=`SELECT ${k} FROM ${j}`;P=null}return this},groupBy(...j){if(j.length)K=WZ.GROUP_BY.test(K)?`${K}, ${j.join(", ")}`:`${K} GROUP BY ${j.join(", ")}`,P=null;return this},groupByRaw(j){let V=Z9(j,"groupByRaw(fragment)");return K=WZ.GROUP_BY.test(K)?`${K}, ${V}`:`${K} GROUP BY ${V}`,P=null,this},having(j){let V=/\bHAVING\b/i.test(K)?"AND":"HAVING";if(Array.isArray(j)){let D=B.length+1;K=`${K} ${V} ${j[0]} ${j[1]} ${s(D)}`,B.push(j[2]),P=null}else if(j&&typeof j==="object"&&!("raw"in j)){let D=Object.keys(j),E=D.length;if(E){let S=B.length,k=Array.from({length:E});for(let g=0;g<E;g++){let p=D[g];k[g]=`${p} = ${s(S+g+1)}`,B.push(j[p])}K=`${K} ${V} ${k.join(" AND ")}`,P=null}}else if(j&&typeof j.raw<"u")K+=` ${V} ${j.raw}`,P=null;return this},havingRaw(j){let V=Z9(j,"havingRaw(fragment)"),D=/\bHAVING\b/i.test(K)?"AND":"HAVING";return K+=` ${D} ${V}`,P=null,this},orderByRaw(j){let V=Z9(j,"orderByRaw(fragment)");return K=WZ.ORDER_BY.test(K)?`${K}, ${V}`:`${K} ORDER BY ${V}`,P=null,this},$call(j){return j(this),this},union(j){return r("UNION",j),this},unionAll(j){return r("UNION ALL",j),this},intersect(j){return r("INTERSECT",j),this},intersectAll(j){return r("INTERSECT ALL",j),this},except(j){return r("EXCEPT",j),this},exceptAll(j){return r("EXCEPT ALL",j),this},forPage(j,V){let D=Math.max(1,Math.floor(j)),E=Math.max(1,Math.floor(V));return K+=` LIMIT ${E} OFFSET ${(D-1)*E}`,P=null,this},toSQL(){let j=m9(y());return{sql:j,toString:()=>j,execute:()=>T().execute(),values:()=>T().values(),raw:()=>T().raw()}},async value(j){let V=L`${T()} LIMIT 1`,D=await Q(V,"select",{signal:h,timeoutMs:n}),[E]=D;return E?.[j]},async pluck(j,V){let D=await Q(T(),"select",{signal:h,timeoutMs:n});if(V){let E={};for(let S of D){let k=String(S?.[V]);if(Object.prototype.hasOwnProperty.call(E,k))throw Error(`[query-builder] pluck(${j}, ${V}): duplicate key '${k}' \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.`);E[k]=S?.[j]}return E}return D.map((E)=>E?.[j])},async exists(){let j=L`SELECT EXISTS (${T()}) as e`,V=await Q(j,"select",{signal:h,timeoutMs:n}),[D]=V;return Boolean(D?.e)},async doesntExist(){return!await this.exists()},async paginate(j,V=1,D={}){if(!Number.isFinite(j)||j<=0||!Number.isInteger(j))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${j}`);if(!Number.isFinite(V)||V<1||!Number.isInteger(V))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${V}`);if(D.tx){let o=m9(y()),JZ=[...B],SZ=await D.tx.unsafe(`SELECT COUNT(*) as c FROM (${o}) as sub`,JZ),t=Number(SZ?.[0]?.c??0),NZ=Math.max(1,Math.ceil(t/j)),cZ=Math.max(1,Math.min(V,NZ)),iZ=(cZ-1)*j;return{data:await D.tx.unsafe(`${o} LIMIT ${j} OFFSET ${iZ}`,JZ),meta:{perPage:j,page:cZ,total:t,lastPage:NZ}}}let E=L`SELECT COUNT(*) as c FROM (${T()}) as sub`,S=await Q(E,"select",{signal:h,timeoutMs:n}),[k]=S,g=Number(k?.c??0),p=Math.max(1,Math.ceil(g/j)),u=Math.max(1,Math.min(V,p)),b=(u-1)*j;return{data:await Q(L`${T()} LIMIT ${j} OFFSET ${b}`,"select",{signal:h,timeoutMs:n}),meta:{perPage:j,page:u,total:g,lastPage:p}}},async simplePaginate(j,V=1){let D=Math.max(1,V),E=(D-1)*j,S=await Q(L`${T()} LIMIT ${j+1} OFFSET ${E}`,"select",{signal:h,timeoutMs:n}),k=S.length>j;return{data:k?S.slice(0,j):S,meta:{perPage:j,page:D,hasMore:k}}},async cursorPaginate(j,V,D="id",E="asc"){if(!Number.isInteger(j)||j<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${j}`);let S=(Array.isArray(D)?D:[D]).map(String);for(let dZ of S)i(dZ,"cursorPaginate(column)");let k=E==="asc"?">":"<",g=E==="asc"?"ASC":"DESC",p=[...B],u="";if(V!==void 0&&V!==null)if(Array.isArray(D)){let dZ=V.map((GZ)=>{return p.push(GZ),s(p.length)});u=`(${S.join(", ")}) ${k} (${dZ.join(", ")})`}else p.push(V),u=`${S[0]} ${k} ${s(p.length)}`;let b=m9(u?y({conn:"AND",sql:u}):y()),d=S.map((dZ)=>`${dZ} ${g}`).join(", ");if(_6(b))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${d} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let o=p.length>0?$.unsafe(`${b} ORDER BY ${d} LIMIT ${j+1}`,p):$.unsafe(`${b} ORDER BY ${d} LIMIT ${j+1}`),JZ=await Q(o,"select",{signal:h,timeoutMs:n}),SZ=JZ.length>j,t=JZ.slice(0,j),NZ=t[t.length-1],cZ=SZ&&NZ?Array.isArray(D)?D.map((dZ)=>NZ[dZ]):NZ[D]:null,iZ=t.length?Array.isArray(D)?D.map((dZ)=>t[0]?.[dZ]):t[0]?.[D]:null;return{data:t,meta:{perPage:j,nextCursor:cZ??null,prevCursor:iZ}}},async chunk(j,V){let D=1;while(!0){let{data:E,meta:S}=await this.paginate(j,D);if(E.length===0)break;if(await V(E),D>=S.lastPage)break;D+=1}},async chunkById(j,V="id",D){let E;while(!0){let{data:S,meta:k}=await this.cursorPaginate(j,E,V,"asc");if(S.length===0)break;if(D)await D(S);if(E=k.nextCursor,!E)break}},async eachById(j,V="id",D){await this.chunkById(j,V,async(E)=>{for(let S of E)await D?.(S)})},withTimeout(j){return n=Math.max(1,Math.floor(j)),this},abort(j){return h=j,this},withTrashed(){return ZZ=!0,a=!1,this},onlyTrashed(){ZZ=!0,a=!0;let j=f.softDeletes?.column||"deleted_at",V=(S,k)=>{let g=S.toUpperCase(),p=0;for(let u=0;u<S.length;u++){let b=S[u];if(b==="(")p++;else if(b===")")p--;else if(p===0&&g.substring(u,u+5)==="WHERE"&&(u===0||/\s/.test(S[u-1]??""))&&/\s/.test(S[u+5]??""))return`${S.substring(0,u)}WHERE ${k} AND ${S.substring(u+6)}`}return`${S} WHERE ${k}`},D=`${_}.${j} IS NOT NULL`;K=V(K,D);let E=String(T());return P=L([V(E,D)]),this},scope(j,V){let D=String(_),S=Y?.scopes?.[D]?.[j];if(S)return S(this,V);return this},when(j,V,D){if(j)return V(this);if(D)return D(this);return this},tap(j){return j(this),this},dump(){return console.log(String(T())),this},dd(){throw console.log(String(T())),Error("Dump and Die")},cache(j=60000){return k8=j,DZ=!0,this},async explain(){let j=L`EXPLAIN ${T()}`;return await Q(j,"select",{signal:h,timeoutMs:n})},simple(){return T().simple()},toText(){return y()},async get(){let j=G(),V=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||d9(j));if(!f.softDeletes?.enabled&&!DZ&&!n&&!h&&!V){let g=$._prepareStatement;if(g){let p=g(y());return l8(B.length>0?p.all(...B):p.all())}}let D=y();if(P=B.length>0?$.unsafe(D,B):$.unsafe(D),!f.softDeletes?.enabled&&!DZ&&!n&&!h&&!V){let g=T()._stmt,p=T()._params;if(g)return l8(p&&p.length>0?g.all(...p):g.all());return l8(await T().execute())}if(!f.softDeletes?.enabled&&!DZ&&!n&&!h)return l8(await Q(T(),"select"));let E=T();if(f.softDeletes?.enabled&&f.softDeletes.defaultFilter&&!ZZ){let g=f.softDeletes.column,p=String(_);if((X?Boolean(X[p]?.columns?.[g]):!0)&&!WZ.DELETED_AT.test(y()))M("WHERE",`${String(g)} IS ${a?"NOT ":""}NULL`),E=T()}let S=DZ?`${String(E)}\x00${JSON.stringify(B)}`:"";if(DZ){let g=e$.get(S);if(g)return g}let k=await Q(E,"select",{signal:h,timeoutMs:n});if(DZ)e$.set(S,k,k8);return l8(k)},async executeTakeFirst(){let j=await Q(T(),"select",{signal:h,timeoutMs:n});return i8(Array.isArray(j)?j[0]:j)},async executeTakeFirstOrThrow(){let j=await this.executeTakeFirst();if(!j)throw Error("Record not found");return j},async first(){let j=G(),V=j&&(j.onQueryStart||j.onQueryEnd||j.onQueryError||j.startSpan||d9(j));if(!f.softDeletes?.enabled&&!DZ&&!n&&!h&&!V){let S=$._prepareStatement;if(S){let k=y(),g=k.includes(" LIMIT ")?k:`${k} LIMIT 1`,p=S(g),u=B.length>0?p.all(...B):p.all();return i8(u[0])}}let D=await Q(L`${T()} LIMIT 1`,"select",{signal:h,timeoutMs:n}),[E]=D;return i8(E)},async firstOrFail(){let j=await this.first();if(!j)throw Error("Record not found");return j},async find(j){let V=Y?.primaryKeys[String(_)]??"id",D=await Q(L`${T()} WHERE ${L(V)} = ${j} LIMIT 1`,"select",{signal:h,timeoutMs:n}),[E]=D;return E},async findOrFail(j){let V=await this.find(j);if(!V)throw Error("Record not found");return V},async findMany(j){let V=Y?.primaryKeys[String(_)]??"id";return await Q(L`${T()} WHERE ${L(String(V))} IN ${L(j)}`,"select",{signal:h,timeoutMs:n})},async*lazy(){let j,V=Y?.primaryKeys[String(_)]??"id";while(!0){let E=await(j==null?L`${T()} ORDER BY ${L(String(V))} ASC LIMIT 100`:L`${T()} WHERE ${L(String(V))} > ${j} ORDER BY ${L(String(V))} ASC LIMIT 100`).execute();if(E.length===0)break;for(let S of E)yield S;if(j=E[E.length-1]?.[V],j==null)break}},async*lazyById(){let j=Y?.primaryKeys[String(_)]??"id",V;while(!0){let E=await(V==null?L`${T()} ORDER BY ${L(String(j))} ASC LIMIT 100`:L`${T()} WHERE ${L(String(j))} > ${V} ORDER BY ${L(String(j))} ASC LIMIT 100`).execute();if(E.length===0)break;for(let S of E)yield S;if(V=E[E.length-1]?.[j],V==null)break}},pipe(j){return j(this)},async count(){let j=y(),V=j.indexOf(" FROM "),D=/ GROUP BY /i.test(j),E;if(D)E=`SELECT COUNT(*) as c FROM (${j}) AS _bqb_count_sub`;else if(V!==-1)E=`SELECT COUNT(*) as c${j.substring(V)}`;else E=`SELECT COUNT(*) as c FROM ${_}`;let S=G(),k=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||d9(S));if(!f.softDeletes?.enabled&&!DZ&&!n&&!h&&!k){let b=$._prepareStatement;if(b){let d=b(E),o=B.length>0?d.all(...B):d.all();return Number(o[0]?.c??0)}}let g=B.length>0?$.unsafe(E,B):$.unsafe(E),p=await Q(g,"select",{signal:h,timeoutMs:n}),[u]=p;return Number(u?.c??0)},async avg(j){let V=y(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT AVG(${j}) as a${V.substring(D)}`:`SELECT AVG(${j}) as a FROM ${_}`,S=G(),k=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||d9(S));if(!f.softDeletes?.enabled&&!DZ&&!n&&!h&&!k){let b=$._prepareStatement;if(b){let d=b(E),o=B.length>0?d.all(...B):d.all();return Number(o[0]?.a??0)}}let g=B.length>0?$.unsafe(E,B):$.unsafe(E),p=await Q(g,"select",{signal:h,timeoutMs:n}),[u]=p;return Number(u?.a??0)},async sum(j){let V=y(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT SUM(${j}) as s${V.substring(D)}`:`SELECT SUM(${j}) as s FROM ${_}`,S=B.length>0?$.unsafe(E,B):$.unsafe(E),k=await Q(S,"select",{signal:h,timeoutMs:n}),[g]=k;return Number(g?.s??0)},async max(j){let V=y(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT MAX(${j}) as m${V.substring(D)}`:`SELECT MAX(${j}) as m FROM ${_}`,S=B.length>0?$.unsafe(E,B):$.unsafe(E),k=await Q(S,"select",{signal:h,timeoutMs:n}),[g]=k;return g?.m},async min(j){let V=y(),D=V.indexOf(" FROM "),E=D!==-1?`SELECT MIN(${j}) as m${V.substring(D)}`:`SELECT MIN(${j}) as m FROM ${_}`,S=B.length>0?$.unsafe(E,B):$.unsafe(E),k=await Q(S,"select",{signal:h,timeoutMs:n}),[g]=k;return g?.m},lockForUpdate(){return K+=" FOR UPDATE",P=null,this},sharedLock(){let j=f.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return K+=` ${j}`,P=null,this},withCTE(j,V){return i(j,"withCTE(name)"),K=`WITH ${j} AS (${String(V.toSQL())}) ${K}`,P=null,this},withRecursive(j,V){return i(j,"withRecursive(name)"),K=`WITH RECURSIVE ${j} AS (${String(V.toSQL())}) ${K}`,P=null,this},execute(){return Q(T(),"select",{signal:h,timeoutMs:n})},values(){return T().values()},toParams(){return[...B]},__rawState(){return{sql:m9(y()),params:[...B]}},raw(){return T().raw()},get rows(){return},get row(){return},cancel(){try{T().cancel()}catch{}}},{get(j,V,D){let E=Reflect.get(j,V,D);if(E!==void 0)return E;if(typeof V==="string"&&(V.startsWith("where")||V.startsWith("orWhere")||V.startsWith("andWhere"))){let S=V.startsWith("orWhere"),k=V.startsWith("andWhere"),g=`${String(_)}|${V}`,p=U.get(g);if(p===void 0){let b=V.replace(/^(?:or|and)?where/i,"");if(!b)U.set(g,""),p="";else{let d=b.charAt(0).toLowerCase()+b.slice(1),o=b.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),JZ=X?Object.keys(X[String(_)]?.columns??{}):[];p=[o,d,d.toLowerCase()].find((SZ)=>JZ.includes(SZ))??o,U.set(g,p)}}if(p==="")return()=>D;let u=p;return(b)=>{if(Array.isArray(b)){let d=PZ(b.length,B.length+1);M(S?"OR":k?"AND":"WHERE",`${u} IN (${d})`),B.push(...b)}else{let d=s(B.length+1);M(S?"OR":k?"AND":"WHERE",`${u} = ${d}`),B.push(b)}return D}}return Reflect.get(j,V,D)}})}return{configure(_){return FX(_),this},id(_){if(!WZ.IDENTIFIER.test(_))throw Error(`[query-builder] Invalid identifier: '${_}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(String(_))},ids(..._){for(let F of _)if(!WZ.IDENTIFIER.test(F))throw Error(`[query-builder] Invalid identifier: '${F}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(_)},select(_,...F){return N(_,F)},selectFrom(_){return N(_)},selectFromSub(_,F){function L(M){return()=>{throw Error(`[query-builder] selectFromSub(...).${M}() is not supported. Apply ${M}() 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.")}}i(String(F),"selectFromSub(alias)");let K=typeof _.__rawState==="function"?_.__rawState():null,I=_.toSQL(),B=K?.sql??(typeof I==="string"?I:I?.sql??String(I)),v=K?.params??(Array.isArray(I?.values)?I.values:[]),P=`SELECT * FROM (${B}) AS ${String(F)}`,T=(M,q,C,y)=>{let c=[...M],l=(x,m,n)=>{i(x,"selectFromSub where(column)");let h=TZ(m,"selectFromSub where(operator)");if(h==="in"||h==="not in"){let a=Array.isArray(n)?n:[n],DZ=PZ(a.length,c.length+1);return c.push(...a),`${x} ${h.toUpperCase()} (${DZ})`}let ZZ=s(c.length+1);return c.push(n),`${x} ${h} ${ZZ}`},r;if(typeof q==="string"&&C!==void 0)r=l(q,C,y);else if(Array.isArray(q)&&q.length===3)r=l(q[0],q[1],q[2]);else if(q&&typeof q==="object"){let x=Object.entries(q).map(([m,n])=>l(m,"=",n));r=x.length>1?`(${x.join(" AND ")})`:x[0]}else return{clause:null,params:M};return{clause:r,params:c}};function w(M,q,C,y=""){let c=e8(q),l=c?`${M} WHERE ${c}${y}`:`${M}${y}`,r=()=>C.length>0?$.unsafe(l,C):$.unsafe(l),x=(h,ZZ,a,DZ)=>{let jZ=T(C,ZZ,a,DZ);return jZ.clause===null?w(M,q,C,y):w(M,[...q,{conn:h,sql:jZ.clause}],jZ.params,y)},m=(h,ZZ)=>{let a=[],DZ=[...C],jZ=(FZ)=>($8,i8,l8)=>{let F8=T(DZ,$8,i8,l8);if(F8.clause!==null)a.push({conn:FZ,sql:F8.clause}),DZ=F8.params;return mZ},mZ={where:jZ("AND"),andWhere:jZ("AND"),orWhere:jZ("OR")};ZZ(mZ);let k8=e8(a);if(!k8)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return w(M,[...q,{conn:h,sql:`(${k8})`}],DZ,y)},n={distinct(){return w(M.replace(/^SELECT\s+/i,"SELECT DISTINCT "),q,C,y)},distinctOn(...h){let ZZ=h.map(String).join(", ");return w(M.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${ZZ}) `),q,C,y)},selectRaw(h){let ZZ=Z9(h,"selectFromSub.selectRaw(fragment)"),a=M.indexOf(" FROM "),DZ=a!==-1?`${M.slice(0,a)}, ${ZZ}${M.slice(a)}`:`${M}, ${ZZ}`;return w(DZ,q,C,y)},$call(h){return h(this)??this},where(h,ZZ,a){return x("AND",h,ZZ,a)},andWhere(h,ZZ,a){return x("AND",h,ZZ,a)},orWhere(h,ZZ,a){return x("OR",h,ZZ,a)},whereGroup(h){return m("AND",h)},orWhereGroup(h){return m("OR",h)},orderBy(h,ZZ="asc"){i(String(h),"selectFromSub.orderBy(column)");let a=ZZ==="asc"?"ASC":"DESC",DZ=WZ.ORDER_BY.test(y)?`${y}, ${h} ${a}`:`${y} ORDER BY ${h} ${a}`;return w(M,q,C,DZ)},limit(h){if(!Number.isInteger(h)||h<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${h}`);let ZZ=WZ.LIMIT.test(y)?y.replace(WZ.LIMIT,` LIMIT ${h}`):`${y} LIMIT ${h}`;return w(M,q,C,ZZ)},offset(h){if(!Number.isInteger(h)||h<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${h}`);let ZZ=WZ.OFFSET.test(y)?y.replace(WZ.OFFSET,` OFFSET ${h}`):`${y} OFFSET ${h}`;return w(M,q,C,ZZ)},toSQL(){return O(r(),l)},async execute(){return Q(r(),"select")},async executeTakeFirst(){let h=await Q(r(),"select");return Array.isArray(h)?h[0]:h},async executeTakeFirstOrThrow(){let h=await Q(r(),"select"),ZZ=Array.isArray(h)?h[0]:h;if(!ZZ)throw Error("Record not found");return ZZ},async get(){return Q(r(),"select")},async first(){let h=await Q(r(),"select");return Array.isArray(h)?h[0]:h},async firstOrFail(){let h=await Q(r(),"select"),ZZ=Array.isArray(h)?h[0]:h;if(!ZZ)throw Error("No rows found");return ZZ},async count(){let h=C.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${l}) as sub`,C):$.unsafe(`SELECT COUNT(*) as c FROM (${l}) as sub`),ZZ=await Q(h,"select");return Number(ZZ?.[0]?.c??0)},async exists(){let h=C.length>0?$.unsafe(`SELECT EXISTS(${l}) as e`,C):$.unsafe(`SELECT EXISTS(${l}) as e`),ZZ=await Q(h,"select");return Boolean(ZZ?.[0]?.e)},async doesntExist(){return!await n.exists()},values(){return r().values()},raw(){return r().raw()},cancel(){try{r().cancel()}catch{}},whereRaw:L("whereRaw"),whereColumn:L("whereColumn"),orWhereColumn:L("orWhereColumn"),whereIn:L("whereIn"),orWhereIn:L("orWhereIn"),whereNotIn:L("whereNotIn"),orWhereNotIn:L("orWhereNotIn"),whereLike:L("whereLike"),whereILike:L("whereILike"),orWhereLike:L("orWhereLike"),orWhereILike:L("orWhereILike"),whereNotLike:L("whereNotLike"),whereNotILike:L("whereNotILike"),orWhereNotLike:L("orWhereNotLike"),orWhereNotILike:L("orWhereNotILike"),whereAny:L("whereAny"),whereAll:L("whereAll"),whereNone:L("whereNone"),whereNested:L("whereNested"),orWhereNested:L("orWhereNested"),whereDate:L("whereDate"),whereBetween:L("whereBetween"),whereNotBetween:L("whereNotBetween"),whereJsonContains:L("whereJsonContains"),whereJsonPath:L("whereJsonPath"),whereNull:L("whereNull"),orWhereNull:L("orWhereNull"),whereNotNull:L("whereNotNull"),orWhereNotNull:L("orWhereNotNull"),whereExists:L("whereExists"),orWhereExists:L("orWhereExists"),orWhereBetween:L("orWhereBetween"),orWhereRaw:L("orWhereRaw"),whereJsonDoesntContain:L("whereJsonDoesntContain"),whereJsonContainsKey:L("whereJsonContainsKey"),whereJsonDoesntContainKey:L("whereJsonDoesntContainKey"),whereJsonLength:L("whereJsonLength"),join:L("join"),joinSub:L("joinSub"),innerJoin:L("innerJoin"),leftJoin:L("leftJoin"),leftJoinSub:L("leftJoinSub"),rightJoin:L("rightJoin"),crossJoin:L("crossJoin"),crossJoinSub:L("crossJoinSub"),groupBy:L("groupBy"),groupByRaw:L("groupByRaw"),having:L("having"),havingRaw:L("havingRaw"),addSelect:L("addSelect"),select:L("select"),selectAll:L("selectAll"),orderByDesc:L("orderByDesc"),inRandomOrder:L("inRandomOrder"),reorder:L("reorder"),orderByRaw:L("orderByRaw"),union:L("union"),unionAll:L("unionAll"),forPage:L("forPage"),selectAllRelations:L("selectAllRelations"),with:L("with"),value:L("value"),pluck:L("pluck"),cursorPaginate:L("cursorPaginate"),paginate:L("paginate"),simplePaginate:L("simplePaginate"),chunk:L("chunk"),chunkById:L("chunkById"),eachById:L("eachById"),avg:L("avg"),sum:L("sum"),max:L("max"),min:L("min"),find:L("find"),findOrFail:L("findOrFail"),findMany:L("findMany"),latest:L("latest"),oldest:L("oldest"),lazy:L("lazy"),lazyById:L("lazyById"),pipe:(h)=>h(n),when:L("when"),tap:()=>n,dump:()=>n,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>r().simple(),toText:()=>l,toParams:()=>[...C],withTimeout:()=>n,abort:()=>n,lockForUpdate:()=>n,sharedLock:()=>n,withCTE:()=>n,withRecursive:()=>n,cache:()=>n,clone:()=>n,withTrashed:()=>n,onlyTrashed:()=>n,scope:()=>n,get rows(){return[]},get row(){return}};return n}return w(P,[],v)},insertInto(_){let F,L="",K=[],I=!1,B=()=>P?[]:{changes:0,lastInsertRowid:0},v=()=>{let M=async()=>{return},q=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>v(),andWhere:()=>v(),orWhere:()=>v(),orderBy:()=>v(),limit:()=>v(),offset:()=>v(),toSQL:()=>O(null,""),execute:async()=>[],get:async()=>[],first:M,executeTakeFirst:M,firstOrFail:q,executeTakeFirstOrThrow:q}},P=f.dialect==="postgres",T=P?(M)=>`"${String(M).replace(/"/g,'""')}"`:YZ(f.dialect)?(M)=>`\`${String(M).replace(/`/g,"``")}\``:(M)=>`"${String(M).replace(/"/g,'""')}"`,w=P?(M)=>`$${M+1}`:(M)=>"?";return{values(M){let q=Array.isArray(M)?M:[M],C=q.length;if(C===0)return I=!0,F=null,L="",K.length=0,this;I=!1;let y=q[0],c=Object.keys(y),l=c.length,r=C*l;K.length=r;let x=P?c.map((m)=>T(m)).join(","):c.join(",");if(C===1)if(!P){let m=T(c[0]),n="?";K[0]=y[c[0]];for(let h=1;h<l;h++)m+=`,${T(c[h])}`,n+=",?",K[h]=y[c[h]];L=`INSERT INTO ${T(_)}(${m})VALUES(${n})`}else{L=`INSERT INTO ${T(_)}(${x})VALUES(`;for(let m=0;m<l;m++){if(m>0)L+=",";L+=w(m),K[m]=y[c[m]]}L+=")"}else{let m=c.map((h)=>T(h)).join(",");L=`INSERT INTO ${T(_)}(${m})VALUES`;let n=0;for(let h=0;h<C;h++){let ZZ=q[h];if(h===0)L+="(";else L+="),(";for(let a=0;a<l;a++){if(a>0)L+=",";L+=w(n),K[n++]=ZZ[c[a]]}}L+=")"}if(!$._prepareStatement)F=$.unsafe(L,K);return this},returning(...M){if(I)return v();let q=`${L} RETURNING ${M.join(", ")}`,C=$.unsafe(q,K),y=async()=>{let c=await Q(C,"insert");return Array.isArray(c)?c[0]:c};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>O(C,q),execute:()=>Q(C,"insert"),get:()=>Q(C,"insert"),first:y,executeTakeFirst:y,async firstOrFail(){let c=await y();if(!c)throw Error("Insert with RETURNING returned no rows");return c},async executeTakeFirstOrThrow(){let c=await y();if(!c)throw Error("Insert with RETURNING returned no rows");return c}}},toSQL(){if(I)return O(null,"");if(!F)F=$.unsafe(L,K);return O(F,L)},execute(){if(I)return Promise.resolve(B());let M=G();if(!(M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||M.beforeCreate||M.afterCreate||d9(M)))){let C=$._prepareStatement;if(C){let y=C(L);return K.length>0?y.run(...K):y.run()}}if(!F)F=$.unsafe(L,K);return Q(F,"insert")},async executeTakeFirst(){if(I)return B();if(!F)F=$.unsafe(L,K);return await Q(F,"insert")},async executeTakeFirstOrThrow(){if(I)throw Error("Insert failed");if(!F)F=$.unsafe(L,K);let M=await Q(F,"insert");if(!M)throw Error("Insert failed");return M},returningAll(){if(I)return v();let M=`${L} RETURNING *`,q=$.unsafe(M,K),C=async()=>{let y=await Q(q,"insert");return Array.isArray(y)?y[0]:y};return{toSQL:()=>O(q,M),execute:()=>Q(q,"insert"),get:()=>Q(q,"insert"),first:C,executeTakeFirst:C,async firstOrFail(){let y=await C();if(!y)throw Error("Insert with RETURNING returned no rows");return y},async executeTakeFirstOrThrow(){let y=await C();if(!y)throw Error("Insert with RETURNING returned no rows");return y}}}}},updateTable(_){let F,L=[],K=(B)=>{let v=String(B);if(YZ(f.dialect))return`\`${v.replace(/`/g,"``")}\``;return`"${v.replace(/"/g,'""')}"`},I=`UPDATE ${K(String(_))}`;return{set(B){let v=Object.keys(B),P=v.length,T=Array.from({length:P});for(let w=0;w<P;w++){let M=v[w],q=B[M];if(w8(q))T[w]=`${K(M)} = ${q.raw}`;else if(o$(q)){let C=r$(q,L.length+1);T[w]=`${K(M)} = ${C.text}`,L.push(...C.parameters)}else T[w]=`${K(M)} = ${s(L.length+1)}`,L.push(q)}return I=`${I} SET ${T.join(", ")}`,F=$.unsafe(I,L),this},where(B,v,P){let T=()=>WZ.WHERE.test(I)?"AND":"WHERE";if(v!==void 0&&(typeof B==="string"||w8(B)||o$(B))){let w=TZ(v,"updateTable.where"),M;if(typeof B==="string")M=K(B);else if(w8(B))M=B.raw;else{let C=r$(B,L.length+1);M=C.text,L.push(...C.parameters)}if(w.toLowerCase()==="in"||w.toLowerCase()==="not in"){let C=Array.isArray(P)?P:[P],y=PZ(C.length,L.length+1);return I=`${I} ${T()} ${M} ${w.toUpperCase()} (${y})`,L.push(...C),F=$.unsafe(I,L),this}let q=L.length+1;return I=`${I} ${T()} ${M} ${w} ${s(q)}`,L.push(P),F=$.unsafe(I,L),this}if(Array.isArray(B)){let[w,M,q]=B,C=TZ(M,"updateTable.where");if(C.toLowerCase()==="in"||C.toLowerCase()==="not in"){let c=Array.isArray(q)?q:[q],l=PZ(c.length,L.length+1);return I=`${I} ${T()} ${K(String(w))} ${C.toUpperCase()} (${l})`,L.push(...c),F=$.unsafe(I,L),this}let y=L.length+1;return I=`${I} ${T()} ${K(String(w))} ${C} ${s(y)}`,L.push(q),F=$.unsafe(I,L),this}if(w8(B))return I=`${I} ${T()} ${B.raw}`,F=$.unsafe(I,L),this;if(o$(B)){let w=r$(B,L.length+1);return I=`${I} ${T()} ${w.text}`,L.push(...w.parameters),F=$.unsafe(I,L),this}if(B&&typeof B==="object"){let w=Object.keys(B);if(w.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 M=w.length,q=L.length,C=Array.from({length:M});for(let y=0;y<M;y++)C[y]=`${K(w[y])} = ${s(q+y+1)}`,L.push(B[w[y]]);return I=`${I} ${T()} ${C.join(" AND ")}`,F=$.unsafe(I,L),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){let v=WZ.WHERE.test(I)?"AND":"WHERE";return I=`${I} ${v} ${K(String(B))} IS NULL`,F=$.unsafe(I,L),this},whereNotNull(B){let v=WZ.WHERE.test(I)?"AND":"WHERE";return I=`${I} ${v} ${K(String(B))} IS NOT NULL`,F=$.unsafe(I,L),this},returning(...B){let v=this,P=()=>`${I} RETURNING ${B.join(", ")}`,T=()=>L.length>0?$.unsafe(P(),L):$.unsafe(P()),w=async()=>{let C=await Q(T(),"update");return Array.isArray(C)?C[0]:C},M=(C)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${C}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},q={where:(...C)=>{return v.where(...C),q},andWhere:(...C)=>{return v.where(...C),q},whereNull:(...C)=>{return v.whereNull(...C),q},whereNotNull:(...C)=>{return v.whereNotNull(...C),q},orWhere:M("orWhere"),orderBy:M("orderBy"),limit:M("limit"),offset:M("offset"),toSQL:()=>O(T(),P()),execute:()=>Q(T(),"update"),get:()=>Q(T(),"update"),first:w,executeTakeFirst:w,async firstOrFail(){let C=await w();if(!C)throw Error("Update with RETURNING returned no rows");return C},async executeTakeFirstOrThrow(){let C=await w();if(!C)throw Error("Update with RETURNING returned no rows");return C}};return q},toSQL(){if(!F)F=L.length>0?$.unsafe(I,L):$.unsafe(I);return O(F,I)},async execute(){let B=await Q(F,"update");return R(B)},async executeTakeFirst(){return{numUpdatedRows:R(await Q(F,"update"))}},async executeTakeFirstOrThrow(){let B=R(await Q(F,"update"));if(B===0)throw Error("No rows updated");return{numUpdatedRows:B}},returningAll(){let B=()=>`${I} RETURNING *`,v=()=>L.length>0?$.unsafe(B(),L):$.unsafe(B());return{toSQL:()=>O(v(),B()),execute:()=>Q(v(),"update"),async executeTakeFirst(){let P=await Q(v(),"update");return Array.isArray(P)?P[0]:P},async executeTakeFirstOrThrow(){let P=await Q(v(),"update"),T=Array.isArray(P)?P[0]:P;if(!T)throw Error("Update with RETURNING failed");return T}}}}},deleteFrom(_){let F=(w)=>{let M=String(w);if(YZ(f.dialect))return`\`${M.replace(/`/g,"``")}\``;return`"${M.replace(/"/g,'""')}"`},K=`DELETE FROM ${F(String(_))}`,I=null,B=[],v=null,P=()=>WZ.WHERE.test(K)?"AND":"WHERE",T=()=>{if(I===null)I=B.length>0?$.unsafe(K,B):$.unsafe(K);return I};return{where(w,M,q){if(v=w,typeof w==="string"&&M!==void 0){let C=TZ(M,"deleteFrom.where");if(C.toLowerCase()==="in"||C.toLowerCase()==="not in"){let c=Array.isArray(q)?q:[q],l=PZ(c.length,B.length+1);return K+=` ${P()} ${F(w)} ${C.toUpperCase()} (${l})`,B.push(...c),I=null,this}let y=B.length+1;return K+=` ${P()} ${F(w)} ${C} ${s(y)}`,B.push(q),I=null,this}if(Array.isArray(w)){let[C,y,c]=w,l=TZ(y,"deleteFrom.where");if(l.toLowerCase()==="in"||l.toLowerCase()==="not in"){let x=Array.isArray(c)?c:[c],m=PZ(x.length,B.length+1);return K+=` ${P()} ${F(String(C))} ${l.toUpperCase()} (${m})`,B.push(...x),I=null,this}let r=B.length+1;return K+=` ${P()} ${F(String(C))} ${l} ${s(r)}`,B.push(c),I=null,this}if(w8(w))return K+=` ${P()} ${w.raw}`,I=null,this;if(o$(w)){let C=r$(w,B.length+1);return K+=` ${P()} ${C.text}`,B.push(...C.parameters),I=null,this}if(w&&typeof w==="object"){let C=Object.keys(w);if(C.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 y=[];for(let c of C){let l=B.length+1;y.push(`${F(c)} = ${s(l)}`),B.push(w[c])}return K+=` ${P()} ${y.join(" AND ")}`,I=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${w===null?"null":typeof w}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(w){return K+=` ${P()} ${F(String(w))} IS NULL`,I=null,this},whereNotNull(w){return K+=` ${P()} ${F(String(w))} IS NOT NULL`,I=null,this},returning(...w){let M=this,q=()=>`${K} RETURNING ${w.join(", ")}`,C=()=>B.length>0?$.unsafe(q(),B):$.unsafe(q()),y=async()=>{await G()?.beforeDelete?.({table:String(_),where:v});let x=await Q(C(),"delete");try{await G()?.afterDelete?.({table:String(_),where:v,result:x})}catch{}return x},c=async()=>{let x=await y();return Array.isArray(x)?x[0]:x},l=(x)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${x}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},r={where:(...x)=>{return M.where(...x),r},andWhere:(...x)=>{return M.where(...x),r},whereNull:(...x)=>{return M.whereNull(...x),r},whereNotNull:(...x)=>{return M.whereNotNull(...x),r},orWhere:l("orWhere"),orderBy:l("orderBy"),limit:l("limit"),offset:l("offset"),toSQL:()=>O(C(),q()),execute:()=>y(),get:()=>y(),first:c,executeTakeFirst:c,async firstOrFail(){let x=await c();if(!x)throw Error("Delete with RETURNING returned no rows");return x},async executeTakeFirstOrThrow(){let x=await c();if(!x)throw Error("Delete with RETURNING returned no rows");return x}};return r},toSQL(){return O(T(),K)},async execute(){try{await G()?.beforeDelete?.({table:String(_),where:v})}catch(M){throw M}let w=R(await Q(T(),"delete"));try{await G()?.afterDelete?.({table:String(_),where:v,result:w})}catch{}return w},async executeTakeFirst(){return{numDeletedRows:R(await Q(T(),"delete"))}},async executeTakeFirstOrThrow(){let w=R(await Q(T(),"delete"));if(w===0)throw Error("No rows deleted");return{numDeletedRows:w}},returningAll(){let w=()=>`${K} RETURNING *`,M=()=>B.length>0?$.unsafe(w(),B):$.unsafe(w());return{toSQL:()=>O(M(),w()),execute:()=>Q(M(),"delete"),async executeTakeFirst(){let q=await Q(M(),"delete");return Array.isArray(q)?q[0]:q},async executeTakeFirstOrThrow(){let q=await Q(M(),"delete"),C=Array.isArray(q)?q[0]:q;if(!C)throw Error("Delete with RETURNING failed");return C}}}}},table(_){let F=this;return{insert(L){return F.insertInto(_).values(L)},update(L){return F.updateTable(_).set(L)},delete(){return F.deleteFrom(_)},select(...L){if(L.length===0)return F.selectFrom(_);return F.select(_,...L)}}},sql:$,raw(_,...F){return $(_,...F)},simple(_,...F){return $(_,...F).simple()},async advisoryLock(_){if(f.dialect==="postgres"){let F=J(_),L=$`SELECT pg_advisory_lock(${F})`;await Q(L,"raw");return}if(YZ(f.dialect)){let F=`bqb:${String(_)}`,L=$`SELECT GET_LOCK(${F}, -1) AS ok`;await Q(L,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(_){if(f.dialect==="postgres"){let F=J(_),L=$`SELECT pg_try_advisory_lock(${F}) as ok`,K=await Q(L,"raw");return Boolean(K?.[0]?.ok)}if(YZ(f.dialect)){let F=`bqb:${String(_)}`,L=$`SELECT GET_LOCK(${F}, 0) AS ok`,K=await Q(L,"raw");return Number(K?.[0]?.ok)===1}return!1},async advisoryUnlock(_){if(f.dialect==="postgres"){let F=J(_),L=$`SELECT pg_advisory_unlock(${F}) as ok`,K=await Q(L,"raw");return Boolean(K?.[0]?.ok)}if(YZ(f.dialect)){let F=`bqb:${String(_)}`,L=$`SELECT RELEASE_LOCK(${F}) AS ok`,K=await Q(L,"raw");return Number(K?.[0]?.ok)===1}return!1},unsafe(_,F){return $.unsafe(_,F)},file(_,F){return $.file(_,F)},async reserve(){let _=await e.reserve(),F=XZ({sql:_,meta:Y,schema:X,hooks:Z?.hooks});return F.release=()=>_.release(),F},async close(_){await e.close(_)},async listen(_,F){},async unlisten(_){},async notify(_,F){},async copyTo(_,F){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(_,F,L){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let _=$`SELECT 1`;return await Q(_,"select"),!0}catch{return!1}},async waitForReady(_){let F=Math.max(1,_?.attempts??10),L=Math.max(10,_?.delayMs??100);for(let K=0;K<F;K++){if(await this.ping())return;await new Promise((I)=>setTimeout(I,L))}throw Error("Database not ready after waiting")},async transaction(_,F){let K={...Z?.txDefaults,...F},I=Z?.sql??e,B=Z?.inTransaction===!0,v=B&&typeof I?.savepoint==="function"?"savepoint":"begin",P=async(M)=>{K.logger?.({type:"start",attempt:M});let q=Date.now();return await I[v](async(C)=>{let y=XZ({sql:C,meta:Y,schema:X,hooks:Z?.hooks,inTransaction:!0});if(K?.isolation&&!B){let r=K.isolation,x=r==="read committed"?"READ COMMITTED":r==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(f.dialect==="postgres")await C.unsafe(`SET TRANSACTION ISOLATION LEVEL ${x}`);else if(YZ(f.dialect))await C.unsafe(`SET TRANSACTION ISOLATION LEVEL ${x}`);else if(r!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${r}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(K?.readOnly)if(f.dialect==="postgres")await C.unsafe("SET TRANSACTION READ ONLY");else if(YZ(f.dialect))await C.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let c=await _(y),l=Date.now()-q;return K.logger?.({type:"commit",attempt:M,durationMs:l}),c})},T=Math.max(0,K?.retries??0),w=0;for(;;)try{let M=await P(w+1);return K?.afterCommit?.(),M}catch(M){let q=F6(M)||B6(M,K.sqlStates);if(w<T&&q){w++,K?.onRetry?.(w,M);let C=E6(w,K.backoff);if(C>0)await R6(C);continue}try{K.onRollback?.(M)}catch{}try{K.afterRollback?.()}catch{}throw M}},async savepoint(_){if(Z?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let F=$;if(!F||typeof F.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await F.savepoint(async(L)=>{let K=XZ({sql:L,meta:Y,schema:X,hooks:Z?.hooks,inTransaction:!0});return await _(K)})},async beginDistributed(_,F){return await(Z?.sql??e).beginDistributed(_,async(I)=>{let B=XZ({sql:I,meta:Y,schema:X,hooks:Z?.hooks});return await F(B)})},async commitDistributed(_){await e.commitDistributed(_)},async rollbackDistributed(_){await e.rollbackDistributed(_)},setTransactionDefaults(_){Z={...Z,txDefaults:{...Z?.txDefaults,..._}}},transactional(_,F){return(...L)=>{return this.transaction((K)=>_(K,...L),F)}},async insertOrIgnore(_,F){let L=Array.isArray(F)?F:[F];if(!L.length)return;let{colsSql:K,valuesSql:I,params:B}=a$(L),v=oZ(String(_)),P=YZ(f.dialect)?`INSERT IGNORE INTO ${v} (${K}) VALUES ${I}`:`INSERT INTO ${v} (${K}) VALUES ${I} ON CONFLICT DO NOTHING`;return $.unsafe(P,B).execute()},async insertGetId(_,F,L="id"){let{colsSql:K,valuesSql:I,params:B}=a$([F]),v=oZ(String(_));if(YZ(f.dialect)){await $.unsafe(`INSERT INTO ${v} (${K}) VALUES ${I}`,B).execute();let[T]=await $.unsafe("SELECT LAST_INSERT_ID() as id").execute();return T?.id}if(f.dialect==="sqlite"){let T=await $.unsafe(`INSERT INTO ${v} (${K}) VALUES ${I}`,B).execute();if(T?.lastInsertRowid!=null)return T.lastInsertRowid;let[w]=await $.unsafe("SELECT last_insert_rowid() as id").execute();return w?.id}let[P]=await $.unsafe(`INSERT INTO ${v} (${K}) VALUES ${I} RETURNING ${oZ(String(L))} as id`,B).execute();return P?.id},async updateOrInsert(_,F,L){let K=oZ(String(_)),I=Object.keys(F),B=1,v=I.map((C)=>`${oZ(C)} = ${s(B++)}`).join(" AND "),P=I.map((C)=>F[C]);if((await $.unsafe(`SELECT 1 FROM ${K} WHERE ${v} LIMIT 1`,P).execute()).length){let C=Object.keys(L),y=1,c=C.map((x)=>`${oZ(x)} = ${s(y++)}`).join(", "),l=I.map((x)=>`${oZ(x)} = ${s(y++)}`).join(" AND "),r=[...C.map((x)=>L[x]),...I.map((x)=>F[x])];return await $.unsafe(`UPDATE ${K} SET ${c} WHERE ${l}`,r).execute(),!0}let{colsSql:w,valuesSql:M,params:q}=a$([{...F,...L}]);return await $.unsafe(`INSERT INTO ${K} (${w}) VALUES ${M}`,q).execute(),!0},async upsert(_,F,L,K){let I=L.map((c)=>String(c)),B=(K??[]).map((c)=>String(c)),v=F;if(!v.length)return;let{colsSql:P,valuesSql:T,params:w}=a$(v),M=oZ(String(_)),q=`INSERT INTO ${M} (${P}) VALUES ${T}`;if(YZ(f.dialect)){if(B.length===0)return $.unsafe(`INSERT IGNORE INTO ${M} (${P}) VALUES ${T}`,w).execute();let c=B.map((l)=>`${oZ(l)} = VALUES(${oZ(l)})`).join(", ");return $.unsafe(`${q} ON DUPLICATE KEY UPDATE ${c}`,w).execute()}let C=I.map(oZ).join(", ");if(B.length===0)return $.unsafe(`${q} ON CONFLICT (${C}) DO NOTHING`,w).execute();let y=B.map((c)=>`${oZ(c)} = EXCLUDED.${oZ(c)}`).join(", ");return $.unsafe(`${q} ON CONFLICT (${C}) DO UPDATE SET ${y}`,w).execute()},async save(_,F){let L=Y?.primaryKeys[String(_)]??"id",K=F[L];if(K!=null)if(await this.selectFrom(_).find(K)){await this.updateTable(_).set(F).where({[L]:K}).execute();let B=await this.selectFrom(_).find(K);if(!B)throw Error("save() failed to retrieve updated row");return B}else return await this.create(_,F);return await this.create(_,F)},async remove(_,F){return await this.deleteFrom(_).where({id:F}).execute()},async find(_,F){return await this.selectFrom(_).find(F)},async findOrFail(_,F){return await this.selectFrom(_).findOrFail(F)},async findMany(_,F){return await this.selectFrom(_).findMany(F)},async latest(_,F){return await this.selectFrom(_).latest(F).first()},async oldest(_,F){return await this.selectFrom(_).oldest(F).first()},skip(_,F){return this.selectFrom(_).offset(F)},async rawQuery(_){let F=Date.now();try{G()?.onQueryStart?.({sql:_,kind:"raw"});let L=await $.unsafe(_);return G()?.onQueryEnd?.({sql:_,durationMs:Date.now()-F,kind:"raw"}),L}catch(L){throw G()?.onQueryError?.({sql:_,error:L,durationMs:Date.now()-F,kind:"raw"}),L}},async create(_,F){let L=Y?.primaryKeys[String(_)]??"id";try{await G()?.beforeCreate?.({table:String(_),data:F})}catch(K){throw K}if(f.dialect==="postgres"){let K=$`INSERT INTO ${$(String(_))} ${$(F)} RETURNING ${$(String(L))} as id`,[I]=await K.execute();if(!I?.id)throw console.error(`create() failed to get insert ID for table ${String(_)}`),console.error("Inserted values:",F),Error(`create() failed to get insert ID for table ${String(_)}`);let B=await this.selectFrom(_).find(I.id);if(!B)throw console.error(`create() failed to retrieve inserted row for table ${String(_)} with id ${I.id}`),console.error("Inserted values:",F),Error(`create() failed to retrieve inserted row for table ${String(_)} with id ${I.id}`);try{await G()?.afterCreate?.({table:String(_),data:F,result:B})}catch{}return B}else{let K=await this.insertGetId(_,F,L);if(K==null)throw Error(`create() failed to get insert ID for table ${String(_)}`);let I=await this.selectFrom(_).find(K);if(!I)throw console.error(`create() failed to retrieve inserted row for table ${String(_)} with id ${K}`),console.error("Inserted values:",F),Error(`create() failed to retrieve inserted row for table ${String(_)} with id ${K}`);try{await G()?.afterCreate?.({table:String(_),data:F,result:I})}catch{}return I}},async createMany(_,F){if(!F?.length)return;let L=F[0],K=Object.keys(L),I=K.length,B=F.length,v=Array.from({length:B*I}),P=YZ(f.dialect)?(M)=>`\`${String(M).replace(/`/g,"``")}\``:(M)=>`"${String(M).replace(/"/g,'""')}"`,T=`INSERT INTO ${P(String(_))}(${K.map(P).join(",")})VALUES`,w=0;for(let M=0;M<B;M++){if(M>0)T+=",";T+="(";let q=F[M];for(let C=0;C<I;C++){if(C>0)T+=",";T+=s(w+1),v[w++]=q[K[C]]}T+=")"}return $.unsafe(T,v).execute()},async insertMany(_,F){if(!F?.length)return;let L=F[0],K=Object.keys(L),I=K.length,B=F.length,v=B*I,P=Array(v),T=f.dialect==="postgres",w;if(!T){let C=Array(I);for(let y=0;y<I;y++)C[y]="?";w=`(${C.join(",")})`}else w="";let M=Array(B+2);M[0]=`INSERT INTO ${_}(${K.join(",")})VALUES`;let q=0;if(!T){for(let C=0;C<B;C++){let y=F[C];M[C+1]=w;for(let c=0;c<I;c++)P[q++]=y[K[c]]}return $.unsafe(M[0]+M.slice(1,B+1).join(","),P).execute()}for(let C=0;C<B;C++){let y=F[C],c=Array(I);for(let l=0;l<I;l++)c[l]=`$${q+1}`,P[q++]=y[K[l]];M[C+1]=`(${c.join(",")})`}return $.unsafe(M[0]+M.slice(1,B+1).join(","),P).execute()},async updateMany(_,F,L){let K=Object.keys(L),I=K.length;if(I===0)return 0;let B=[],v=Array.from({length:I});for(let T=0;T<I;T++)v[T]=`${K[T]}=${s(T+1)}`,B.push(L[K[T]]);let P=`UPDATE ${_} SET ${v.join(",")}`;if(Array.isArray(F))P+=` WHERE ${F[0]}${F[1]}${s(B.length+1)}`,B.push(F[2]);else if(F&&typeof F==="object"&&!("raw"in F)){let T=Object.keys(F),w=T.length;if(w>0){let M=B.length,q=Array.from({length:w});for(let C=0;C<w;C++)q[C]=`${T[C]}=${s(M+C+1)}`,B.push(F[T[C]]);P+=` WHERE ${q.join(" AND ")}`}}return $.unsafe(P,B).execute()},async deleteMany(_,F){if(!Array.isArray(F)||F.length===0)return 0;let L=Y?.primaryKeys[String(_)]??"id",K=F.length;if(f.dialect==="postgres"){let B=Array(K);for(let v=0;v<K;v++)B[v]=`$${v+1}`;return $.unsafe(`DELETE FROM ${_} WHERE ${L} IN (${B.join(",")})`,F).execute()}let I=Array(K);for(let B=0;B<K;B++)I[B]="?";return $.unsafe(`DELETE FROM ${_} WHERE ${L} IN (${I.join(",")})`,F).execute()},async firstOrCreate(_,F,L){let K=await this.selectFrom(_).where(F).first();if(K)return K;return await this.create(_,{...F,...L})},async updateOrCreate(_,F,L){let K=await this.selectFrom(_).where(F).first();if(K){await this.updateTable(_).set(L).where(F).execute();let I=Y?.primaryKeys[String(_)]??"id",B=K[I],v=B!=null?await this.selectFrom(_).find(B):await this.selectFrom(_).where(F).first();if(!v)throw Error("updateOrCreate() failed to retrieve updated row");return v}return await this.create(_,{...F,...L})},async count(_,F){let L=F?$(String(F)):$`*`,K=$`SELECT COUNT(${L}) as c FROM ${$(String(_))}`,[I]=await K.execute();return Number(I?.c??0)},async sum(_,F){let L=$`SELECT SUM(${$(String(F))}) as s FROM ${$(String(_))}`,[K]=await L.execute();return Number(K?.s??0)},async avg(_,F){let L=$`SELECT AVG(${$(String(F))}) as a FROM ${$(String(_))}`,[K]=await L.execute();return Number(K?.a??0)},async min(_,F){let L=$`SELECT MIN(${$(String(F))}) as m FROM ${$(String(_))}`,[K]=await L.execute();return K?.m},async max(_,F){let L=$`SELECT MAX(${$(String(F))}) as m FROM ${$(String(_))}`,[K]=await L.execute();return K?.m},getRelationships(_){if(!Y?.relations)return{};let F=Y.relations[_];if(!F)return{};let L={};for(let[K,I]of Object.entries(F))if(I&&typeof I==="object"&&Object.keys(I).length>0)L[K]=I;return L},hasRelationship(_,F){if(!Y?.relations)return!1;let L=Y.relations[_];if(!L)return!1;return Object.values(L).some((K)=>K&&typeof K==="object"&&(F in K))},getRelationshipType(_,F){if(!Y?.relations)return null;let L=Y.relations[_];if(!L)return null;for(let[K,I]of Object.entries(L))if(I&&typeof I==="object"&&F in I)return K;return null},getRelationshipTarget(_,F){if(!Y?.relations)return null;let L=Y.relations[_];if(!L)return null;for(let[K,I]of Object.entries(L))if(I&&typeof I==="object"&&F in I){let B=I[F];if(typeof B==="string")return Y.modelToTable[B]||B;else if(B&&typeof B==="object"){if("model"in B)return Y.modelToTable[B.model]||B.model;if("target"in B)return Y.modelToTable[B.target]||B.target}}return null}}}function xX(){e$.clear()}function vX(Z){e$.setMaxSize(Z)}async function I6(){console.log("-- Clearing query cache..."),xX(),console.log("-- \u2713 Query cache cleared")}async function M6(){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 w6(Z={}){if(console.log("-- Configuring query cache..."),console.log(),Z.size!==void 0){let $=Number(Z.size);if(Number.isNaN($)||$<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");vX($),console.log(`-- \u2713 Cache max size set to: ${$}`)}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 Z7 from"process";import{createInterface as C6}from"readline";async function yX(){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 Z=XZ(),$=C6({input:Z7.stdin,output:Z7.stdout,prompt:"qb> "}),Y="",X=!1,J=`
113
+ Available Commands:
114
+ .help Show this help message
115
+ .exit Exit the console
116
+ .tables List all tables
117
+ .clear Clear the screen
118
+
119
+ Query Examples:
120
+ qb.selectFrom('users').where({ active: true }).limit(10).execute()
121
+ qb.selectFrom('users').count()
122
+ qb.insertInto('users').values({ name: 'John' }).execute()
123
+ qb.selectFrom('users').where('id', '=', 1).first()
124
+ qb.unsafe("SELECT * FROM users WHERE id = $1", [1]).execute()
125
+
126
+ Tips:
127
+ - Use 'qb' to access the query builder
128
+ - Use 'await' for async operations
129
+ - Multi-line input: end with \\ to continue on next line
130
+ - Press Enter on an empty line to execute multi-line input
131
+ `,G=async(H)=>{try{let W=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${H})`)(Z);if(W!==void 0)if(Array.isArray(W))console.log(`-- ${W.length} row(s) returned`),console.table(W);else if(typeof W==="object"&&W!==null)console.log(W);else console.log(W)}catch(z){console.error("Error:",z.message)}},U=async(H)=>{let z=H.trim();if(z.startsWith(".")){let A=z.toLowerCase();if(A===".exit"||A===".quit")console.log("Goodbye!"),$.close(),Z7.exit(0);else if(A===".help")console.log(J);else if(A===".clear")console.clear();else if(A===".tables")try{let W=await Z.unsafe(`
132
+ SELECT name FROM sqlite_master
133
+ WHERE type = 'table'
134
+ AND name NOT LIKE 'sqlite_%'
135
+ ORDER BY name
136
+ `);if(W.length>0){console.log("Tables:");for(let Q of W)console.log(` - ${Q.name}`)}else console.log("No tables found")}catch(W){console.error("Error listing tables:",W.message)}else console.log(`Unknown command: ${z}`),console.log("Type .help for available commands");return}if(z.endsWith("\\")){X=!0,Y+=`${z.slice(0,-1)}
137
+ `;return}if(X){if(z==="")await G(Y),Y="",X=!1;else Y+=`${z}
138
+ `;return}if(z)await G(z)};$.on("line",async(H)=>{await U(H),$.prompt()}),$.on("SIGINT",()=>{if(X)console.log(`
139
+ -- Multi-line input cancelled`),Y="",X=!1,$.prompt();else console.log(`
140
+ -- Type .exit to quit`),$.prompt()}),$.on("close",()=>{console.log(`
141
+ Goodbye!`),Z7.exit(0)}),$.prompt()}async function S6(){return yX()}qZ();import{existsSync as N6,readFileSync as P6,writeFileSync as c9}from"fs";async function q6(Z,$={}){let Y=$.format||"json",X=$.output||`${Z}.${Y}`,J=$.limit;if(console.log(`-- Exporting data from table: ${Z}`),console.log(`-- Format: ${Y}`),console.log(`-- Output: ${X}`),J)console.log(`-- Limit: ${J} rows`);console.log();try{let U=XZ().selectFrom(Z);if(J)U=U.limit(J);let H=await U.execute();if(console.log(`-- Retrieved ${H.length} rows`),Y==="json")c9(X,JSON.stringify(H,null,2)),console.log(`-- \u2713 Exported to JSON: ${X}`);else if(Y==="csv"){if(H.length===0){c9(X,""),console.log(`-- \u2713 Exported to CSV: ${X} (empty)`);return}let z=Object.keys(H[0]),A=[z.join(",")];for(let W of H){let Q=z.map((R)=>{let O=W[R];if(O===null||O===void 0)return"";let N=String(O);if(N.includes(",")||N.includes('"')||N.includes(`
142
+ `))return`"${N.replace(/"/g,'""')}"`;return N});A.push(Q.join(","))}c9(X,A.join(`
143
+ `)),console.log(`-- \u2713 Exported to CSV: ${X}`)}else if(Y==="sql"){let z=[];for(let A of H){let W=Object.keys(A),Q=W.map((R)=>{let O=A[R];if(O===null||O===void 0)return"NULL";if(typeof O==="number")return String(O);return`'${String(O).replace(/'/g,"''")}'`});z.push(`INSERT INTO ${Z} (${W.join(", ")}) VALUES (${Q.join(", ")});`)}c9(X,z.join(`
144
+ `)),console.log(`-- \u2713 Exported to SQL: ${X}`)}}catch(G){throw console.error(`-- Failed to export data from ${Z}:`,G),G}}async function T6(Z,$,Y={}){if(!N6($))throw console.error(`-- File not found: ${$}`),Error(`File not found: ${$}`);let X=Y.format||($.endsWith(".json")?"json":"csv"),J=Y.truncate??!1;console.log(`-- Importing data into table: ${Z}`),console.log(`-- Format: ${X}`),console.log(`-- File: ${$}`),console.log(`-- Truncate: ${J}`),console.log();try{let G=XZ();if(J)await G.deleteFrom(Z).execute(),console.log("-- Table truncated");let U=P6($,"utf8"),H=[];if(X==="json"){if(H=JSON.parse(U),!Array.isArray(H))throw TypeError("JSON file must contain an array of objects")}else if(X==="csv"){let W=U.split(`
145
+ `).filter((R)=>R.trim());if(W.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let Q=W[0].split(",").map((R)=>R.trim());for(let R=1;R<W.length;R++){let O=W[R].split(",").map((_)=>_.trim()),N={};for(let _=0;_<Q.length;_++){let F=O[_];if(F.startsWith('"')&&F.endsWith('"'))F=F.slice(1,-1).replace(/""/g,'"');if(F==="")F=null;else if(!Number.isNaN(Number(F)))F=Number(F);N[Q[_]]=F}H.push(N)}}if(H.length===0){console.log("-- No data to import");return}let z=100,A=0;for(let W=0;W<H.length;W+=z){let Q=H.slice(W,W+z);await G.insertInto(Z).values(Q).execute(),A+=Q.length,console.log(`-- Imported ${A}/${H.length} rows...`)}console.log(`-- \u2713 Successfully imported ${H.length} rows`)}catch(G){throw console.error(`-- Failed to import data into ${Z}:`,G),G}}async function k6(Z={}){let $=f.dialect||"postgres",Y=Z.output||`dump-${Date.now()}.sql`,X=Z.tables?.split(",").map((J)=>J.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${$}`),console.log(`-- Output: ${Y}`),X)console.log(`-- Tables: ${X.join(", ")}`);console.log();try{let J=XZ(),G=[];if($==="sqlite")G=(await J.unsafe(`
146
+ SELECT name FROM sqlite_master
147
+ WHERE type = 'table'
148
+ AND name NOT LIKE 'sqlite_%'
149
+ ORDER BY name
150
+ `)).map((z)=>z.name);else if($==="postgres")G=(await J.unsafe(`
151
+ SELECT table_name
152
+ FROM information_schema.tables
153
+ WHERE table_schema = 'public'
154
+ AND table_type = 'BASE TABLE'
155
+ ORDER BY table_name
156
+ `)).map((z)=>z.table_name);else if(YZ($))G=(await J.unsafe(`
157
+ SELECT table_name
158
+ FROM information_schema.tables
159
+ WHERE table_schema = DATABASE()
160
+ AND table_type = 'BASE TABLE'
161
+ ORDER BY table_name
162
+ `)).map((z)=>z.table_name);if(X)G=G.filter((H)=>X.includes(H));if(G.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${G.length} table(s)`);let U=[];U.push("-- Database dump"),U.push(`-- Generated at: ${new Date().toISOString()}`),U.push(`-- Dialect: ${$}`),U.push("");for(let H of G){console.log(`-- Dumping table: ${H}`);let z=await J.selectFrom(H).execute();U.push(`-- Table: ${H}`),U.push(`-- Rows: ${z.length}`),U.push("");for(let A of z){let W=Object.keys(A),Q=W.map((R)=>{let O=A[R];if(O===null||O===void 0)return"NULL";if(typeof O==="number")return String(O);return`'${String(O).replace(/'/g,"''")}'`});U.push(`INSERT INTO ${H} (${W.join(", ")}) VALUES (${Q.join(", ")});`)}U.push("")}c9(Y,U.join(`
163
+ `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${Y}`)}catch(J){throw console.error("-- Failed to dump database:",J),J}}qZ();async function hX(){let Z=f.dialect||"postgres",$=f.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${Z}`),console.log(`-- Database: ${$}`),console.log();try{let Y=XZ(),X=[],J=[];if(Z==="postgres")J=(await Y.unsafe(`
164
+ SELECT table_name
165
+ FROM information_schema.tables
166
+ WHERE table_schema = 'public'
167
+ AND table_type = 'BASE TABLE'
168
+ ORDER BY table_name
169
+ `)).map((H)=>H.table_name);else if(YZ(Z))J=(await Y.unsafe(`
170
+ SELECT table_name
171
+ FROM information_schema.tables
172
+ WHERE table_schema = DATABASE()
173
+ AND table_type = 'BASE TABLE'
174
+ ORDER BY table_name
175
+ `)).map((H)=>H.table_name);else if(Z==="sqlite")J=(await Y.unsafe(`
176
+ SELECT name
177
+ FROM sqlite_master
178
+ WHERE type = 'table'
179
+ AND name NOT LIKE 'sqlite_%'
180
+ ORDER BY name
181
+ `)).map((H)=>H.name);for(let U of J)try{let H=await Y.unsafe(`SELECT COUNT(*) as count FROM ${U}`),z=Number(H[0]?.count||0),A=0,W=0;if(Z==="postgres"){let Q=await Y.unsafe(`
182
+ SELECT COUNT(*) as count
183
+ FROM information_schema.columns
184
+ WHERE table_name = $1
185
+ `,[U]);A=Number(Q[0]?.count||0);let R=await Y.unsafe(`
186
+ SELECT COUNT(*) as count
187
+ FROM pg_indexes
188
+ WHERE tablename = $1
189
+ `,[U]);W=Number(R[0]?.count||0)}else if(YZ(Z)){let Q=await Y.unsafe(`
190
+ SELECT COUNT(*) as count
191
+ FROM information_schema.columns
192
+ WHERE table_name = ?
193
+ AND table_schema = DATABASE()
194
+ `,[U]);A=Number(Q[0]?.count||0);let R=await Y.unsafe(`
195
+ SELECT COUNT(*) as count
196
+ FROM information_schema.statistics
197
+ WHERE table_name = ?
198
+ AND table_schema = DATABASE()
199
+ `,[U]);W=Number(R[0]?.count||0)}else if(Z==="sqlite")A=(await Y.unsafe(`PRAGMA table_info(${U})`)).length,W=(await Y.unsafe(`PRAGMA index_list(${U})`)).length;X.push({name:U,rowCount:z,columns:A,indexes:W})}catch(H){console.error(`-- Error getting info for table ${U}:`,H)}let G=X.reduce((U,H)=>U+H.rowCount,0);if(console.log(`-- Total Tables: ${X.length}`),console.log(`-- Total Rows: ${G.toLocaleString()}`),console.log(),X.length>0){console.log("Tables:"),console.log();let U=Math.max(...X.map((A)=>A.name.length)),H=U+2,z="Table".padEnd(H)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(z),console.log("-".repeat(z.length));for(let A of X){let W=A.name.padEnd(U+2),Q=A.rowCount.toLocaleString().padStart(12),R=(A.columns||0).toString().padStart(10),O=(A.indexes||0).toString().padStart(10);console.log(`${W}${Q}${R}${O}`)}}else console.log("-- No tables found");return{dialect:Z,database:$,tables:X,totalTables:X.length,totalRows:G}}catch(Y){throw console.error("-- Failed to get database info:",Y),Y}}async function x6(){return hX()}qZ();h8();async function bX(Z={}){let $=g$(Z.dialect),Y=Z.aggressive||!1;if(Z.verbose)console.log(`Optimizing ${$} database${Y?" (aggressive mode)":""}...`);try{if($==="postgres"){if(Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Analyzing table: ${X}`);if(Y)await e`VACUUM FULL ANALYZE ${e(X)}`;else await e`VACUUM ANALYZE ${e(X)}`}else{if(Z.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Y)await e`VACUUM FULL`,await e`ANALYZE`;else await e`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(YZ($)){if(Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Optimizing table: ${X}`);await e`OPTIMIZE TABLE ${e(X)}`,await e`ANALYZE TABLE ${e(X)}`}else{let X=m$(),J=await e`
200
+ SELECT table_name
201
+ FROM information_schema.tables
202
+ WHERE table_schema = ${X}
203
+ `;for(let G of J){let U=G.table_name||G.TABLE_NAME;if(Z.verbose)console.log(`Optimizing table: ${U}`);await e`OPTIMIZE TABLE ${e(U)}`,await e`ANALYZE TABLE ${e(U)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(Z.verbose)console.log("Running VACUUM on SQLite database...");if(await e`VACUUM`,Z.tables&&Z.tables.length>0)for(let X of Z.tables){if(Z.verbose)console.log(`Analyzing table: ${X}`);await e`ANALYZE ${e(X)}`}else await e`ANALYZE`;if(Y){if(Z.verbose)console.log("Running aggressive SQLite optimizations...");await e`PRAGMA optimize`,await e`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${$}`)}catch(X){throw console.error("Error optimizing database:",X.message),X}}qZ();h8();async function fX(Z={}){let $=g$(Z.dialect);if(Z.verbose)console.log(`Wiping all tables from ${$} database...`);try{let Y=[];if($==="postgres")Y=(await e`
204
+ SELECT tablename
205
+ FROM pg_tables
206
+ WHERE schemaname = 'public'
207
+ `).map((J)=>J.tablename);else if(YZ($)){let X=m$();Y=(await e`
208
+ SELECT table_name
209
+ FROM information_schema.tables
210
+ WHERE table_schema = ${X}
211
+ `).map((G)=>G.table_name||G.TABLE_NAME)}else if($==="sqlite")Y=(await e`
212
+ SELECT name
213
+ FROM sqlite_master
214
+ WHERE type = 'table'
215
+ AND name NOT LIKE 'sqlite_%'
216
+ `).map((J)=>J.name);if(Y.length===0){console.log("No tables found to drop.");return}if(Z.verbose)console.log(`Found ${Y.length} tables: ${Y.join(", ")}`);if($==="postgres")for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await e`DROP TABLE IF EXISTS ${e(X)} CASCADE`}else if(YZ($)){await e`SET FOREIGN_KEY_CHECKS = 0`;for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await e`DROP TABLE IF EXISTS ${e(X)}`}await e`SET FOREIGN_KEY_CHECKS = 1`}else if($==="sqlite"){await e`PRAGMA foreign_keys = OFF`;for(let X of Y){if(Z.verbose)console.log(`Dropping table: ${X}`);await e`DROP TABLE IF EXISTS ${e(X)}`}await e`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${Y.length} tables`)}catch(Y){throw console.error("Error wiping database:",Y.message),Y}}async function v6(Z){let X=await(XZ().raw([Z]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(X,null,2)),X}async function y6(Z,$={}){let Y=XZ(),X=$.params?JSON.parse($.params):void 0,J=await Y.file(Z,X);return console.log(JSON.stringify(J)),J}qZ();async function gX(Z,$={}){let Y=f.dialect||"postgres",X=$.verbose??!0;if(X)console.log(`-- Inspecting table: ${Z}`),console.log(`-- Dialect: ${Y}`),console.log();try{let J=XZ(),G=[],U=[],H=await J.unsafe(`SELECT COUNT(*) as count FROM ${Z}`),z=Number(H[0]?.count||0);if(Y==="postgres"){let A=await J.unsafe(`
217
+ SELECT
218
+ c.column_name,
219
+ c.data_type,
220
+ c.is_nullable,
221
+ c.column_default,
222
+ CASE
223
+ WHEN pk.column_name IS NOT NULL THEN true
224
+ ELSE false
225
+ END as is_primary_key,
226
+ CASE
227
+ WHEN fk.column_name IS NOT NULL THEN true
228
+ ELSE false
229
+ END as is_foreign_key
230
+ FROM information_schema.columns c
231
+ LEFT JOIN (
232
+ SELECT ku.column_name
233
+ FROM information_schema.table_constraints tc
234
+ JOIN information_schema.key_column_usage ku
235
+ ON tc.constraint_name = ku.constraint_name
236
+ WHERE tc.constraint_type = 'PRIMARY KEY'
237
+ AND tc.table_name = $1
238
+ ) pk ON c.column_name = pk.column_name
239
+ LEFT JOIN (
240
+ SELECT ku.column_name
241
+ FROM information_schema.table_constraints tc
242
+ JOIN information_schema.key_column_usage ku
243
+ ON tc.constraint_name = ku.constraint_name
244
+ WHERE tc.constraint_type = 'FOREIGN KEY'
245
+ AND tc.table_name = $1
246
+ ) fk ON c.column_name = fk.column_name
247
+ WHERE c.table_name = $1
248
+ ORDER BY c.ordinal_position
249
+ `,[Z]);for(let Q of A)G.push({name:Q.column_name,type:Q.data_type,nullable:Q.is_nullable==="YES",default:Q.column_default,isPrimaryKey:Q.is_primary_key,isForeignKey:Q.is_foreign_key});let W=await J.unsafe(`
250
+ SELECT
251
+ i.indexname as name,
252
+ i.indexdef,
253
+ ix.indisunique as is_unique
254
+ FROM pg_indexes i
255
+ JOIN pg_class c ON c.relname = i.indexname
256
+ JOIN pg_index ix ON ix.indexrelid = c.oid
257
+ WHERE i.tablename = $1
258
+ `,[Z]);for(let Q of W){let R=Q.indexdef?.match(/\(([^)]+)\)/),N=(R?R[1]:"").split(",").map((_)=>_.trim());U.push({name:Q.name,columns:N,unique:Q.is_unique})}}else if(YZ(Y)){let A=await J.unsafe(`
259
+ SELECT
260
+ COLUMN_NAME as column_name,
261
+ DATA_TYPE as data_type,
262
+ IS_NULLABLE as is_nullable,
263
+ COLUMN_DEFAULT as column_default,
264
+ COLUMN_KEY as column_key
265
+ FROM information_schema.COLUMNS
266
+ WHERE TABLE_NAME = ?
267
+ AND TABLE_SCHEMA = DATABASE()
268
+ ORDER BY ORDINAL_POSITION
269
+ `,[Z]);for(let R of A)G.push({name:R.column_name,type:R.data_type,nullable:R.is_nullable==="YES",default:R.column_default,isPrimaryKey:R.column_key==="PRI",isForeignKey:R.column_key==="MUL"});let W=await J.unsafe(`
270
+ SHOW INDEXES FROM ${Z}
271
+ `),Q=new Map;for(let R of W){let O=R.Key_name;if(!Q.has(O))Q.set(O,{columns:[],unique:R.Non_unique===0});Q.get(O).columns.push(R.Column_name)}for(let[R,O]of Q)U.push({name:R,columns:O.columns,unique:O.unique})}else if(Y==="sqlite"){let A=await J.unsafe(`PRAGMA table_info(${Z})`);for(let Q of A)G.push({name:Q.name,type:Q.type,nullable:Q.notnull===0,default:Q.dflt_value,isPrimaryKey:Q.pk===1});let W=await J.unsafe(`PRAGMA index_list(${Z})`);for(let Q of W){let R=await J.unsafe(`PRAGMA index_info(${Q.name})`);U.push({name:Q.name,columns:R.map((O)=>O.name),unique:Q.unique===1})}}if(X){console.log(`Table: ${Z}`),console.log(`Rows: ${z.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let A=Math.max(...G.map((N)=>N.name.length),10),W=Math.max(...G.map((N)=>N.type.length),10),Q=A+2,R=W+2,O=`${"Name".padEnd(Q)+"Type".padEnd(R)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(O),console.log("-".repeat(O.length));for(let N of G){let _=N.name.padEnd(Q),F=N.type.padEnd(R),L=(N.nullable?"YES":"NO").padEnd(10),K=String(N.default||"").padEnd(20),I=[N.isPrimaryKey?"PK":"",N.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${_}${F}${L}${K}${I}`)}if(console.log(),U.length>0){console.log("Indexes:"),console.log();for(let N of U){let _=N.unique?" (UNIQUE)":"";console.log(` - ${N.name}${_}: [${N.columns.join(", ")}]`)}console.log()}}return{tableName:Z,rowCount:z,columns:G,indexes:U}}catch(J){throw console.error(`-- Failed to inspect table ${Z}:`,J),J}}async function h6(Z,$={}){return gX(Z,$)}async function b6(Z,$={}){let Y=await W8({modelsDir:Z}),X=$7(Y);return console.log(JSON.stringify(X,null,2)),{models:Y,schema:X}}qZ();function pX(Z){let $=Z.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test($))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test($))return"number";if(/timestamp|datetime|date|time/.test($))return"datetime";if(/json/.test($))return"json";return"string"}function f6(Z){if(/ies$/i.test(Z))return Z.replace(/ies$/i,"y");if(/ses$/i.test(Z))return Z.replace(/es$/i,"");if(/s$/i.test(Z)&&!/ss$/i.test(Z))return Z.replace(/s$/i,"");return Z}function g6(Z){return Z.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function U0(Z){return g6(f6(Z))}async function dX(Z,$){if($==="postgres")return(await Z.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((J)=>J.table_name);if(YZ($))return(await Z.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((J)=>J.table_name??J.TABLE_NAME);return(await Z.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((X)=>X.name)}async function p6(Z,$,Y){if($==="sqlite")return(await Z.unsafe(`PRAGMA table_info(${Y})`)).map((G)=>({name:G.name,sqlType:String(G.type||""),nullable:Number(G.notnull)===0,isPrimaryKey:Number(G.pk)>0}));if($==="postgres")return(await Z.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
272
+ (SELECT COUNT(*) FROM information_schema.table_constraints tc
273
+ JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
274
+ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
275
+ FROM information_schema.columns c
276
+ WHERE c.table_name = $1 AND c.table_schema = 'public'
277
+ ORDER BY c.ordinal_position`,[Y])).map((G)=>({name:G.column_name,sqlType:String(G.data_type||""),nullable:String(G.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(G.is_pk)>0}));return(await Z.unsafe(`SELECT column_name, data_type, is_nullable, column_key
278
+ FROM information_schema.columns
279
+ WHERE table_name = ? AND table_schema = DATABASE()
280
+ ORDER BY ordinal_position`,[Y])).map((J)=>({name:J.column_name??J.COLUMN_NAME,sqlType:String(J.data_type??J.DATA_TYPE??""),nullable:String(J.is_nullable??J.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(J.column_key??J.COLUMN_KEY).toUpperCase()==="PRI"}))}function mX(Z,$){let Y=U0(Z),X=$.find((G)=>G.isPrimaryKey)?.name??"id",J=$.map((G)=>{let U=[`type: '${pX(G.sqlType)}'`];if(!G.nullable&&!G.isPrimaryKey)U.push("required: true");return` ${G.name}: { ${U.join(", ")} },`}).join(`
281
+ `);return`export const ${Y} = defineModel({
282
+ name: '${Y}',
283
+ table: '${Z}',
284
+ primaryKey: '${X}',
285
+ attributes: {
286
+ ${J}
287
+ },
288
+ })
289
+ `}async function z0(Z={}){let $=f.dialect||"postgres",Y=XZ(),X=Z.tables?.length?Z.tables:await dX(Y,$),J=[];for(let G of X){let U=await p6(Y,$,G);if(!U.length)continue;J.push({table:G,modelName:U0(G),primaryKey:U.find((H)=>H.isPrimaryKey)?.name??"id",columns:U,source:mX(G,U)})}return J}function H0(Z,$,Y){if(Y?.enumValues&&Y.enumValues.length>0)return"enum";let X=String(Z||"").toLowerCase().trim(),J=X.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(YZ($)&&/^tinyint\(1\)/.test(X))return"boolean";if(/^bool/.test(J))return"boolean";if(J==="int8"||J==="bigint"||J==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(J))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(J)){let G=X.match(/\((\d+)\)/),U=G?Number(G[1]):void 0;if(YZ($))return"string";return U!==void 0&&U>255?"text":"string"}if(/text|clob/.test(J))return"text";if(J==="float8"||/^double/.test(J))return"double";if(/^(?:real|float4|float)/.test(J))return"float";if(/^(?:numeric|decimal|money)/.test(J))return"decimal";if(J==="date")return"date";if(J==="timestamptz"||/\bwith time zone\b/.test(X))return"timestamptz";if(/^(?:timestamp|datetime)/.test(J))return"datetime";if(/^time/.test(J))return"string";if(/json/.test(J))return"json";if(/^enum/.test(J))return"enum";return"string"}function d6(Z,$,Y){return H0(String($||Z||""),"mysql",{enumValues:Y})}function m6(Z){let $=String(Z||"").trim().match(/^varchar\((\d+)\)/i);if(!$)return;let Y=Number($[1]);return Number.isSafeInteger(Y)&&Y>0?Y:void 0}function O9(Z){let $=String(Z??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function c6(Z,$){let Y=await Z.unsafe(`PRAGMA table_info(${JSON.stringify($)})`),X=await Z.unsafe(`PRAGMA index_list(${JSON.stringify($)})`),J=await Z.unsafe(`PRAGMA foreign_key_list(${JSON.stringify($)})`),G=await Z.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[$]),U=String(G?.[0]?.sql??""),H=new Map;for(let Q of J)H.set(String(Q.from),{table:String(Q.table),column:String(Q.to??"id"),onDelete:O9(Q.on_delete),onUpdate:O9(Q.on_update)});let z=[],A=new Set;for(let Q of X){let R=String(Q.origin??""),O=String(Q.name??"");if(R==="pk"||O.startsWith("sqlite_autoindex_"))continue;let _=(await Z.unsafe(`PRAGMA index_info(${JSON.stringify(O)})`)).map((L)=>String(L.name)).filter(Boolean);if(_.length===0)continue;let F=Number(Q.unique)===1;if(F&&_.length===1)A.add(_[0]);z.push({name:O,columns:_,type:F?"unique":"index"})}let W=Y.map((Q)=>{let R=String(Q.name),O=u6(U,R),N=Number(Q.pk)>0,_=Q.dflt_value,F=_!==null&&_!==void 0;return{name:R,type:H0(String(Q.type??""),"sqlite",{enumValues:O}),isPrimaryKey:N,isUnique:A.has(R),isNullable:N?!1:Number(Q.notnull)===0,hasDefault:F,defaultValue:F?A0(_):void 0,enumValues:O,references:H.get(R)}});return{table:$,columns:W,indexes:z}}function u6(Z,$){if(!Z)return;let Y=new RegExp(`(?:"${$}"|\`${$}\`|\\b${$}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),X=Z.match(Y);if(!X)return;let J=X[1].split(",").map((G)=>G.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((G)=>G.length>0);return J.length>0?J:void 0}function A0(Z){if(typeof Z==="number"||typeof Z==="boolean")return Z;return String(Z)}async function cX(Z){let $=await Z.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
290
+ FROM pg_type t
291
+ JOIN pg_enum e ON e.enumtypid = t.oid
292
+ JOIN pg_namespace n ON n.oid = t.typnamespace
293
+ WHERE n.nspname = 'public'
294
+ ORDER BY t.typname, e.enumsortorder`),Y=new Map;for(let X of $){let J=String(X.type_name),G=Y.get(J);if(G)G.push(String(X.label));else Y.set(J,[String(X.label)])}return Y}function n6(Z,$,Y){let X=Y.get($),J=H0(String(Z||$||""),"postgres",{enumValues:X});return X?{type:J,enumValues:X,enumTypeName:$}:{type:J}}async function i6(Z,$,Y){let X=Y??await cX(Z),J=await Z.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
295
+ (SELECT COUNT(*) FROM information_schema.table_constraints tc
296
+ JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
297
+ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
298
+ FROM information_schema.columns c
299
+ WHERE c.table_name = $1 AND c.table_schema = 'public'
300
+ ORDER BY c.ordinal_position`,[$]),G=await Z.unsafe(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
301
+ a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
302
+ pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
303
+ FROM pg_class t
304
+ JOIN pg_index ix ON t.oid = ix.indrelid
305
+ JOIN pg_class i ON i.oid = ix.indexrelid
306
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
307
+ WHERE t.relname = $1 AND t.relkind = 'r'
308
+ ORDER BY i.relname, ord`,[$]),U=await Z.unsafe(`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column,
309
+ tc.constraint_name, rc.delete_rule, rc.update_rule
310
+ FROM information_schema.table_constraints tc
311
+ JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
312
+ JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
313
+ JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
314
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[$]),H=new Map,z=new Map;for(let R of U){let O=String(R.constraint_name);z.set(O,(z.get(O)??0)+1)}for(let R of U){let O=String(R.column_name),N=H.get(O),_=String(R.constraint_name),F=z.get(_)===1?[...new Set([...N?.constraintNames??[],_])]:N?.constraintNames;H.set(O,N?{...N,constraintNames:F}:{table:String(R.ref_table),column:String(R.ref_column??"id"),onDelete:O9(R.delete_rule),onUpdate:O9(R.update_rule),constraintNames:F})}let{indexes:A,uniqueColumns:W}=uX($,G.map((R)=>({indexName:String(R.index_name),isUnique:R.is_unique===!0||R.is_unique==="t",isPrimary:R.is_primary===!0||R.is_primary==="t",column:String(R.column_name),where:R.where_clause?String(R.where_clause):void 0}))),Q=J.map((R)=>{let O=String(R.column_name),N=Number(R.is_pk)>0,_=R.column_default==null?null:String(R.column_default),F=_!=null&&/nextval\(/i.test(_),L=_!=null&&!F;return{name:O,...n6(String(R.data_type??""),R.udt_name==null?"":String(R.udt_name),X),isPrimaryKey:N,isUnique:W.has(O),isNullable:N?!1:String(R.is_nullable).toUpperCase()==="YES",hasDefault:L,defaultValue:L?A0(_):void 0,references:H.get(O)}});return{table:$,columns:Q,indexes:A}}async function l6(Z,$){let Y=await Z.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
315
+ FROM information_schema.columns
316
+ WHERE table_name = ? AND table_schema = DATABASE()
317
+ ORDER BY ordinal_position`,[$]),X=await Z.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
318
+ FROM information_schema.statistics
319
+ WHERE table_name = ? AND table_schema = DATABASE()
320
+ ORDER BY index_name, seq_in_index`,[$]),J=await Z.unsafe(`SELECT kcu.column_name, kcu.referenced_table_name AS ref_table, kcu.referenced_column_name AS ref_column,
321
+ kcu.constraint_name, rc.delete_rule, rc.update_rule
322
+ FROM information_schema.key_column_usage kcu
323
+ JOIN information_schema.referential_constraints rc
324
+ ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
325
+ WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[$]),G=new Map,U=new Map;for(let W of J){let Q=String(W.constraint_name??W.CONSTRAINT_NAME);U.set(Q,(U.get(Q)??0)+1)}for(let W of J){let Q=String(W.column_name??W.COLUMN_NAME),R=G.get(Q),O=String(W.constraint_name??W.CONSTRAINT_NAME),N=U.get(O)===1?[...new Set([...R?.constraintNames??[],O])]:R?.constraintNames;G.set(Q,R?{...R,constraintNames:N}:{table:String(W.ref_table??W.REF_TABLE),column:String(W.ref_column??W.REF_COLUMN??"id"),onDelete:O9(W.delete_rule??W.DELETE_RULE),onUpdate:O9(W.update_rule??W.UPDATE_RULE),constraintNames:N})}let{indexes:H,uniqueColumns:z}=uX($,X.map((W)=>({indexName:String(W.index_name??W.INDEX_NAME),isUnique:Number(W.non_unique??W.NON_UNIQUE)===0,isPrimary:String(W.index_name??W.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(W.column_name??W.COLUMN_NAME)}))),A=Y.map((W)=>{let Q=String(W.column_name??W.COLUMN_NAME),R=String(W.column_type??W.COLUMN_TYPE??""),O=s6(R),_=String(W.column_key??W.COLUMN_KEY??"").toUpperCase()==="PRI",F=W.column_default??W.COLUMN_DEFAULT,L=F!=null;return{name:Q,type:d6(W.data_type??W.DATA_TYPE,R,O),isPrimaryKey:_,isUnique:z.has(Q),isNullable:_?!1:String(W.is_nullable??W.IS_NULLABLE).toUpperCase()==="YES",hasDefault:L,defaultValue:L?A0(F):void 0,enumValues:O,maxLength:m6(R),references:G.get(Q)}});return{table:$,columns:A,indexes:H}}function s6(Z){let $=Z.match(/^enum\((.*)\)$/i);if(!$)return;return $[1].split(",").map((Y)=>Y.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((Y)=>Y.length>0)}function uX(Z,$){let Y=new Map;for(let G of $){if(G.isPrimary)continue;let U=Y.get(G.indexName)??{isUnique:G.isUnique,isPrimary:G.isPrimary,columns:[],where:G.where};U.columns.push(G.column),Y.set(G.indexName,U)}let X=[],J=new Set;for(let[G,U]of Y){if(U.columns.length===0)continue;if(U.isUnique&&U.columns.length===1)J.add(U.columns[0]);X.push({name:G,columns:U.columns,type:U.isUnique?"unique":"index",where:U.where})}return{indexes:X,uniqueColumns:J}}async function nX(Z,$={}){let Y=Z||f.dialect||"postgres",X=XZ(),G=(($.tables?.length)?$.tables:await dX(X,Y)).filter((z)=>z!=="migrations"),U=Y==="postgres"?await cX(X):void 0,H=[];for(let z of G){let A;if(Y==="sqlite")A=await c6(X,z);else if(Y==="postgres")A=await i6(X,z,U);else A=await l6(X,z);if(A.columns.length>0)H.push(A)}return{dialect:Y,tables:H}}import{existsSync as W0,mkdirSync as o6,writeFileSync as r6}from"fs";import{dirname as iX,join as j0}from"path";import lX from"process";function a6(Z){let $=Z;while($!==iX($)){if(W0(j0($,"package.json")))return $;$=iX($)}return lX.cwd()}async function t6(Z,$={}){let Y=a6(lX.cwd()),X=$.dir||j0(Y,"app/Models");if(!W0(X))o6(X,{recursive:!0}),console.log(`-- Created models directory: ${X}`);let J=Z.charAt(0).toUpperCase()+Z.slice(1),G=$.table||`${Z.toLowerCase()}s`,U=`${J}.ts`,H=j0(X,U);if(W0(H))throw console.error(`-- Model already exists: ${H}`),Error(`Model already exists: ${H}`);let A=$.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
326
+ updated_at: { validation: { rule: v.date() } },`:"",W=`import { v } from '@stacksjs/ts-validation'
327
+ import { defineModel } from 'bun-query-builder'
328
+
329
+ const model = defineModel({
330
+ name: '${J}',
331
+ table: '${G}',
332
+ primaryKey: 'id',
333
+ attributes: {
334
+ id: { validation: { rule: v.integer() } },
335
+ ${A}
336
+ // Add your model attributes here
337
+ // Example:
338
+ // name: { validation: { rule: v.string() } },
339
+ // email: { unique: true, validation: { rule: v.string().email() } },
340
+ // age: { default: 0, validation: { rule: v.number().min(0) } },
341
+ },
342
+ })
343
+
344
+ export default model
345
+ `;r6(H,W),console.log(`-- \u2713 Created model: ${H}`),console.log(`-- Table: ${G}`)}async function e6(Z,$={}){return Q0(Z,$)}qZ();import{existsSync as aX,readFileSync as YU,unlinkSync as XU}from"fs";import{join as JU}from"path";import{existsSync as ZU}from"fs";import{dirname as sX,isAbsolute as $U,join as rX}from"path";import oX from"process";function _0(Z=oX.cwd()){let $=Z;while($!==sX($)){if(ZU(rX($,"package.json")))return $;$=sX($)}return oX.cwd()}function C8(Z,$="database/migrations"){let Y=$||"database/migrations";return $U(Y)?Y:rX(Z??_0(),Y)}function GU(Z){let $=[],Y="",X=null;for(let J=0;J<Z.length;J++){let G=Z[J];if(X){if(Y+=G,G===X)if(Z[J+1]===X)Y+=Z[J+1],J++;else X=null;continue}if(G==="'"||G==='"'||G==="`"){X=G,Y+=G;continue}if(G==="-"&&Z[J+1]==="-"){let U=Z.indexOf(`
346
+ `,J);J=U===-1?Z.length:U;continue}if(G==="/"&&Z[J+1]==="*"){let U=Z.indexOf("*/",J+2);J=U===-1?Z.length:U+1;continue}if(G===";"){if(Y.trim())$.push(Y.trim());Y="";continue}Y+=G}if(Y.trim())$.push(Y.trim());return $}function UU(Z,$=f.dialect){let Y=(G)=>YZ($)?`\`${G}\``:`"${G}"`,X=[],J=[];for(let G of GU(Z)){let U;if(U=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(G))X.push(`DROP TABLE IF EXISTS ${Y(U[1])}`);else if(U=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(G))if($==="sqlite")J.push(G);else if(YZ($)&&/\bFOREIGN\s+KEY\b/i.test(U[3]??""))X.push(`ALTER TABLE ${Y(U[1])} DROP FOREIGN KEY ${Y(U[2])}`);else X.push(`ALTER TABLE ${Y(U[1])} DROP CONSTRAINT ${Y(U[2])}`);else if(U=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(G)){let H=U[2]??U[3]??U[4];if(U[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(U[4]))J.push(G);else X.push(`ALTER TABLE ${Y(U[1])} DROP COLUMN ${Y(H)}`)}else if(U=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(G))X.push(YZ($)&&U[2]?`DROP INDEX ${Y(U[1])} ON ${Y(U[2])}`:`DROP INDEX IF EXISTS ${Y(U[1])}`);else J.push(G)}return{down:X.reverse(),skipped:J}}async function zU(Z={}){let $=Z.steps||1,Y=Z.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let X=XZ(),J=[];try{J=await X.unsafe(`
347
+ SELECT migration, executed_at
348
+ FROM migrations
349
+ ORDER BY executed_at DESC, migration DESC
350
+ `)}catch(z){console.log("-- Migrations table not found. Nothing to rollback.",z);return}if(J.length===0){console.log("-- No migrations to rollback");return}let G=J.slice(0,$);console.log(`-- Found ${J.length} executed migrations`),console.log(`-- Rolling back ${G.length} migration(s):`),console.log();for(let z of G)console.log(` - ${z.migration}`);console.log();let U=C8(void 0,f.migrationDir),H=!1;for(let z of G)try{let A=JU(U,z.migration);if(Y&&aX(A)){let Q=YU(A,"utf8"),{down:R,skipped:O}=UU(Q);for(let N of R)await X.unsafe(N),console.log(`-- \u21A9 ${N}`),H=!0;if(O.length>0)console.log(`-- \u26A0\uFE0F ${O.length} statement(s) in ${z.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let W=`DELETE FROM migrations WHERE migration = ${s(1)}`;if(await X.unsafe(W,[z.migration]),console.log(`-- \u2713 Removed migration record: ${z.migration}`),Z.deleteFiles&&aX(A))XU(A),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${z.migration}`)}catch(A){throw console.error(`-- \u2717 Failed to rollback migration ${z.migration}:`,A),A}if(console.log(),Y)console.log(H?"-- \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(X){throw console.error("-- Rollback failed:",X),X}}qZ();import{existsSync as HU,readdirSync as AU}from"fs";async function tX(){let Z=f.dialect||"postgres",$=K8(Z),Y=C8(void 0,f.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${Z}`),console.log(`-- SQL directory: ${Y}`),console.log(),!HU(Y))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let J=AU(Y).filter((G)=>G.endsWith(".sql")).sort();if(J.length===0)return console.log("-- No migration files found"),[];try{let G=XZ(),U=[];try{U=await G.unsafe($.getExecutedMigrationsQuery())}catch(Q){console.log("-- Migrations table not found. All migrations are pending.",Q),console.log()}let H=new Map(U.map((Q)=>[Q.migration,Q.executed_at])),z=J.map((Q)=>({file:Q,status:H.has(Q)?"executed":"pending",executedAt:H.get(Q)})),A=z.filter((Q)=>Q.status==="executed"),W=z.filter((Q)=>Q.status==="pending");if(console.log(`-- Total migrations: ${J.length}`),console.log(`-- Executed: ${A.length}`),console.log(`-- Pending: ${W.length}`),console.log(),A.length>0){console.log("\u2713 Executed Migrations:");for(let Q of A)console.log(` - ${Q.file} ${Q.executedAt?`(${new Date(Q.executedAt).toLocaleString()})`:""}`);console.log()}if(W.length>0){console.log("\u25CB Pending Migrations:");for(let Q of W)console.log(` - ${Q.file}`);console.log()}return z}catch(G){throw console.error("-- Failed to get migration status:",G),G}}async function WU(){return tX()}import{readdirSync as jU}from"fs";import{extname as V0,join as eX}from"path";import QU from"process";async function Z1(Z,$={}){let Y=$.dir||eX(QU.cwd(),"app/Models");try{let X=jU(Y),J=X.find((W)=>{return W.replace(V0(W),"").toLowerCase()===Z.toLowerCase()});if(!J){console.error(`Model "${Z}" not found in ${Y}`),console.log(`Available models: ${X.filter((W)=>[".ts",".js"].includes(V0(W))).map((W)=>W.replace(V0(W),"")).join(", ")}`);return}let U=await import(eX(Y,J)),H=U.default||U[Object.keys(U)[0]];if(!H||!H.name){console.error(`Invalid model file: ${J}`);return}let z={name:H.name,table:H.table||`${H.name.toLowerCase()}s`,primaryKey:H.primaryKey||"id",attributes:H.attributes||{},relations:H.relations,scopes:H.scopes,indexes:H.indexes,timestamps:H.timestamps!==!1,softDeletes:H.softDeletes===!0},A=[];if(H.beforeCreate)A.push("beforeCreate");if(H.afterCreate)A.push("afterCreate");if(H.beforeUpdate)A.push("beforeUpdate");if(H.afterUpdate)A.push("afterUpdate");if(H.beforeDelete)A.push("beforeDelete");if(H.afterDelete)A.push("afterDelete");if(A.length>0)z.hooks=A;if($.json)return console.log(JSON.stringify(z,null,2)),z;console.log(`
351
+ \uD83D\uDCE6 Model: ${z.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: ${z.table}`),console.log(`Primary Key: ${z.primaryKey}`),console.log(`Timestamps: ${z.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${z.softDeletes?"\u2713":"\u2717"}`),console.log(`
352
+ \uD83D\uDCCB Attributes (${Object.keys(z.attributes).length}):`);for(let[W,Q]of Object.entries(z.attributes)){let R=Q.type||"string",O=Q.required?"(required)":"",N=Q.unique?"(unique)":"",_=Q.default!==void 0?`= ${JSON.stringify(Q.default)}`:"";console.log(` \u2022 ${W}: ${R} ${O} ${N} ${_}`.trim())}if(z.relations&&Object.keys(z.relations).length>0){console.log(`
353
+ \uD83D\uDD17 Relations (${Object.keys(z.relations).length}):`);for(let[W,Q]of Object.entries(z.relations)){let R=Q.type||"unknown",O=Q.model||Q.table||"unknown";console.log(` \u2022 ${W}: ${R} \u2192 ${O}`)}}if(z.scopes&&Object.keys(z.scopes).length>0){console.log(`
354
+ \uD83D\uDD0D Scopes (${Object.keys(z.scopes).length}):`);for(let W of Object.keys(z.scopes))console.log(` \u2022 ${W}()`)}if(z.hooks&&z.hooks.length>0){console.log(`
355
+ \uD83E\uDE9D Hooks (${z.hooks.length}):`);for(let W of z.hooks)console.log(` \u2022 ${W}`)}if(z.indexes&&z.indexes.length>0){console.log(`
356
+ \uD83D\uDCC7 Indexes (${z.indexes.length}):`);for(let W of z.indexes){let Q=Array.isArray(W.columns)?W.columns.join(", "):W.columns,R=W.unique?"(unique)":"";console.log(` \u2022 ${W.name||"unnamed"}: [${Q}] ${R}`.trim())}}return console.log(),z}catch(X){throw console.error(`Error loading model "${Z}":`,X.message),X}}async function _U(){let $=await XZ().ping();return console.log($?"OK":"NOT READY"),$}h8();import{readdirSync as VU,readFileSync as $1,statSync as KU}from"fs";import{extname as Y1,join as LU}from"path";async function X1(Z,$={}){let Y=[];try{let X=KU(Z),J=[];if(X.isDirectory())J=VU(Z).filter((z)=>Y1(z)===".sql").map((z)=>LU(Z,z));else if(X.isFile()&&Y1(Z)===".sql")J=[Z];else return console.error("Path must be a .sql file or directory containing .sql files"),Y;if(J.length===0)return console.log("No .sql files found"),Y;if($.verbose)console.log(`Analyzing ${J.length} SQL file(s)...
357
+ `);for(let H of J)try{let z=$1(H,"utf8").trim();if(!z){if($.verbose)console.log(`\u2298 ${H}: empty file`);continue}if($.verbose)console.log(`\uD83D\uDCC4 ${H}`),console.log(` Query: ${z.substring(0,60)}${z.length>60?"...":""}`);let A=await e`EXPLAIN ${e.unsafe(z)}`;if(Y.push({file:H,query:z,plan:Array.isArray(A)?A:[A]}),$.verbose&&!$.json){if(console.log(" Plan:"),Array.isArray(A))for(let W of A)if(typeof W==="string")console.log(` ${W}`);else if(W["QUERY PLAN"])console.log(` ${W["QUERY PLAN"]}`);else if(W.plan)console.log(` ${JSON.stringify(W.plan)}`);else console.log(` ${JSON.stringify(W)}`);console.log()}}catch(z){if(Y.push({file:H,query:$1(H,"utf8").trim(),plan:[],error:z.message}),$.verbose)console.log(` \u2717 Error: ${z.message}
358
+ `)}let G=Y.filter((H)=>!H.error).length,U=Y.filter((H)=>H.error).length;if($.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: ${G} successful, ${U} failed`);if($.json)console.log(JSON.stringify(Y,null,2));return Y}catch(X){throw console.error("Error explaining queries:",X.message),X}}import{writeFileSync as FU}from"fs";import{join as BU}from"path";import RU from"process";async function J1(Z={}){let $=Z.dir||BU(RU.cwd(),"app/Models"),Y=Z.format||"mermaid";try{let X=await W8({modelsDir:$});if(!X||Object.keys(X).length===0)return console.error("No models found"),"";let J="";if(Y==="mermaid")J=OU(X);else if(Y==="dot")J=DU(X);else return console.error(`Unsupported format: ${Y}`),"";if(Z.output)FU(Z.output,J,"utf8"),console.log(`\u2713 Diagram written to: ${Z.output}`);else console.log(J);return J}catch(X){throw console.error("Error generating diagram:",X.message),X}}function OU(Z){let $=["erDiagram"];for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.attributes||{};$.push(` ${J} {`);for(let[U,H]of Object.entries(G)){let z=H.type||"string",A=X.primaryKey===U?"PK":"",W=H.unique?"UK":"",Q=[A,W].filter(Boolean).join(","),R=Q?` "${Q}"`:"";$.push(` ${z} ${U}${R}`)}$.push(" }")}for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.relations||{};for(let[U,H]of Object.entries(G)){let{type:z,model:A}=H,W=Z[A]?.table||`${A?.toLowerCase()}s`||"unknown",Q="";if(z==="hasOne")Q="||--||";else if(z==="hasMany")Q="||--o{";else if(z==="belongsTo")Q="}o--||";else if(z==="belongsToMany"||z==="manyToMany")Q="}o--o{";else Q="||--||";$.push(` ${J} ${Q} ${W} : "${U}"`)}}return $.join(`
359
+ `)}function DU(Z){let $=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.attributes||{},U=[];for(let[z,A]of Object.entries(G)){let W=A.type||"string",Q=X.primaryKey===z?" (PK)":"",R=A.unique?" (UK)":"";U.push(`${z}: ${W}${Q}${R}`)}let H=`${U.join("\\l")}\\l`;$.push(` ${J} [label="{${J}|${H}}"];`)}$.push("");for(let[Y,X]of Object.entries(Z)){let J=X.table||`${Y.toLowerCase()}s`,G=X.relations||{};for(let[U,H]of Object.entries(G)){let{type:z,model:A}=H,W=Z[A]?.table||`${A?.toLowerCase()}s`||"unknown",Q="";if(z==="hasOne")Q="arrowhead=none, arrowtail=normal";else if(z==="hasMany")Q="arrowhead=crow, arrowtail=none";else if(z==="belongsTo")Q="arrowhead=normal, arrowtail=none";else if(z==="belongsToMany"||z==="manyToMany")Q="arrowhead=crow, arrowtail=crow";$.push(` ${J} -> ${W} [label="${U}", ${Q}];`)}}return $.push("}"),$.join(`
360
+ `)}import{existsSync as Y7,mkdirSync as EU,readdirSync as IU,writeFileSync as MU}from"fs";import{dirname as G1,join as p8}from"path";import u9 from"process";function X7(Z){let $=Z;while($!==G1($)){if(Y7(p8($,"package.json")))return $;$=G1($)}return u9.cwd()}async function U1(Z){if(!Y7(Z))return console.log(`-- Seeders directory not found: ${Z}`),[];let Y=IU(Z).sort((J,G)=>J.localeCompare(G)).filter((J)=>(J.endsWith(".ts")||J.endsWith(".js"))&&J!=="index.ts"&&J!=="index.js"),X=[];for(let J of Y){let G=p8(Z,J);try{let U=await import(G),H=U.default||U[Object.keys(U)[0]];if(H&&typeof H==="function"){let z=new H;if(z&&typeof z.run==="function")X.push({name:J.replace(/\.(ts|js)$/,""),className:String(H.name||""),instance:z})}}catch(U){console.error(`-- Failed to load seeder ${J}:`,U)}}return X.sort((J,G)=>J.instance.order-G.instance.order),X}async function z1(Z={}){let $=X7(u9.cwd()),Y=Z.seedersDir||p8($,"database/seeders"),X=Z.verbose??!0;if(X)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${Y}`);let J=await U1(Y);if(J.length===0){console.log("-- No seeders found");return}if(X)console.log(`-- Found ${J.length} seeder(s)`);let G=XZ();for(let{name:U,instance:H}of J)try{if(X)console.log(`-- Seeding: ${U}`);if(await H.run(G),X)console.log(`-- \u2713 Seeded: ${U}`)}catch(z){throw console.error(`-- \u2717 Failed to seed ${U}:`,z),z}if(X)console.log("-- All seeders completed successfully")}async function wU(Z,$={}){let Y=X7(u9.cwd()),X=p8(Y,"database/seeders"),J=$.verbose??!0;if(J)console.log(`-- Running seeder: ${Z}`);let G=await U1(X),U=G.find((z)=>z.className===Z)??G.find((z)=>z.name===Z);if(!U){let z=G.map((A)=>A.className||A.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${Z}. Available: ${z}`),Error(`Seeder not found: ${Z}. Available: ${z}`)}let H=XZ();try{if(await U.instance.run(H),J)console.log(`-- \u2713 Seeder completed: ${Z}`)}catch(z){throw console.error(`-- \u2717 Seeder failed: ${Z}`,z),z}}async function CU(Z){let $=X7(u9.cwd()),Y=p8($,"database/seeders");if(!Y7(Y))EU(Y,{recursive:!0}),console.log(`-- Created seeders directory: ${Y}`);let J=`${Z.replace(/Seeder$/i,"")}Seeder`,G=`${J}.ts`,U=p8(Y,G);if(Y7(U))throw console.error(`-- Seeder already exists: ${U}`),Error(`Seeder already exists: ${U}`);let H=`import type { QueryBuilder } from 'bun-query-builder'
361
+ import { Seeder } from 'bun-query-builder'
362
+ import { faker } from '@stacksjs/ts-faker'
363
+
364
+ export default class ${J} extends Seeder {
365
+ /**
366
+ * Run the database seeds.
367
+ */
368
+ async run(qb: QueryBuilder): Promise<void> {
369
+ console.log('Seeding: ${J}')
370
+
371
+ // Example: Create 10 records with faker
372
+ const records = Array.from({ length: 10 }, () => ({
373
+ name: faker.person.fullName(),
374
+ email: faker.internet.email().toLowerCase(),
375
+ age: faker.number.int({ min: 18, max: 80 }),
376
+ created_at: faker.date.past(),
377
+ updated_at: new Date(),
378
+ }))
379
+
380
+ // Option 1: Kysely-style API
381
+ await qb.insertInto('table_name').values(records).execute()
382
+
383
+ // Option 2: Laravel-style API (equivalent)
384
+ // await qb.table('table_name').insert(records).execute()
385
+
386
+ console.log(\`\u2713 Seeded \${records.length} records\`)
387
+
388
+ // For large datasets, use batch inserts:
389
+ // const batchSize = 100
390
+ // for (let i = 0; i < records.length; i += batchSize) {
391
+ // const batch = records.slice(i, i + batchSize)
392
+ // await qb.insertInto('table_name').values(batch).execute()
393
+ // // Or: await qb.table('table_name').insert(batch).execute()
394
+ // }
395
+ }
396
+
397
+ /**
398
+ * Specify the order in which this seeder should run.
399
+ * Lower numbers run first. Default is 100.
400
+ */
401
+ get order(): number {
402
+ return 100
403
+ }
404
+ }
405
+ `;MU(U,H),console.log(`-- \u2713 Created seeder: ${U}`)}async function SU(Z={}){let $=X7(u9.cwd()),Y=Z.modelsDir||p8($,"app/Models"),X=Z.seedersDir||p8($,"database/seeders"),J=Z.verbose??!0;try{let{resetDatabase:G,generateMigration:U,executeMigration:H}=await import("./chunk-8jb6b5yg.js");if(J)console.log("-- Refreshing database...");if(await G(Y),J)console.log("-- Running migrations...");if(await U(Y,{full:!0}),await H(),J)console.log("-- Running seeders...");if(await z1({seedersDir:X,verbose:J}),J)console.log("-- \u2713 Database refreshed successfully")}catch(G){throw console.error("-- \u2717 Database refresh failed:",G),G}}qZ();function NU(Z,$,Y={}){let X=W8({modelsDir:Z}),J=$7(X);if(f.debug)f.debug.captureText=!0;let G=XZ({schema:J}),U=G.selectFrom($).limit(Number(Y.limit||10)).toText?.()??"";return console.log(U||"[query]"),{sql:U,qb:G,schema:J}}async function PU(Z,$={}){let Y=XZ(),X=$.params?JSON.parse($.params):void 0,J=await Y.unsafe(Z,X);return console.log(JSON.stringify(J)),J}qZ();import{existsSync as qU}from"fs";import{dirname as H1,join as A1}from"path";import W1 from"process";function TU(Z){let $=Z;while($!==H1($)){if(qU(A1($,"package.json")))return $;$=H1($)}return W1.cwd()}async function j1(Z){if(!Z)Z=A1(TU(W1.cwd()),"app/Models");let $=f.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${Z}`),console.log(`-- Dialect: ${$}`),console.log();let Y=[];try{let X=await W8({modelsDir:Z}),J=n9(X,{dialect:$}),G=XZ(),U=[];if($==="sqlite")U=(await G.unsafe(`
406
+ SELECT name FROM sqlite_master
407
+ WHERE type = 'table'
408
+ AND name NOT LIKE 'sqlite_%'
409
+ AND name != 'migrations'
410
+ `)).map((W)=>W.name);else if($==="postgres")U=(await G.unsafe(`
411
+ SELECT table_name
412
+ FROM information_schema.tables
413
+ WHERE table_schema = 'public'
414
+ AND table_type = 'BASE TABLE'
415
+ AND table_name != 'migrations'
416
+ `)).map((W)=>W.table_name);else if(YZ($))U=(await G.unsafe(`
417
+ SELECT table_name
418
+ FROM information_schema.tables
419
+ WHERE table_schema = DATABASE()
420
+ AND table_type = 'BASE TABLE'
421
+ AND table_name != 'migrations'
422
+ `)).map((W)=>W.table_name);let H=J.tables.map((A)=>A.table);for(let A of H)if(!U.includes(A))Y.push({type:"missing_table",severity:"error",table:A,message:`Table '${A}' defined in models but not found in database`});for(let A of U)if(!H.includes(A))Y.push({type:"extra_table",severity:"warning",table:A,message:`Table '${A}' exists in database but not defined in models`});for(let A of J.tables){if(!U.includes(A.table))continue;let W=[];if($==="sqlite")W=(await G.unsafe(`PRAGMA table_info(${A.table})`)).map((N)=>({name:N.name,type:N.type.toLowerCase()}));else if($==="postgres")W=(await G.unsafe(`
423
+ SELECT column_name, data_type
424
+ FROM information_schema.columns
425
+ WHERE table_name = $1
426
+ `,[A.table])).map((N)=>({name:N.column_name,type:N.data_type.toLowerCase()}));else if(YZ($))W=(await G.unsafe(`
427
+ SELECT column_name, data_type
428
+ FROM information_schema.columns
429
+ WHERE table_name = ?
430
+ AND table_schema = DATABASE()
431
+ `,[A.table])).map((N)=>({name:N.column_name,type:N.data_type.toLowerCase()}));let Q=W.map((O)=>O.name),R=A.columns.map((O)=>O.name);for(let O of A.columns)if(!Q.includes(O.name))Y.push({type:"missing_column",severity:"error",table:A.table,column:O.name,expected:O.type,message:`Column '${A.table}.${O.name}' defined in model but not found in database`});for(let O of W)if(!R.includes(O.name))Y.push({type:"extra_column",severity:"warning",table:A.table,column:O.name,actual:O.type,message:`Column '${A.table}.${O.name}' exists in database but not defined in model`});for(let O of A.columns){let N=W.find((_)=>_.name===O.name);if(N){let _=(K)=>{return K.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},F=_(O.type),L=_(N.type);if(F!==L)Y.push({type:"type_mismatch",severity:"warning",table:A.table,column:O.name,expected:O.type,actual:N.type,message:`Column '${A.table}.${O.name}' type mismatch: expected '${O.type}', found '${N.type}'`})}}}let z=Y.filter((A)=>A.severity==="error").length===0;if(z&&Y.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${Y.length} issue(s)`),console.log();let A=Y.filter((Q)=>Q.severity==="error"),W=Y.filter((Q)=>Q.severity==="warning");if(A.length>0){console.log(`\u2717 Errors (${A.length}):`);for(let Q of A)console.log(` - ${Q.message}`);console.log()}if(W.length>0){console.log(`\u26A0 Warnings (${W.length}):`);for(let Q of W)console.log(` - ${Q.message}`);console.log()}if(!z)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:z,issues:Y}}catch(X){throw console.error("-- Schema validation failed:",X),X}}async function kU(Z){return j1(Z)}async function xU(Z={}){let $=Number(Z.attempts||10),Y=Number(Z.delay||100),X=XZ();try{return await X.waitForReady({attempts:$,delayMs:Y}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}T1();s9();qZ();class c8{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(Z){this.driver=a8(Z.config),this.client=Z.client,this.tableName=Z.config.tableName??""}table(Z){return this.tableName=Z,this}index(Z){return this.indexName=Z,this}entity(Z){return this.entityType=Z,this}whereKey(Z,$,Y){return this.keyConditions.push({attribute:Z,operator:$,value:Y}),this}wherePartitionKey(Z,$){return this.whereKey(Z,"=",$)}whereSortKey(Z,$){return this.whereKey(Z,"=",$)}whereSortKeyBeginsWith(Z,$){return this.keyConditions.push({attribute:Z,operator:"begins_with",value:$}),this}whereSortKeyBetween(Z,$,Y){return this.keyConditions.push({attribute:Z,operator:"BETWEEN",values:[$,Y]}),this}where(Z,$,Y){return this.filterConditions.push({attribute:Z,operator:$,value:Y}),this}whereEquals(Z,$){return this.where(Z,"=",$)}whereLessThan(Z,$){return this.where(Z,"<",$)}whereLessThanOrEqual(Z,$){return this.where(Z,"<=",$)}whereGreaterThan(Z,$){return this.where(Z,">",$)}whereGreaterThanOrEqual(Z,$){return this.where(Z,">=",$)}whereBetween(Z,$,Y){return this.filterConditions.push({attribute:Z,operator:"BETWEEN",values:[$,Y]}),this}whereBeginsWith(Z,$){return this.filterConditions.push({attribute:Z,operator:"begins_with",value:$}),this}whereContains(Z,$){return this.where(Z,"contains",$)}whereExists(Z){return this.where(Z,"attribute_exists")}whereNotExists(Z){return this.where(Z,"attribute_not_exists")}whereIn(Z,$){return this.filterConditions.push({attribute:Z,operator:"IN",values:$}),this}select(...Z){return this.projectionAttrs.push(...Z),this}limit(Z){return this.limitValue=Z,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(Z=!0){return this.consistentReadValue=Z,this}startFrom(Z){return this.startKey=Z,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 Z=this.buildQueryParams(),$={TableName:Z.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(Z.indexName)$.IndexName=Z.indexName;let Y=0;if(Z.keyConditions.length>0){let X=[];for(let J of Z.keyConditions){let G=`#key${Y}`;if($.ExpressionAttributeNames[G]=J.attribute,J.operator==="begins_with"){let U=`:keyval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`begins_with(${G}, ${U})`)}else if(J.operator==="BETWEEN"){let U=`:keyval${Y}a`,H=`:keyval${Y}b`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.values?.[0]}).v,$.ExpressionAttributeValues[H]=this.driver.marshall({v:J.values?.[1]}).v,X.push(`${G} BETWEEN ${U} AND ${H}`)}else{let U=`:keyval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`${G} ${J.operator} ${U}`)}Y++}$.KeyConditionExpression=X.join(" AND ")}if(Z.filterConditions&&Z.filterConditions.length>0){let X=[];for(let J of Z.filterConditions){let G=`#flt${Y}`;if($.ExpressionAttributeNames[G]=J.attribute,J.operator==="attribute_exists")X.push(`attribute_exists(${G})`);else if(J.operator==="attribute_not_exists")X.push(`attribute_not_exists(${G})`);else if(J.operator==="begins_with"||J.operator==="contains"){let U=`:fltval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`${J.operator}(${G}, ${U})`)}else if(J.operator==="BETWEEN"){let U=`:fltval${Y}a`,H=`:fltval${Y}b`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.values?.[0]}).v,$.ExpressionAttributeValues[H]=this.driver.marshall({v:J.values?.[1]}).v,X.push(`${G} BETWEEN ${U} AND ${H}`)}else if(J.operator==="IN"){let U=(J.values??[]).map((H,z)=>`:fltval${Y}_${z}`);J.values?.forEach((H,z)=>{$.ExpressionAttributeValues[`:fltval${Y}_${z}`]=this.driver.marshall({v:H}).v}),X.push(`${G} IN (${U.join(", ")})`)}else{let U=`:fltval${Y}`;$.ExpressionAttributeValues[U]=this.driver.marshall({v:J.value}).v,X.push(`${G} ${J.operator} ${U}`)}Y++}$.FilterExpression=X.join(" AND ")}if(Z.projectionAttributes&&Z.projectionAttributes.length>0){let X=[];for(let J of Z.projectionAttributes){let G=`#proj${Y}`;$.ExpressionAttributeNames[G]=J,X.push(G),Y++}$.ProjectionExpression=X.join(", ")}if(Z.limit!==void 0)$.Limit=Z.limit;if(Z.scanIndexForward!==void 0)$.ScanIndexForward=Z.scanIndexForward;if(Z.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(Z.exclusiveStartKey);if(Z.consistentRead)$.ConsistentRead=Z.consistentRead;if(Object.keys($.ExpressionAttributeNames).length===0)delete $.ExpressionAttributeNames;if(Object.keys($.ExpressionAttributeValues).length===0)delete $.ExpressionAttributeValues;return $}toScanRequest(){let Z=this.buildScanParams(),$={TableName:Z.tableName};if(Z.indexName)$.IndexName=Z.indexName;if(Z.filterConditions&&Z.filterConditions.length>0){let{expression:Y,expressionAttributeNames:X,expressionAttributeValues:J}=this.driver.buildFilterExpression(Z.filterConditions);$.FilterExpression=Y,$.ExpressionAttributeNames=X,$.ExpressionAttributeValues=J}if(Z.projectionAttributes&&Z.projectionAttributes.length>0){let{expression:Y,expressionAttributeNames:X}=this.driver.buildProjectionExpression(Z.projectionAttributes);$.ProjectionExpression=Y,$.ExpressionAttributeNames={...$.ExpressionAttributeNames,...X}}if(Z.limit!==void 0)$.Limit=Z.limit;if(Z.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(Z.exclusiveStartKey);if(Z.consistentRead)$.ConsistentRead=Z.consistentRead;return $}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 Z=this.toQueryRequest(),$=await this.client.query(Z);return{items:$.Items?.map((Y)=>this.driver.unmarshall(Y)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.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 Z=this.toScanRequest(),$=await this.client.scan(Z);return{items:$.Items?.map((Y)=>this.driver.unmarshall(Y)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async getAll(){let Z=[],$;do{if($)this.startFrom($);let Y=this.keyConditions.length>0?await this.query():await this.scan();if(Y.items)Z.push(...Y.items);$=Y.lastEvaluatedKey}while($);return Z}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 Z=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return Z.Select="COUNT",(this.keyConditions.length>0?await this.client.query(Z):await this.client.scan(Z)).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 L8{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(Z){this.driver=a8(Z.config),this.client=Z.client,this.tableName=Z.config.tableName??""}table(Z){return this.tableName=Z,this}key(Z){return this.keyData=Z,this}item(Z){return this.itemData=Z,this}set(Z,$){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[Z]=$,this}setMany(Z){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,Z),this}remove(Z){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(Z),this}add(Z,$){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[Z]=$,this}deleteFromSet(Z,$){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[Z]=$,this}condition(Z){return this.conditionExpr=Z,this}ifNotExists(Z="pk"){return this.conditionExpr=`attribute_not_exists(${Z})`,this}ifExists(Z="pk"){return this.conditionExpr=`attribute_exists(${Z})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let Z={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)Z.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")Z.ReturnValues=this.returnValuesOption;return Z}toUpdateRequest(){let Z={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:$,expressionAttributeNames:Y,expressionAttributeValues:X}=this.driver.buildUpdateExpression(this.updateExpressions);if($)Z.UpdateExpression=$,Z.ExpressionAttributeNames=Y,Z.ExpressionAttributeValues=X;if(this.conditionExpr)Z.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")Z.ReturnValues=this.returnValuesOption;return Z}toDeleteRequest(){let Z={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)Z.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")Z.ReturnValues=this.returnValuesOption;return Z}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toPutRequest(),$=await this.client.putItem(Z);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toUpdateRequest(),$=await this.client.updateItem(Z);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toDeleteRequest(),$=await this.client.deleteItem(Z);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let Z=this.toGetRequest(),$=await this.client.getItem(Z);if($.Item)return this.driver.unmarshall($.Item);return}}function X3(Z){return new c8(Z)}function J3(Z){return new L8(Z)}function G3(Z){let $=a8(Z.config);return{query:()=>new c8(Z),item:()=>new L8(Z),driver:$,registerEntity:(Y)=>$.registerEntity(Y),buildKey:(Y,X)=>$.buildPrimaryKey(Y,X)}}class f1{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(Z){this.config=Z,this.pkAttribute=Z.pkAttribute??"pk",this.skAttribute=Z.skAttribute??"sk",this.typeAttribute=Z.typeAttribute??"_type";for(let $ of Z.entities)this.entities.set($.name,$)}getEntity(Z){return this.entities.get(Z)}registerEntity(Z){this.entities.set(Z.name,Z)}buildKey(Z,$){let Y=this.entities.get(Z);if(!Y)throw Error(`Entity not found: ${Z}`);let X=this.interpolatePattern(Y.pkPattern,$),J=this.interpolatePattern(Y.skPattern,$);return{pk:X,sk:J}}buildGSIKey(Z,$,Y){let X=this.entities.get(Z);if(!X)throw Error(`Entity not found: ${Z}`);let J=X.indexes?.find((H)=>H.name===$);if(!J)throw Error(`GSI not found: ${$} for entity ${Z}`);let G=this.interpolatePattern(J.pkPattern,Y),U=J.skPattern?this.interpolatePattern(J.skPattern,Y):void 0;return{pk:G,sk:U}}createItem(Z,$){let{pk:Y,sk:X}=this.buildKey(Z,$),J=this.entities.get(Z),G={[this.pkAttribute]:Y,[this.skAttribute]:X,[this.typeAttribute]:Z,...$};if(J.indexes)for(let U of J.indexes){let H=this.buildGSIKey(Z,U.name,$),z=this.config.indexes?.find((A)=>A.name===U.name);if(z){if(G[z.pkAttribute]=H.pk,z.skAttribute&&H.sk)G[z.skAttribute]=H.sk}}return G}parseEntityType(Z){if(Z[this.typeAttribute])return Z[this.typeAttribute];let $=Z[this.pkAttribute];if(!$)return;for(let[Y,X]of this.entities){let J=X.pkPattern.split("${")[0];if($.startsWith(J))return Y}return}parseItem(Z){let $=this.parseEntityType(Z);if(!$)return;let{[this.pkAttribute]:Y,[this.skAttribute]:X,[this.typeAttribute]:J,...G}=Z;return{type:$,data:G}}getEntityPrefix(Z){let $=this.entities.get(Z);if(!$)throw Error(`Entity not found: ${Z}`);return $.pkPattern.split("${")[0]}generateTableDefinition(){let Z=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],$=[];if(this.config.indexes)for(let Y of this.config.indexes){if(!Z.find((X)=>X.name===Y.pkAttribute))Z.push({name:Y.pkAttribute,type:"S"});if(Y.skAttribute&&!Z.find((X)=>X.name===Y.skAttribute))Z.push({name:Y.skAttribute,type:"S"});$.push({indexName:Y.name,keySchema:{partitionKey:Y.pkAttribute,sortKey:Y.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:Z,globalSecondaryIndexes:$.length>0?$:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(Z,$){return Z.replace(/\$\{(\w+)\}/g,(Y,X)=>{if(!(X in $))throw Error(`Missing value for pattern key: ${X}`);return String($[X])})}}class g1{manager;entityName;options;constructor(Z,$,Y){this.manager=Z,this.entityName=$,this.options=Y}async create(Z){let $=this.manager.createItem(this.entityName,Z),Y=new L8(this.options).table(this.options.config.tableName).item($).ifNotExists("pk");if(this.options.client)await Y.put();return Z}async get(Z){let{pk:$,sk:Y}=this.manager.buildKey(this.entityName,Z),X=new L8(this.options).table(this.options.config.tableName).key({pk:$,sk:Y});if(!this.options.client)throw Error("DynamoDB client not provided");let J=await X.get();if(!J)return;return this.manager.parseItem(J)?.data}async update(Z,$){let{pk:Y,sk:X}=this.manager.buildKey(this.entityName,Z),J=new L8(this.options).table(this.options.config.tableName).key({pk:Y,sk:X}).setMany($).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let G=await J.update();if(!G)return;return this.manager.parseItem(G)?.data}async delete(Z){let{pk:$,sk:Y}=this.manager.buildKey(this.entityName,Z),X=new L8(this.options).table(this.options.config.tableName).key({pk:$,sk:Y});if(!this.options.client)throw Error("DynamoDB client not provided");return await X.delete(),!0}query(){return new p1(this.manager,this.entityName,this.options)}async findAll(){let Z=this.manager.typeAttribute??"_type",$=new c8(this.options).table(this.options.config.tableName).whereEquals(Z,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await $.getAll()).map((X)=>this.manager.parseItem(X)).filter((X)=>X!==void 0).map((X)=>X.data)}}class p1{manager;entityName;options;builder;pkValue;skConditions=[];constructor(Z,$,Y){this.manager=Z,this.entityName=$,this.options=Y,this.builder=new c8(Y).table(Y.config.tableName)}wherePartitionKey(Z){let{pk:$}=this.manager.buildKey(this.entityName,Z);this.pkValue=$;let Y=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(Y,$),this}whereSortKey(Z){let{sk:$}=this.manager.buildKey(this.entityName,Z),Y=this.manager.skAttribute??"sk";return this.builder.whereSortKey(Y,$),this}whereSortKeyBeginsWith(Z){let $=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith($,Z),this}useIndex(Z,$){let Y=this.manager.buildGSIKey(this.entityName,Z,$),X=this.manager.config.indexes?.find((J)=>J.name===Z);if(!X)throw Error(`GSI configuration not found: ${Z}`);return this.builder.index(Z),this.builder.wherePartitionKey(X.pkAttribute,Y.pk),this}where(Z,$,Y){return this.builder.where(Z,$,Y),this}select(...Z){return this.builder.select(...Z),this}limit(Z){return this.builder.limit(Z),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(($)=>this.manager.parseItem($)).filter(($)=>$!==void 0).map(($)=>$.data)}async first(){return this.limit(1),(await this.execute())[0]}}function d1(Z){return new f1(Z)}function m1(Z,$,Y){return new g1(Z,$,Y)}var H3={simpleEntity:(Z,$="id")=>({name:Z,pkPattern:`${Z.toUpperCase()}#\${${$}}`,skPattern:"METADATA",keyFields:[$]}),oneToMany:(Z,$,Y="id",X="id")=>({parent:{name:Z,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:"METADATA",keyFields:[Y]},child:{name:$,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${X}}`,keyFields:[Y,X]}}),manyToMany:(Z,$,Y="id",X="relatedId")=>({entity:{name:Z,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:"METADATA",keyFields:[Y]},relation:{name:$,pkPattern:`${Z.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${X}}`,keyFields:[Y,X],indexes:[{name:"GSI1",pkPattern:`${Z.toUpperCase()}#\${${X}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`}]}}),hierarchical:(Z,$="rootId",Y="path")=>({name:Z,pkPattern:`ROOT#\${${$}}`,skPattern:`PATH#\${${Y}}`,keyFields:[$,Y]})};function c1(Z,$){let Y={};for(let[X,J]of Object.entries(Z))if(J)Y[X]=J.replace(/\{([^}]+)\}/g,(G,U)=>{return $[U]!==void 0?String($[U]):`{${U}}`});return Y}async function tU(Z){return{models:new Map}}function W3(Z){return Z}function j3(Z){return Z}function Q3(Z){return Z}function _3(Z){return Z}class u1{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(Z){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...Z};let $={region:Z.region,endpoint:Z.endpoint,credentials:Z.credentials,tableName:Z.tableName};this.driver=a8($);let Y={tableName:Z.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=d1(Y),this.queryBuilderOptions={config:$}}setClient(Z){return this.queryBuilderOptions.client=Z,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let Z=await tU({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),$=[];for(let[,Y]of Z.models)this.registerParsedModel(Y),$.push(Y);return $}registerModel(Z){let $=this.parseWithTooling(Z);return this.registerParsedModel($)}registerParsedModel(Z){this.models.set(Z.name,Z);let $=this.toSingleTableEntity(Z);this.singleTableManager.registerEntity($);let Y=this.toEntityMapping(Z);return this.driver.registerEntity(Y),Z}registerModels(Z){return Z.map(($)=>this.registerModel($))}getModel(Z){return this.models.get(Z)}getAllModels(){return Array.from(this.models.values())}repository(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return m1(this.singleTableManager,Z,this.queryBuilderOptions)}query(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return new c8(this.queryBuilderOptions).table(this.config.tableName).entity(Z)}item(Z){if(!this.models.get(Z))throw Error(`Model not found: ${Z}`);return new L8(this.queryBuilderOptions).table(this.config.tableName)}buildKey(Z,$){let Y=this.models.get(Z);if(!Y)throw Error(`Model not found: ${Z}`);let X=c1(Y.keyPatterns,$);return{pk:X.pk,sk:X.sk}}createItem(Z,$){let Y=this.models.get(Z);if(!Y)throw Error(`Model not found: ${Z}`);let X=c1(Y.keyPatterns,$),J=X.pk,G=X.sk,U={[this.config.pkAttribute]:J,[this.config.skAttribute]:G,[this.config.entityTypeAttribute]:Y.name,...$};if(Y.hasTimestamps){let H=new Date().toISOString();if(!U.createdAt)U.createdAt=H;U.updatedAt=H}if(Y.hasVersioning){if(!U._v)U._v=1}return U}parseItem(Z){let $=Z[this.config.entityTypeAttribute];if(!$)return;let{[this.config.pkAttribute]:Y,[this.config.skAttribute]:X,[this.config.entityTypeAttribute]:J,...G}=Z;return{type:$,data:G}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(Z){let $=this.models.get(Z);if(!$)throw Error(`Model not found: ${Z}`);return $.accessPatterns}parseWithTooling(Z){let $=Z.name.toUpperCase(),Y=Z.primaryKey??"id",X=this.config.keyDelimiter,J=this.parseAttributes(Z),G=this.parseRelationships(Z,Y),U={pk:`${$}${X}{${Y}}`,sk:`${$}${X}{${Y}}`,...this.deriveGSIKeyPatterns($,Y,X,G)},H=this.deriveAccessPatterns(Z.name,$,Y,G);return{name:Z.name,entityType:$,primaryKey:Y,attributes:J,relationships:G,keyPatterns:U,accessPatterns:H,traits:Z.traits??{},hasTimestamps:Z.traits?.useTimestamps??!1,hasSoftDeletes:Z.traits?.useSoftDeletes??!1,hasUuid:Z.traits?.useUuid??!1,hasTtl:Z.traits?.useTtl??!1,hasVersioning:Z.traits?.useVersioning??!1,original:Z}}parseAttributes(Z){let $=[];if($.push({name:Z.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),Z.attributes)for(let[Y,X]of Object.entries(Z.attributes))$.push({name:Y,fillable:X.fillable??!0,required:X.required??!1,nullable:X.nullable??!0,unique:X.unique??!1,hidden:X.hidden??!1,defaultValue:X.default,cast:X.cast,dynamoDbType:this.inferDynamoDBType(X)});if(Z.traits?.useTimestamps)$.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(Z.traits?.useSoftDeletes)$.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return $}inferDynamoDBType(Z){if(Z.cast){let $=Z.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes($))return"N";if(["boolean","bool"].includes($))return"BOOL";if(["array","list"].includes($))return"L";if(["object","json","map"].includes($))return"M"}if(Z.validation?.rule){let $=String(Z.validation.rule);if($.includes("integer")||$.includes("numeric")||$.includes("number"))return"N";if($.includes("boolean"))return"BOOL";if($.includes("array"))return"L";if($.includes("object"))return"M"}return"S"}parseRelationships(Z,$){let Y=[];if(Z.hasOne)for(let X of Z.hasOne)Y.push({type:"hasOne",relatedModel:X,foreignKey:`${Z.name.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(Z.hasMany)for(let X of Z.hasMany)Y.push({type:"hasMany",relatedModel:X,foreignKey:`${Z.name.toLowerCase()}Id`,localKey:$,requiresGsi:!1});if(Z.belongsTo)for(let X of Z.belongsTo)Y.push({type:"belongsTo",relatedModel:X,foreignKey:`${X.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(Z.belongsToMany){let X=Array.isArray(Z.belongsToMany)?Z.belongsToMany:Object.values(Z.belongsToMany);for(let J of X){let G=typeof J==="string"?J:J?.model;if(!G)continue;let U=[Z.name,G].sort();Y.push({type:"belongsToMany",relatedModel:G,foreignKey:`${Z.name.toLowerCase()}Id`,localKey:$,pivotEntity:U.join(""),requiresGsi:!0})}}return Y}deriveGSIKeyPatterns(Z,$,Y,X){let J={},G=1;for(let U of X)if(U.requiresGsi&&G<=5)J[`gsi${G}pk`]=`${U.relatedModel.toUpperCase()}${Y}{${U.foreignKey}}`,J[`gsi${G}sk`]=`${Z}${Y}{${$}}`,U.gsiIndex=G,G++;return J}deriveAccessPatterns(Z,$,Y,X){let J=[];J.push({name:`Get ${Z} by ID`,description:`Retrieve a single ${Z} by its primary key`,entityType:$,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${$}#123`,exampleSk:`${$}#123`,efficient:!0}),J.push({name:`List all ${Z}s`,description:`Scan all ${Z} entities`,entityType:$,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:$,efficient:!1});for(let G of X){if(G.type==="hasMany")J.push({name:`Get ${G.relatedModel}s for ${Z}`,description:`Query ${G.relatedModel}s related to a ${Z}`,entityType:$,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${$}#123`,exampleSk:`${G.relatedModel.toUpperCase()}#`,efficient:!0});if(G.gsiIndex){let U=`GSI${G.gsiIndex}`;J.push({name:`Get ${Z}s by ${G.relatedModel}`,description:`Query ${Z}s by their related ${G.relatedModel}`,entityType:$,operation:"query",index:U,keyCondition:`gsi${G.gsiIndex}pk = :pk`,examplePk:`${G.relatedModel.toUpperCase()}#123`,efficient:!0})}}return J}toSingleTableEntity(Z){let $=this.extractKeyFields(Z.keyPatterns.pk);return{name:Z.name,pkPattern:Z.keyPatterns.pk,skPattern:Z.keyPatterns.sk,keyFields:$,indexes:this.extractGSIPatterns(Z.keyPatterns)}}extractKeyFields(Z){let $=Z.match(/\{([^}]+)\}/g);if(!$)return[];return $.map((Y)=>Y.slice(1,-1))}extractGSIPatterns(Z){let $=[];for(let Y=1;Y<=5;Y++){let X=`gsi${Y}pk`,J=`gsi${Y}sk`;if(Z[X])$.push({name:`GSI${Y}`,pkPattern:Z[X],skPattern:Z[J]})}return $.length>0?$:void 0}toEntityMapping(Z){return{entityType:Z.name,pkPattern:Z.keyPatterns.pk,skPattern:Z.keyPatterns.sk}}buildGSIConfig(){let Z=this.config.gsiConfig??{},$=[];if(Z.gsi1pk)$.push({name:"GSI1",pkAttribute:Z.gsi1pk,skAttribute:Z.gsi1sk});if(Z.gsi2pk)$.push({name:"GSI2",pkAttribute:Z.gsi2pk,skAttribute:Z.gsi2sk});if(Z.gsi3pk)$.push({name:"GSI3",pkAttribute:Z.gsi3pk,skAttribute:Z.gsi3sk});return $}}function R3(Z){return new u1(Z)}function O3(Z){return Z.accessPatterns}function D3(Z,$="#"){let Y=Z.name.toUpperCase(),X=Z.primaryKey??"id";return{name:Z.name,pkPattern:`${Y}${$}\${${X}}`,skPattern:`${Y}${$}\${${X}}`}}g8();function $7(Z){let $={};for(let Y of Object.keys(Z)){let X=Z[Y],J=X.definition??X.getDefinition?.()??X,G=b8(J),U=J.attributes??{},H={};for(let z of Object.keys(U))H[z]=void 0;$[G]={columns:H,primaryKey:J.primaryKey??"id"}}return $}L0();g8();import{readdirSync as eU}from"fs";import{basename as n1,extname as i1,isAbsolute as Z2,join as l1}from"path";import $2 from"process";var Y2=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"]);function X2(Z){let $=i1(Z);if(!Y2.has($))return!1;let Y=n1(Z,$);if(Y.startsWith("_")||Y==="index")return!1;return!Y.endsWith(".d")}function J2(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;return typeof $.name==="string"||typeof $.table==="string"}function s1(Z){let $=[],Y=eU(Z,{withFileTypes:!0}).sort((X,J)=>X.name.localeCompare(J.name));for(let X of Y){let J=l1(Z,X.name);if(X.isDirectory()){$.push(...s1(J));continue}if(X2(X.name))$.push(J)}return $}async function W8(Z){let $=Z.cwd??$2.cwd(),Y=Z2(Z.modelsDir)?Z.modelsDir:l1($,Z.modelsDir),X={};for(let J of s1(Y)){let G=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,U=await import(`${J}${G}`),H=U.default??U,z=H.definition??H.getDefinition?.()??H;if(!J2(z))continue;let A=z.name??n1(J,i1(J));X[A]={...z,name:A}}return X}g8();G7();function o1(Z){let $={},Y={},X={},J={},G={};for(let U of Object.keys(Z)){let H=Z[U],z=H.definition??H.getDefinition?.()??H,A=b8(z);$[U]=A,Y[A]=U,X[A]=z.primaryKey??"id";let W=(O)=>{if(!O)return{};let N={};if(Array.isArray(O)){for(let _ of O){let F=J7(_);if(F)N[F.model]=F.model}return N}if(typeof O==="object"){for(let[_,F]of Object.entries(O)){let L=J7(F);if(L)N[_]=L.model}return N}return{}},Q=(O)=>{if(!O)return{};if(Array.isArray(O)){let N={};for(let _ of O)if(typeof _==="string")N[_]=_;else if(_&&typeof _==="object"&&typeof _.model==="string")N[_.model]=_;return N}return O},R=(O)=>{if(!O)return{};return O};if(J[A]={hasOne:W(z.hasOne),hasMany:W(z.hasMany),belongsTo:W(z.belongsTo),belongsToMany:Q(z.belongsToMany),hasOneThrough:R(z.hasOneThrough),hasManyThrough:R(z.hasManyThrough),morphOne:W(z.morphOne),morphMany:W(z.morphMany),morphTo:z.morphTo,morphToMany:W(z.morphToMany),morphedByMany:W(z.morphedByMany)},z.scopes&&typeof z.scopes==="object"){G[A]={};for(let O of Object.keys(z.scopes)){let N=z.scopes[O];if(typeof N==="function")G[A][O]=N}}}return{modelToTable:$,tableToModel:Y,primaryKeys:X,relations:J,scopes:G,models:Z}}G7();g8();qZ();import{existsSync as k0,mkdirSync as G2,readdirSync as U2,readFileSync as z2,writeFileSync as H2}from"fs";import{dirname as r1,join as A7}from"path";import $J from"process";function bZ(Z){if(f.verbose)console.log(Z)}function u8(Z){return Z.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function C0(Z){return f8(f.relations?.singularizeStrategy)(Z)}var r9=0,q8=0,n8=0,W7=!0,j7=[],C9=null;function YJ(){return[...j7]}function A2(Z){let $=Z;while($!==r1($)){if(k0(A7($,"package.json")))return $;$=r1($)}return $J.cwd()}function W2(){let Z=A2($J.cwd()),$=C8(Z,f.migrationDir);if(!k0($))G2($,{recursive:!0}),bZ(`-- Created SQL directory: ${$}`);return $}var XJ="-- qb:generated";function JJ(Z){return Z.trimStart().startsWith(XJ)}function GJ(Z){return Z.split(`
432
+ `).filter(($)=>!$.trimStart().startsWith("--")).join(`
433
+ `).replace(/\s+/g," ").trim().replace(/;+$/,"")}function j2(Z){let $=new Set,Y;try{Y=U2(Z).filter((X)=>X.endsWith(".sql"))}catch{return $}for(let X of Y)try{$.add(GJ(z2(A7(Z,X),"utf8")))}catch{}return $}function UJ(Z,$){if(!Z)return!1;let Y=W2();if(C9===null)C9=j2(Y);let X=GJ(Z);if(X.length>0&&C9.has(X))return bZ(`-- Migration already in the corpus, not writing it again: ${$}`),!1;r9++;let J=W7?String(r9).padStart(10,"0"):String(Math.floor(Date.now()/1000)+r9),G=`${J}-${$}.sql`;if(!W7){let H=Number(J);while(k0(A7(Y,G)))H+=1,J=String(H),G=`${J}-${$}.sql`}let U=A7(Y,G);return H2(U,`${XJ}
434
+ ${Z}`),bZ(`-- Migration file created: ${G}`),q8++,j7.push(G),C9?.add(X),!0}function Q2(Z,$){return Z==="integer"&&$==="bigint"||Z==="string"&&$==="text"}function a1(Z){if(Z.endsWith("_id"))return"bigint";if(Z.endsWith("_at"))return"datetime";if(Z.startsWith("is_")||Z.startsWith("has_"))return"boolean";return}function t1(Z){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint"||Z instanceof Date)return Z;return}function _2(Z){if(Z&&typeof Z==="object"&&"name"in Z){let $=Z;if($.name==="enum"||$.getRules&&Array.isArray($.getRules())){if($.enumValues&&Array.isArray($.enumValues))return $.enumValues.map((Y)=>String(Y));if($._values&&Array.isArray($._values))return $._values.map((Y)=>String(Y));if($.values&&Array.isArray($.values))return $.values.map((Y)=>String(Y))}}if(Z&&typeof Z==="object"){let $=Z,Y=$.allowedValues||$.enumValues||$._values||$.values;if(Array.isArray(Y)&&Y.length>0)return Y.map((X)=>String(X))}return}function N0(Z){if(!Z?.rules||!Array.isArray(Z.rules))return;for(let $ of Z.rules)if($?.name==="max"||$?.name==="maxLength"){if($.params&&typeof $.params.max==="number")return $.params.max;if(Array.isArray($.args)&&typeof $.args[0]==="number")return $.args[0];if(typeof $.value==="number")return $.value;if(typeof $.expectedValue==="number")return $.expectedValue}return}var P0=767;function V2(Z){if(!Z||typeof Z!=="object")return;let $=Z;if($.name)switch(String($.name).toLowerCase()){case"string":{let X=N0($);return X&&X>P0?"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($.type){let Y=String($.type).toLowerCase();if(Y==="string"||Y==="text")return"string";if(Y==="integer"||Y==="int")return"integer";if(Y==="bigint")return"bigint";if(Y==="float")return"float";if(Y==="number")return"integer";if(Y==="boolean")return"boolean";if(Y==="date")return"date";if(Y==="datetime")return"datetime";if(Y==="timestamptz"||Y==="timestamp_tz")return"timestamptz";if(Y==="json")return"json"}return}function K2(Z){if(typeof Z!=="string")return;switch(Z.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 n9(Z,$){let Y=o1(Z),X=[];for(let H of Object.keys(Z)){let z=Z[H],A=b8(z),W=z.primaryKey??"id",Q=z.autoIncrement!==!1,R=z.attributes??{},O=[],N=[];if(!R[W])O.push({name:u8(W),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let _=new Map,F=E9(z.belongsTo).length>0,L=new Set(Object.keys(R).map((C)=>u8(C))),K=new Set;for(let C of L){if(!C.endsWith("_type"))continue;let y=`${C.slice(0,-5)}_id`;if(L.has(y))K.add(y)}for(let C of E9(z.belongsTo)){let y=C.foreignKey??`${u8(C.model)}_id`,c=Y.modelToTable[C.model];if(c)_.set(y,{table:c,onDelete:C.onDelete})}for(let C of Object.keys(R)){let y=R[C],c=u8(C),l=Boolean(y.validation?.rule?.isRequired),r=C===W?!1:y.nullable??!(y.required??l),x,m,n=C===W;if(x=K2(y.type)??V2(y.validation?.rule),x==="string"){let a=N0(y.validation?.rule);if(a&&a>P0)x="text"}if(!x||x==="enum"){let a=_2(y.validation?.rule);if(a&&a.length>0)x="enum",m=a}if(!x)x=a1(c);if(!x){let a=t1(y.default);if(typeof a==="string")x=a.length>255?"text":"string";else if(typeof a==="number")x=Number.isInteger(a)?"integer":"float";else if(typeof a==="boolean")x="boolean";else if(typeof a==="bigint")x="bigint";else if(a instanceof Date)x="datetime"}if(!x)x=n?"bigint":"string";let h=x==="string"?N0(y.validation?.rule):void 0,ZZ={name:c,type:x,isPrimaryKey:n,isUnique:Boolean(y.unique),isNullable:r,hasDefault:typeof y.default<"u",defaultValue:t1(y.default),enumValues:m,maxLength:typeof h==="number"&&h>0&&h<=P0?h:void 0};if(c.endsWith("_id")&&y.foreignKey!==!1&&!K.has(c))if(typeof y.foreignKey==="object"&&y.foreignKey!==null){let a=y.foreignKey;if(ZZ.references={table:a.table,column:a.column??"id",onDelete:a.onDelete,onUpdate:a.onUpdate},a.nullable!==void 0)ZZ.isNullable=a.nullable}else{let a=_.get(c),jZ=c.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(k8,FZ,$8)=>$8.toUpperCase()),mZ=a?.table??(F?void 0:Y.modelToTable[jZ]);if(mZ){let k8=Y.primaryKeys[mZ]??"id";ZZ.references={table:mZ,column:k8,onDelete:a?.onDelete}}}O.push(ZZ)}let I=E9(z.belongsTo);for(let C of I){let y=C.foreignKey??`${u8(C.model)}_id`;if(O.some((r)=>r.name===y))continue;let c=Y.modelToTable[C.model],l=c?Y.primaryKeys[c]??"id":void 0;O.push({name:y,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:c&&l&&!K.has(y)?{table:c,column:l,onDelete:C.onDelete}:void 0})}let B=z.traits;if(B?.useTimestamps??B?.timestampable??!1){if(!O.some((C)=>C.name==="created_at"))O.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:P8});if(!O.some((C)=>C.name==="updated_at"))O.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(B?.useSoftDeletes??B?.softDeletable??!1){if(!O.some((C)=>C.name==="deleted_at"))O.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(B?.useUuid??!1){if(!O.some((C)=>C.name==="uuid"))O.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let C of z.indexes??[])N.push({name:C.name,columns:C.columns.map((y)=>u8(y)),type:C.unique?"unique":"index",where:C.where});for(let C of O)if(C.isUnique&&!C.isPrimaryKey)N.push({name:`${A}_${C.name}_unique`,columns:[C.name],type:"unique"});let w=Array.isArray(z.shardKey)?z.shardKey.map(u8):void 0,M=Array.isArray(z.sortKey)?z.sortKey.map(u8):void 0,q=z.tableKind;X.push({table:A,columns:O,indexes:N,shardKey:w,sortKey:M,tableKind:q})}let J=new Set(X.map((H)=>H.table));function G(H){if(!J.has(H.table))J.add(H.table),X.push(H)}for(let H of Object.keys(Z)){let z=Z[H],A=z?.traits??{},W=b8(z),Q=C0(W);if(A.likeable){let R=typeof A.likeable==="object"?A.likeable:{},O=R.table||`${W}_likes`,N=R.foreignKey||`${Q}_id`;G({table:O,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:W,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:P8},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${O}_user_target_unique`,columns:["user_id",N],type:"unique"}]})}if(A.taggable)G({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:P8},{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"}]}),G({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:P8},{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(A.categorizable)G({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:P8},{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"}]}),G({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:P8},{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 H of Object.keys(Z)){let z=Z[H],A=z?.belongsToMany;if(!A||typeof A!=="object"||Array.isArray(A))continue;let W=b8(z),Q=C0(W);for(let[R,O]of Object.entries(A)){let N=O;if(!N||typeof N!=="object")continue;if(N.through)continue;let _=N.pivot;if(!_||!_.columns&&!_.timestamps&&!_.uniques)continue;let F=N.model,K=Z[F]?.table||`${String(F).toLowerCase()}s`,I=C0(K),B=N.table||[Q,I].sort().join("_"),v=N.foreignKey||`${Q}_id`,P=N.relatedKey||`${I}_id`,T=new Set([v,P,...Object.keys(_.columns??{})]),w=new Set;for(let c of T){if(!c.endsWith("_type"))continue;let l=`${c.slice(0,-5)}_id`;if(T.has(l))w.add(l)}let M=(c,l)=>w.has(c)?void 0:{table:l,column:"id"},q=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:v,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:M(v,W)},{name:P,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:M(P,K)}];if(_.columns)for(let[c,l]of Object.entries(_.columns)){let r=l,x=a1(c)??"string";q.push({name:c,type:x,isPrimaryKey:!1,isUnique:!1,isNullable:r?.nullable??!1,hasDefault:r?.default!==void 0,defaultValue:r?.default})}if(_.timestamps)q.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:P8}),q.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let C=[],y=_.uniques&&_.uniques.length>0?_.uniques:[[v,P]];for(let c=0;c<y.length;c++){let l=y[c];C.push({name:`${B}_${l.join("_")}_unique${c>0?`_${c}`:""}`,columns:[...l],type:"unique"})}G({table:B,columns:q,indexes:C})}}let U=new Map(X.map((H)=>[H.table,H]));for(let H of X)for(let z of H.columns){if(!z.references)continue;let A=U.get(z.references.table)?.columns.find((W)=>W.name===z.references.column);if(!A||z.type===A.type)continue;z.type=A.type,z.maxLength=A.maxLength,z.enumValues=A.enumValues,z.enumTypeName=A.enumTypeName}return{dialect:$.dialect,vitessSharded:$.vitessSharded,tables:X}}function Q7(Z,$={}){r9=0,q8=0,n8=0,j7=[],C9=null,W7=!0;let Y=$.dryRun?()=>!1:UJ,X=[],J=K8(Z.dialect,{vitessSharded:Z.vitessSharded}),{tables:G,deferredForeignKeys:U}=zJ(Z.tables,Z.dialect);for(let[z,A]of G.entries()){let W={...A,columns:A.columns.map((_)=>U.has(S9(A.table,_.name))?{..._,references:void 0}:_)},Q=[],R=new Set;for(let _ of W.columns)if(_.type==="enum"&&_.enumValues&&_.enumValues.length>0){let F=`${W.table}_${_.name}_type`;if(_.enumTypeName=F,!R.has(F)){let L=J.createEnumType(F,_.enumValues);if(L)Q.push(L);R.add(F)}}let O=J.createTable(W);Q.push(O);for(let _ of W.indexes)Q.push(J.createIndex(W.table,_,W.columns));if(z===G.length-1)for(let _ of G)for(let F of _.columns){if(!F.references||!U.has(S9(_.table,F.name)))continue;let L=J.addForeignKey(_.table,F.name,F.references.table,F.references.column,F.references.onDelete,F.references.onUpdate);if(L)Q.push(L)}X.push(...Q);let N=Q.join(`
435
+
436
+ `);Y(N,`create-${W.table}-table`)}if(q8+n8===0)bZ("-- Nothing to migrate");else{let z=[];if(q8>0)z.push(`${q8} created`);if(n8>0)z.push(`${n8} updated`);bZ(`-- Migration files: ${z.join(", ")}`)}return X}function S9(Z,$){return`${Z}\x00${$}`}function zJ(Z,$){if($==="sqlite"||Z.length<2)return{tables:Z,deferredForeignKeys:new Set};let Y=new Map(Z.map((z)=>[z.table,z])),X=new Map;for(let z of Z)X.set(z.table,new Set(z.columns.map((A)=>A.references?.table).filter((A)=>Boolean(A&&A!==z.table&&Y.has(A)))));let J=[],G=new Set;while(J.length<Z.length){let z=Z.find((A)=>!G.has(A.table)&&[...X.get(A.table)??[]].every((W)=>G.has(W)));if(!z)break;J.push(z),G.add(z.table)}let U=new Set(Z.filter((z)=>!G.has(z.table)).map((z)=>z.table)),H=new Set;for(let z of Z){if(!U.has(z.table))continue;for(let A of z.columns)if(A.references&&U.has(A.references.table)&&A.references.table!==z.table)H.add(S9(z.table,A.name))}return J.push(...Z.filter((z)=>U.has(z.table))),{tables:J,deferredForeignKeys:H}}function c3(Z){return Q7(Z).join(`
437
+ `)}function u3(Z,$){return O2(Z,$).join(`
438
+ `)}function HJ(Z){let $=sZ("crypto");function Y(J){if(J==null||typeof J!=="object"||J instanceof Date)return J;if(Array.isArray(J))return J.map((U)=>Y(U));let G={};for(let U of Object.keys(J).sort())G[U]=Y(J[U]);return G}let X=JSON.stringify(Y(Z));return $.createHash("sha256").update(X).digest("hex")}function e1(Z){let $={};for(let Y of Z)$[Y.table]=Y;return $}function o9(Z){let $={};for(let Y of Z)$[Y.name]=Y;return $}function q0(Z,$){if($==="sqlite"){if(Z.name.endsWith("_id")&&R9(Z.type))return"INTEGER";switch(Z.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($==="mysql"||$==="vitess"||$==="singlestore")switch(Z.type){case"string":return`VARCHAR(${Z.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 Z.type}return Z.type}var P8="UTC_TIMESTAMP";function T0(Z,$){if(!Z.hasDefault||Z.defaultValue===void 0)return;let Y=Z.defaultValue;if(Y instanceof Date)return Y.toISOString();if(typeof Y==="boolean")return Y?"1":"0";if(typeof Y==="bigint"||typeof Y==="number")return String(Y);let X=String(Y).trim();if(X=X.replace(/::[\w ]+$/i,"").trim(),X.startsWith("'")&&X.endsWith("'")||X.startsWith('"')&&X.endsWith('"'))X=X.slice(1,-1);let J=X.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(J.replace(/\s+/g," ")))return P8;if($==="sqlite"&&J==="CURRENT_TIMESTAMP")return P8;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(J))return J==="NOW()"?"CURRENT_TIMESTAMP":J;if(Z.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(X))return"1";if(/^(?:0|f|false|no)$/i.test(X))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(X))return String(Number(X));return X}function L2(Z,$,Y){if(q0(Z,Y)!==q0($,Y))return!0;if(Z.isNullable!==$.isNullable)return!0;if(Z.hasDefault!==$.hasDefault)return!0;if(T0(Z,Y)!==T0($,Y))return!0;if(Z.isUnique!==$.isUnique)return!0;if(Z.type==="enum"&&$.type==="enum"){let X=(Z.enumValues||[]).slice().sort().join(","),J=($.enumValues||[]).slice().sort().join(",");if(X!==J)return!0}return!1}function ZJ(Z,$){return JSON.stringify([q0(Z,$),Z.isPrimaryKey,Z.isUnique,Z.isNullable,Z.hasDefault,T0(Z,$)??null,(Z.enumValues??[]).slice().sort(),Z.references?[Z.references.table,Z.references.column,Z.references.onDelete??null,Z.references.onUpdate??null]:null])}function F2(Z,$,Y){let X=Object.keys(Z).filter((W)=>!$[W]),J=Object.keys($).filter((W)=>!Z[W]),G=new Map,U=new Map;for(let W of X){let Q=ZJ(Z[W],Y),R=G.get(Q)??[];R.push(W),G.set(Q,R)}for(let W of J){let Q=ZJ($[W],Y),R=U.get(Q)??[];R.push(W),U.set(Q,R)}let H=[],z=new Set,A=new Set;for(let[W,Q]of G){let R=U.get(W);if(Q.length===1&&R&&R.length===1)H.push({from:Q[0],to:R[0]}),z.add(Q[0]),A.add(R[0])}return{renames:H,removed:X.filter((W)=>!z.has(W)),added:J.filter((W)=>!A.has(W))}}function B2(Z,$){let Y=Z.columns.find((X)=>X.name===$);if(Y&&(Y.isPrimaryKey||Y.isUnique||Y.references))return!0;return Z.indexes.some((X)=>X.columns.includes($))}function R2(Z,$){if(Boolean(Z)!==Boolean($))return!0;if(!Z||!$)return!1;if((Z.constraintNames?.length??0)>1)return!0;let Y=(X)=>(X??"no action").toLowerCase();return Z.table!==$.table||Z.column!==$.column||Y(Z.onDelete)!==Y($.onDelete)||Y(Z.onUpdate)!==Y($.onUpdate)}function AJ(Z,$){return`${Z.type}:${A8($,Z.name)}:${Z.columns.join(",")}`}function S0(Z,$){let Y={};for(let X of Z)Y[AJ(X,$)]=X;return Y}function x0(Z,$,Y={}){if(!Z||Z.dialect!==$.dialect){let K=Q7($,{dryRun:Y.dryRun}),I=$.tables.map((B)=>({kind:"create_table",table:B.table,destructive:!1,sql:""}));return{statements:K,operations:I}}let X=Y.applyRenames!==!1,J=Y.preserveUnknownColumns===!0,G=Y.dryRun?()=>!1:UJ;r9=0,q8=0,n8=0,j7=[],C9=null,W7=!1;let U=[],H=[],z=K8($.dialect,{vitessSharded:$.vitessSharded}),A=$.dialect,W=e1(Z.tables),Q=e1($.tables);for(let K of Object.keys(W))if(!Q[K]){let I=z.dropTable(K);U.push(I),H.push({kind:"drop_table",table:K,destructive:!0,sql:I}),G(I,`drop-${K}-table`),bZ(`-- Detected dropped table: ${K}`)}let R=Object.keys(Q).filter((K)=>!W[K]).map((K)=>Q[K]),{tables:O,deferredForeignKeys:N}=zJ(R,A);for(let[K,I]of O.entries()){let B={...I,columns:I.columns.map((M)=>N.has(S9(I.table,M.name))?{...M,references:void 0}:M)},v=[],P=new Set;for(let M of B.columns)if(M.type==="enum"&&M.enumValues&&M.enumValues.length>0){let q=`${B.table}_${M.name}_type`;if(M.enumTypeName=q,!P.has(q)){let C=z.createEnumType(q,M.enumValues);if(C)v.push(C);P.add(q)}}let T=z.createTable(B);v.push(T);for(let M of B.indexes){let q=z.createIndex(B.table,M,B.columns);v.push(q),H.push({kind:"create_index",table:B.table,column:M.name,destructive:!1,sql:q})}for(let M of I.columns)if(M.references&&!N.has(S9(I.table,M.name)))H.push({kind:"add_foreign_key",table:I.table,column:M.name,destructive:!1,sql:T});if(K===O.length-1)for(let M of O)for(let q of M.columns){if(!q.references||!N.has(S9(M.table,q.name)))continue;let C=z.addForeignKey(M.table,q.name,q.references.table,q.references.column,q.references.onDelete,q.references.onUpdate);if(!C)continue;v.push(C),H.push({kind:"add_foreign_key",table:M.table,column:q.name,destructive:!1,sql:C})}U.push(...v),H.push({kind:"create_table",table:B.table,destructive:!1,sql:T});let w=v.join(`
439
+
440
+ `);G(w,`create-${B.table}-table`)}let _=new Set;for(let K of Object.keys(Q)){let I=W[K],B=Q[K];if(!I)continue;let v=o9(I.columns),P=o9(B.columns);for(let T of Object.keys(P)){let w=P[T];if(w.type!=="enum"||!w.enumValues||w.enumValues.length===0)continue;let M=`${B.table}_${w.name}_type`;if(w.enumTypeName=M,v[T])continue;if(!_.has(M)){let q=z.createEnumType(M,w.enumValues);if(q)U.push(q),H.push({kind:"create_enum",table:B.table,column:w.name,destructive:!1,sql:q}),G(q,`create-${M}-enum`);_.add(M)}}}for(let K of Object.keys(Q)){let I=W[K],B=Q[K];if(!I)continue;let v=o9(I.columns),P=S0(I.indexes,I.table),T=o9(B.columns),w=S0(B.indexes,B.table),M=[],q=Object.keys(v).filter((x)=>!T[x]),C=Object.keys(T).filter((x)=>!v[x]);if(X&&!J){let x=F2(v,T,A);M=x.renames,q=x.removed,C=x.added}if(J){let x=q.map((n)=>v[n]),m=I.indexes.filter((n)=>!w[AJ(n,I.table)]);if(x.length>0||m.length>0){if(x.length>0)bZ(`-- Keeping ${x.length} column(s) on "${B.table}" no model declares: ${q.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(m.length>0)bZ(`-- Keeping ${m.length} index(es) on "${B.table}" no model declares: ${m.map((n)=>n.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);B={...B,columns:[...B.columns,...x],indexes:[...B.indexes,...m]},T=o9(B.columns),w=S0(B.indexes,B.table)}q=[]}let y=Object.keys(T).filter((x)=>v[x]&&L2(v[x],T[x],A)),c=Object.keys(T).filter((x)=>v[x]&&R2(v[x].references,T[x].references));if(A==="sqlite"){if(y.length>0||c.length>0||q.some((m)=>B2(I,m))){let m={},n=new Map(M.map((jZ)=>[jZ.to,jZ.from]));for(let jZ of B.columns)if(v[jZ.name])m[jZ.name]=jZ.name;else if(n.has(jZ.name))m[jZ.name]=n.get(jZ.name);let h=`_qb_tmp_${B.table}`,ZZ=0;while((W[h]||Q[h])&&ZZ<100)ZZ+=1,h=`_qb_tmp_${B.table}_${ZZ}`;let a=z.rebuildTable({target:B,tempName:h,columnSource:m});U.push(a);let DZ=y.some((jZ)=>v[jZ].type!==T[jZ].type);H.push({kind:"rebuild_table",table:B.table,destructive:q.length>0||DZ,sql:a});for(let jZ of M)H.push({kind:"rename_column",table:B.table,from:jZ.from,to:jZ.to,destructive:!1,confidence:"high",sql:a});for(let jZ of q)H.push({kind:"drop_column",table:B.table,column:jZ,destructive:!0,sql:a});bZ(`-- Detected SQLite table rebuild required: ${B.table}`),G(a,`alter-${B.table}-table`);continue}}let l=[],r=!1;for(let x of Object.keys(P))if(!w[x]){let m=P[x],n=z.dropIndex(B.table,m.name);l.push(n),U.push(n),H.push({kind:"drop_index",table:B.table,column:m.name,destructive:!1,sql:n}),bZ(`-- Detected dropped index: ${m.name} from ${B.table}`),r=!0}for(let x of M){let m=z.renameColumn(B.table,x.from,x.to);l.push(m),U.push(m),H.push({kind:"rename_column",table:B.table,from:x.from,to:x.to,destructive:!1,confidence:"high",sql:m}),bZ(`-- Detected renamed column: ${B.table}.${x.from} -> ${x.to}`),r=!0}for(let x of q){let m=z.dropColumn(B.table,x);l.push(m),U.push(m),H.push({kind:"drop_column",table:B.table,column:x,destructive:!0,sql:m}),bZ(`-- Detected dropped column: ${B.table}.${x}`),r=!0}for(let x of y){let m=v[x],n=T[x],h=z.modifyColumn(B.table,n);l.push(h),U.push(h),H.push({kind:"modify_column",table:B.table,column:x,destructive:m.type!==n.type&&!Q2(m.type,n.type),sql:h}),bZ(`-- Detected column change: ${B.table}.${x} (${m.type} -> ${n.type})`),r=!0}for(let x of c){let m=T[x];if(!m.references)continue;let n=z.addForeignKey(B.table,m.name,m.references.table,m.references.column,m.references.onDelete,m.references.onUpdate,v[x].references?.constraintNames);if(!n)continue;l.push(n),U.push(n),H.push({kind:"add_foreign_key",table:B.table,column:x,destructive:!1,sql:n}),bZ(`-- Detected foreign-key change: ${B.table}.${x} -> ${m.references.table}(${m.references.column})`),r=!0}for(let x of C){let m=T[x],n=z.addColumn(B.table,m);if(l.push(n),U.push(n),H.push({kind:"add_column",table:B.table,column:m.name,destructive:!1,sql:n}),bZ(`-- Detected new column: ${B.table}.${m.name}`),r=!0,m.references){let h=z.addForeignKey(B.table,m.name,m.references.table,m.references.column,m.references.onDelete,m.references.onUpdate);if(h)l.push(h),U.push(h),H.push({kind:"add_foreign_key",table:B.table,column:m.name,destructive:!1,sql:h})}}for(let x of Object.keys(w))if(!P[x]){let m=w[x],n=z.createIndex(B.table,m,B.columns);l.push(n),U.push(n),H.push({kind:"create_index",table:B.table,column:m.name,destructive:!1,sql:n}),bZ(`-- Detected new index: ${m.name} in ${B.table}`),r=!0}if(r){let x=l.join(`
441
+
442
+ `);G(x,`alter-${B.table}-table`)}}if(q8+n8===0)bZ("-- Nothing to migrate");else{let K=[];if(q8>0)K.push(`${q8} created`);if(n8>0)K.push(`${n8} updated`);bZ(`-- Migration files: ${K.join(", ")}`)}return{statements:U.length===0?["-- No changes detected"]:U,operations:H}}function O2(Z,$,Y={}){return x0(Z,$,Y).statements}M0();function i3(Z){return Z}class D2{get order(){return 100}get description(){return}}function s3(Z){return Z}s9();s9();s$();d$();qZ();function WJ(Z){switch(Z){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 jJ(Z){let $=String(Z??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test($)||$==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test($))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test($))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test($))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test($))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test($))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test($)||/^float\d*\b/.test($))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test($)||/^int\d*\b/.test($))return"integer";return"other"}function QJ(Z,$,Y){if(Z===$)return!0;if(Y==="sqlite"){if(Z==="boolean"&&$==="integer")return!0;if((Z==="date"||Z==="json")&&$==="text")return!0}if(YZ(Y)&&Z==="boolean"&&$==="integer")return!0;if(Z==="varchar"&&$==="text")return!0;if(Z==="integer"&&$==="fractional")return!0;if(Z==="other"||$==="other")return!0;return!1}async function E2(Z,$={}){let Y=$.dialect??f.dialect,X=Z.tables.map((A)=>A.table),J=await z0({tables:X}),G=new Map(J.map((A)=>[A.table.toLowerCase(),A])),U=[],H=[],z=[];for(let A of Z.tables){let W=G.get(A.table.toLowerCase());if(!W){U.push(A.table);continue}let Q=new Map(W.columns.map((R)=>[R.name.toLowerCase(),R]));for(let R of A.columns){let O=Q.get(R.name.toLowerCase()),N=WJ(R.type);if(!O){H.push({table:A.table,column:R.name,expected:N});continue}let _=jJ(O.sqlType);if(!QJ(N,_,Y))z.push({table:A.table,column:R.name,expected:N,actual:_,actualSqlType:O.sqlType})}}return{missingTables:U,missingColumns:H,typeMismatches:z,clean:U.length===0&&H.length===0&&z.length===0}}function I2(Z){if(Z.clean)return"";let $=[];if(Z.missingTables.length>0)$.push(` Missing tables: ${Z.missingTables.join(", ")}`);for(let J of Z.missingColumns.slice(0,10))$.push(` \u2022 ${J.table}.${J.column} is missing (models declare ${J.expected})`);for(let J of Z.typeMismatches.slice(0,10))$.push(` \u2022 ${J.table}.${J.column} is ${J.actualSqlType}, models declare ${J.expected}`);let Y=Math.min(Z.missingColumns.length,10)+Math.min(Z.typeMismatches.length,10),X=Z.missingColumns.length+Z.typeMismatches.length;if(X>Y)$.push(` + ${X-Y} more`);return["The live schema does not match the models.",...$,"","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(`
443
+ `)}async function C2(Z,$,Y){if(Y.length===0)return;let X=EJ(G9());try{await IJ(Z,$);for(let J of Y)await _7(Z,J,$),$Z(`-- \u2713 Recorded applied migration: ${J}`)}catch(J){$Z(`-- Could not record applied migrations (the schema change itself succeeded): ${J instanceof Error?J.message:String(J)}`)}}function RJ(Z,$){try{return JJ(a9(Z8(Z,$),"utf8"))}catch{return!1}}function S2(Z){let $=Z instanceof Error?Z.message:String(Z);return/duplicate column name/i.test($)||/duplicate key name/i.test($)||/\balready exists\b/i.test($)}function $Z(Z){if(f.verbose)console.log(Z)}function OJ(Z){return Z8(Z,f.snapshotDir||".qb")}function h0(Z,$){return Z8(OJ(Z),`model-snapshot.${$}.json`)}function N2(Z,$){let Y=h0(Z,$);if(!T8(Y))return;try{let X=a9(Y,"utf8"),J=JSON.parse(X);if(J?.plan&&Array.isArray(J.plan.tables)&&J.plan.dialect)return J.plan;if(Array.isArray(J?.tables)&&J?.dialect)return J;$Z("-- Invalid snapshot format, treating as no previous state");return}catch(X){$Z(`-- Could not load snapshot, treating as no previous state: ${X instanceof Error?X.message:String(X)}`);return}}function DJ(Z,$,Y){let X=h0(Z,$),J=OJ(Z),G=HJ(Y);if(T8(X))try{let H=JSON.parse(a9(X,"utf8"));if(H?.hash===G&&H?.dialect===$&&H?.plan){$Z("-- Model snapshot unchanged");return}}catch{}if(!T8(J))KJ(J,{recursive:!0}),$Z(`-- Created snapshot directory: ${J}`);let U={plan:Y,hash:G,dialect:$,updatedAt:new Date().toISOString()};BJ(X,JSON.stringify(U,null,2)),$Z(`-- Model snapshot saved to ${X}`)}function vU(Z,$={}){let Y=$.dialect??Z.dialect;DJ($.workspaceRoot??G9(),Y,Z)}function G9(){return _0()}function EJ(Z){let $=C8(Z,f.migrationDir);if(!T8($))KJ($,{recursive:!0}),$Z(`-- Created SQL directory: ${$}`);return $}async function Q0(Z,$={}){if(await p$(),!Z)Z=Z8(y0.cwd(),"app/Models");let Y=$.dialect||f.dialect||"postgres",X=G9(),J=await W8({modelsDir:Z}),G=n9(J,{dialect:Y,vitessSharded:$.vitessSharded}),U,H=!1;if(!$.full)if(U=N2(X,Y),U)$Z("-- Comparing with stored model snapshot");else{let O=Z8(Z,`.qb-migrations.${Y}.json`),N=String($.state||O);if(T8(N))try{let _=a9(N,"utf8"),F=JSON.parse(_);if(U=F?.plan&&F.plan.tables?F.plan:F?.tables?F:void 0,U)$Z("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!U||$.fromDb)try{let _=await nX(Y),F=new Set(G.tables.map((K)=>K.table)),L=_.tables.filter((K)=>F.has(K.table));if(L.length>0)U={dialect:_.dialect,tables:L},H=!0,$Z(`-- No snapshot; reconciling against live database (${L.length} matching table${L.length===1?"":"s"})`)}catch(_){$Z(`-- Could not introspect live database, treating as no previous state: ${_ instanceof Error?_.message:String(_)}`)}if(!U)$Z("-- No previous snapshot found, generating full migration")}else $Z("-- Full migration requested, ignoring any previous state");let z=$.full?{statements:Q7(G,{dryRun:$.dryRun}),operations:G.tables.map((O)=>({kind:"create_table",table:O.table,destructive:!1,sql:""}))}:x0(U,G,{applyRenames:$.applyRenames,dryRun:$.dryRun,preserveUnknownColumns:H}),A=z.statements,W=z.operations,Q=A.join(`
444
+ `),R=A.some((O)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(O));if($.apply){let O=M2(Z8(w2(),"qb-migrate-")),N=Z8(O,"migration.sql");try{if(R){BJ(N,Q);let _=XZ();await _.file(N),$Z("-- Migration applied"),await C2(_,Y,YJ())}else $Z("-- No changes; nothing to apply")}catch(_){throw console.error("-- Migration failed:",_),_}finally{FJ(O,{recursive:!0,force:!0})}}if(!$.dryRun)DJ(X,Y,G);return{sql:Q,sqlStatements:A,hasChanges:R,plan:G,operations:W}}var _J="bun-query-builder:migrate",P2=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im;function VJ(Z){return Z==="postgres"||Z==="sqlite"}async function q2(Z,$){if(Z==="sqlite")return await $();let Y=XZ(),X;try{X=await Y.reserve()}catch{return await $()}let J=!1;try{return await X.advisoryLock(_J),J=!0,await $()}finally{try{if(J)await X.advisoryUnlock(_J)}finally{X.release?.()}}}async function yU(Z){await p$();let $=G9(),Y=EJ($),X=f.dialect||"postgres",G=LJ(Y).filter((U)=>U.endsWith(".sql")).sort();if(G.length===0)return $Z("-- No migration files found to execute"),!0;$Z(`-- Found ${G.length} script files to execute`);try{let U=XZ();return await q2(X,async()=>{await IJ(U,X);let H=await v2(U,X),z=G.filter((A)=>!H.includes(A));if(z.length===0)return $Z("-- No pending migrations to execute"),!0;$Z(`-- Executing ${z.length} migration${z.length===1?"":"s"}`);for(let A of z){let W=Z8(Y,A);$Z(`-- Executing: ${A}`);try{if(VJ(X)&&!P2.test(a9(W,"utf-8")))await U.transaction(async(R)=>{await R.file(W),await _7(R,A,X)});else if(await U.file(W),await _7(U,A,X),!VJ(X))$Z(`-- (${X} commits DDL implicitly, so ${A} was not applied atomically)`);else $Z(`-- (${A} contains a statement that cannot run in a transaction, so it was not applied atomically)`);$Z(`-- \u2713 Migration ${A} executed and recorded`)}catch(Q){if(RJ(Y,A)&&S2(Q)){await _7(U,A,X),$Z(`-- \u2713 Migration ${A} was already applied; recorded it (${Q instanceof Error?Q.message:String(Q)})`);continue}throw console.error(`-- \u2717 Migration ${A} failed:`,Q),Q}}return $Z("-- All migrations executed successfully"),!0})}catch(U){throw console.error("-- Migration execution failed:",U),U}return!0}async function hU(Z,$={}){if(await p$(),!Z)Z=Z8(y0.cwd(),"app/Models");let Y=$.dialect||f.dialect||"postgres",X=K8(Y),J=G9(),G=async(U)=>{let H=X.dropTable(U);await X0(async(z)=>{if(Y==="sqlite")await z.unsafe("PRAGMA foreign_keys = OFF").execute();if(Y==="mysql"||Y==="vitess")await z.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await z.unsafe(H).execute()}finally{if(Y==="sqlite")await z.unsafe("PRAGMA foreign_keys = ON").execute();if(Y==="mysql"||Y==="vitess")await z.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await G("migrations"),$Z("-- Dropped migrations table")}catch(z){console.error(z)}let U=[],H=[];try{let z=await W8({modelsDir:Z}),A=n9(z,{dialect:Y});U=A.tables.map((Q)=>Q.table);let W=new Set;for(let Q of A.tables)for(let R of Q.columns)if(R.type==="enum"&&R.enumValues&&R.enumValues.length>0){let O=`${Q.table}_${R.name}_type`;W.add(O)}H=Array.from(W)}catch(z){console.error(z),U=[],H=[]}if(U.length===0)$Z("-- No tables found to drop");else{$Z(`-- Dropping ${U.length} tables: ${U.join(", ")}`);for(let z of U.reverse())try{await G(z),$Z(`-- Dropped table: ${z}`)}catch(A){console.error(A),$Z(`-- Table ${z} may not exist, skipping drop`)}}if(H.length>0){$Z(`-- Dropping ${H.length} enum types: ${H.join(", ")}`);for(let z of H)try{let A=X.dropEnumType(z);if(A)await X0(async(W)=>{await W.unsafe(A).execute(),$Z(`-- Dropped enum type: ${z}`)})}catch(A){console.error(A),$Z(`-- Enum type ${z} may not exist, skipping drop`)}}else $Z("-- No enum types found to drop");if(U.length>0&&!$.preserveMigrationState)try{await T2(Z,J,$)}catch(z){console.error(z),$Z("-- Could not clean up migration files")}else if(U.length===0)$Z("-- No models directory found; keeping committed migration files in place");else $Z("-- Preserving migration files and model snapshot for fresh replay");if(!$.preserveMigrationState)try{await x2(J)}catch(z){console.error(z),$Z("-- Could not clear generated directory")}return $Z("-- Database reset completed successfully"),!0}catch(U){return console.error("-- Database reset failed:",U),!1}}async function T2(Z,$,Y={}){if(!Z)Z=Z8(y0.cwd(),"app/Models");if(!$)$=G9();let X=String(Y.dialect||f.dialect||"postgres"),J=h0($,X);if(T8(J))v0(J),$Z(`-- Removed model snapshot file: ${J}`);let G=Z8(Z,`.qb-migrations.${X}.json`),U=String(Y.state||G);if(T8(U))v0(U),$Z(`-- Removed legacy migration state file: ${U}`);k2(C8($,f.migrationDir))}function k2(Z){if(!T8(Z))return;let $=0,Y=[];for(let X of LJ(Z).filter((J)=>J.endsWith(".sql"))){if(!RJ(Z,X)){Y.push(X);continue}v0(Z8(Z,X)),$Z(`-- Removed generated migration file: ${X}`),$+=1}if($Z(`-- Cleaned up ${$} generated migration file${$===1?"":"s"} from migrations directory`),Y.length>0)$Z(`-- Kept ${Y.length} hand-written migration${Y.length===1?"":"s"}: ${Y.slice(0,5).join(", ")}${Y.length>5?`, +${Y.length-5} more`:""}`)}async function bj(Z,$){}async function x2(Z){if(!Z)Z=G9();let $=Z8(Z,"generated");if(T8($))try{FJ($,{recursive:!0,force:!0}),$Z("-- Cleared generated directory")}catch(Y){console.error("-- Failed to clear generated directory:",Y)}}async function IJ(Z,$){let X=K8($).createMigrationsTable();try{await Z.unsafe(X).execute(),$Z("-- Migrations table ready")}catch(J){throw console.error("-- Failed to create migrations table:",J),J}}async function v2(Z,$){let Y=K8($);try{return(await Z.unsafe(Y.getExecutedMigrationsQuery()).execute()).map((J)=>J.migration)}catch(X){return console.error("-- Failed to get executed migrations:",X),[]}}async function _7(Z,$,Y){let X=K8(Y);try{$Z(`-- Recording migration: ${$}`),await Z.unsafe(X.recordMigrationQuery(),[$]).execute(),$Z(`-- Successfully recorded migration: ${$}`)}catch(J){throw console.error(`-- Failed to record migration ${$}:`,J),J}}
445
+ export{YZ as a,VX as b,f as c,g$ as d,s as e,PZ as f,p$ as g,FX as h,P4 as i,n5 as j,i5 as k,f9 as l,wX as m,H6 as n,G0 as o,b8 as p,A6 as q,W6 as r,f8 as s,t8 as t,OH as u,Q6 as v,NH as w,K6 as x,XZ as y,xX as z,vX as A,I6 as B,M6 as C,w6 as D,yX as E,S6 as F,q6 as G,T6 as H,k6 as I,hX as J,x6 as K,bX as L,fX as M,v6 as N,y6 as O,gX as P,h6 as Q,b6 as R,pX as S,U0 as T,mX as U,z0 as V,t6 as W,yZ as X,c$ as Y,u$ as Z,n$ as _,l$ as $,K8 as aa,vU as ba,Q0 as ca,yU as da,hU as ea,T2 as fa,bj as ga,x2 as ha,e6 as ia,zU as ja,tX as ka,WU as la,Z1 as ma,_U as na,X1 as oa,J1 as pa,z1 as qa,wU as ra,CU as sa,SU as ta,NU as ua,PU as va,j1 as wa,kU as xa,xU as ya,_1 as za,I1 as Aa,K1 as Ba,L1 as Ca,sW as Da,oW as Ea,S1 as Fa,N1 as Ga,rW as Ha,aW as Ia,k1 as Ja,x1 as Ka,v1 as La,y1 as Ma,h1 as Na,w0 as Oa,b1 as Pa,aU as Qa,c8 as Ra,L8 as Sa,X3 as Ta,J3 as Ua,G3 as Va,f1 as Wa,g1 as Xa,p1 as Ya,d1 as Za,m1 as _a,H3 as $a,c1 as ab,tU as bb,W3 as cb,j3 as db,Q3 as eb,_3 as fb,u1 as gb,R3 as hb,O3 as ib,D3 as jb,$7 as kb,W8 as lb,o1 as mb,YJ as nb,XJ as ob,JJ as pb,GJ as qb,Q2 as rb,n9 as sb,Q7 as tb,c3 as ub,u3 as vb,HJ as wb,q0 as xb,P8 as yb,T0 as zb,x0 as Ab,O2 as Bb,i3 as Cb,D2 as Db,s3 as Eb,WJ as Fb,jJ as Gb,QJ as Hb,E2 as Ib,I2 as Jb};