@stacksjs/query-builder 0.70.45 → 0.70.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.
Files changed (3) hide show
  1. package/LICENSE.md +21 -0
  2. package/dist/index.js +226 -165
  3. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,69 +1,70 @@
1
1
  // @bun
2
- var A0=import.meta.require;import{existsSync as mZ,statSync as uZ}from"fs";import{existsSync as V_,mkdirSync as Hz,readdirSync as Nz,readFileSync as G_,writeFileSync as Pz}from"fs";import{homedir as c9}from"os";import{dirname as xz,resolve as o0}from"path";import z$ from"process";import{existsSync as nZ,statSync as iZ}from"fs";import{existsSync as m5,mkdirSync as K_,readdirSync as I_,writeFileSync as W_}from"fs";import{homedir as m9}from"os";import{dirname as lZ,resolve as d0}from"path";import b9 from"process";import{join as D_,relative as S_,resolve as sZ}from"path";import U$ from"process";import{existsSync as e7,mkdirSync as dz,readdirSync as cz,writeFileSync as mz}from"fs";import{homedir as e$}from"os";import{dirname as iz,resolve as g0}from"path";import a8 from"process";import{join as M_,relative as R_,resolve as oZ}from"path";import E$ from"process";import{existsSync as $2,mkdirSync as tz,readdirSync as az,writeFileSync as ez}from"fs";import{dirname as ZU,resolve as O$}from"path";import u5 from"process";import{Buffer as H9}from"buffer";import{createCipheriv as J_,createDecipheriv as C_,randomBytes as $5}from"crypto";import{closeSync as Z5,createReadStream as rZ,createWriteStream as w_,existsSync as X5,fsyncSync as tZ,openSync as aZ,writeFileSync as q_}from"fs";import{access as H_,constants as eZ,mkdir as N_,readdir as Q1,rename as $6,stat as u9,unlink as V1,writeFile as _5}from"fs/promises";import{join as n9}from"path";import T0 from"process";import{pipeline as P_}from"stream/promises";import{createGzip as Z6}from"zlib";import i9 from"process";import G9 from"process";import{Buffer as O9}from"buffer";import{createCipheriv as T_,createDecipheriv as k_,randomBytes as L5}from"crypto";import{closeSync as j5,createReadStream as X6,createWriteStream as x_,existsSync as G1,fsyncSync as _6,openSync as L6,writeFileSync as B_}from"fs";import{access as h_,constants as j6,mkdir as y_,readdir as K1,rename as Y6,stat as l9,unlink as I1,writeFile as Y5}from"fs/promises";import{isAbsolute as A_,join as s9,resolve as v_}from"path";import $0 from"process";import{pipeline as b_}from"stream/promises";import{createGzip as F6}from"zlib";import o9 from"process";import K9 from"process";import W1 from"process";import{existsSync as D1}from"fs";import{resolve as F5}from"path";import{existsSync as f_}from"fs";import{existsSync as g_,readdirSync as p_}from"fs";import{extname as z5,resolve as z6}from"path";import d_ from"process";import{join as c_,relative as m_,resolve as U6}from"path";import Q$ from"process";import{Buffer as Q9}from"buffer";import{createCipheriv as u_,createDecipheriv as n_,randomBytes as U5}from"crypto";import{closeSync as E5,createReadStream as E6,createWriteStream as i_,existsSync as S1,fsyncSync as O6,openSync as Q6,writeFileSync as l_}from"fs";import{access as s_,constants as V6,mkdir as o_,readdir as M1,rename as G6,stat as r9,unlink as R1,writeFile as O5}from"fs/promises";import{isAbsolute as r_,join as t9,resolve as t_}from"path";import Z0 from"process";import{pipeline as a_}from"stream/promises";import{createGzip as K6}from"zlib";import a9 from"process";import I9 from"process";import J1 from"process";import{existsSync as C1}from"fs";import{resolve as Q5}from"path";import{existsSync as e_}from"fs";import{Database as TL}from"bun:sqlite";import H1 from"process";import N1 from"process";import{createInterface as mL}from"readline";import{existsSync as iL,readFileSync as lL,writeFileSync as N8}from"fs";import l6 from"process";import s6 from"process";import{existsSync as XZ,mkdirSync as Lj,writeFileSync as jj}from"fs";import{dirname as o6,join as _Z}from"path";import N2 from"process";import{existsSync as k9,mkdirSync as B2,mkdtempSync as zj,readdirSync as h2,readFileSync as y2,rmSync as Uj,unlinkSync as a1,writeFileSync as A2}from"fs";import{tmpdir as Ej}from"os";import{join as b0}from"path";import F1 from"process";import{existsSync as p2,unlinkSync as Rj}from"fs";import{dirname as r6,join as qZ}from"path";import d2 from"process";import{existsSync as c2,readdirSync as qj}from"fs";import{dirname as t6,join as m2}from"path";import u2 from"process";import{readdirSync as kj}from"fs";import{extname as N5,join as a6}from"path";import xj from"process";import{readdirSync as yj,readFileSync as e6,statSync as Aj}from"fs";import{extname as $7,join as vj}from"path";import{writeFileSync as fj}from"fs";import{join as gj}from"path";import pj from"process";import{existsSync as M$,mkdirSync as uj,readdirSync as nj,writeFileSync as ij}from"fs";import{dirname as Z7,join as h9}from"path";import z1 from"process";import{existsSync as tj}from"fs";import{dirname as X7,join as i2}from"path";import l2 from"process";import{existsSync as _Y}from"fs";import{join as LY}from"path";import jY from"process";import{existsSync as _7,statSync as L7}from"fs";import{existsSync as YY,mkdirSync as OO,readdirSync as QO,writeFileSync as VO}from"fs";import{homedir as e9}from"os";import{dirname as IO,resolve as r0}from"path";import R$ from"process";import{join as FY,relative as zY,resolve as j7}from"path";import J$ from"process";import{existsSync as s2,mkdirSync as RO,readdirSync as JO,writeFileSync as CO}from"fs";import{homedir as P5}from"os";import{dirname as HO,resolve as p0}from"path";import _1 from"process";import{join as UY,relative as EY,resolve as Y7}from"path";import C$ from"process";import{existsSync as o2,mkdirSync as xO,readdirSync as BO,writeFileSync as hO}from"fs";import{dirname as AO,resolve as w$}from"path";import LZ from"process";import{Buffer as N9}from"buffer";import{createCipheriv as OY,createDecipheriv as QY,randomBytes as T5}from"crypto";import{closeSync as k5,createReadStream as F7,createWriteStream as VY,existsSync as x5,fsyncSync as z7,openSync as U7,writeFileSync as GY}from"fs";import{access as KY,constants as E7,mkdir as IY,readdir as P1,rename as O7,stat as $8,unlink as T1,writeFile as B5}from"fs/promises";import{join as Z8}from"path";import x0 from"process";import{pipeline as WY}from"stream/promises";import{createGzip as Q7}from"zlib";import X8 from"process";import W9 from"process";import{Buffer as V9}from"buffer";import{createCipheriv as DY,createDecipheriv as SY,randomBytes as h5}from"crypto";import{closeSync as y5,createReadStream as V7,createWriteStream as MY,existsSync as k1,fsyncSync as G7,openSync as K7,writeFileSync as RY}from"fs";import{access as JY,constants as I7,mkdir as CY,readdir as x1,rename as W7,stat as _8,unlink as B1,writeFile as A5}from"fs/promises";import{isAbsolute as wY,join as L8,resolve as qY}from"path";import j0 from"process";import{pipeline as HY}from"stream/promises";import{createGzip as D7}from"zlib";import j8 from"process";import D9 from"process";import h1 from"process";import{existsSync as y1}from"fs";import{resolve as v5}from"path";import{existsSync as NY}from"fs";import{spawnSync as PY}from"child_process";import{existsSync as F8,readFileSync as TY}from"fs";import{join as z8}from"path";import r2 from"process";import{Database as QZ}from"bun:sqlite";import{readdirSync as uF,statSync as nF}from"fs";import{basename as iF,extname as lF}from"path";import sF from"process";import{existsSync as vX,mkdirSync as tF,writeFileSync as aF}from"fs";import{dirname as b7,join as xZ}from"path";import bX from"process";var{defineProperty:c5,getOwnPropertyNames:uX,getOwnPropertyDescriptor:nX}=Object,iX=Object.prototype.hasOwnProperty;function lX($){return this[$]}var sX=($)=>{var Z=(pZ??=new WeakMap).get($),X;if(Z)return Z;if(Z=c5({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var _ of uX($))if(!iX.call(Z,_))c5(Z,_,{get:lX.bind($,_),enumerable:!(X=nX($,_))||X.enumerable})}return pZ.set($,Z),Z},pZ,oX=($)=>$;function rX($,Z){this[$]=oX.bind(null,Z)}var IZ=($,Z)=>{for(var X in Z)c5($,X,{get:Z[X],enumerable:!0,configurable:!0,set:rX.bind(Z,X)})},n=($,Z)=>()=>($&&(Z=$($=0)),Z),tX=import.meta.require;function Iz($){a={...a,...$}}function Wz(){return a}function Dz(){return typeof window<"u"&&typeof document<"u"}async function p1(){if(a.getToken){let $=a.getToken();return $ instanceof Promise?$:$}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function v0(){let $={"Content-Type":"application/json",Accept:"application/json",...a.headers},Z=await p1();if(Z)$.Authorization=`Bearer ${Z}`;return $}async function t0($){if($.status===401)throw a.onUnauthorized?.(),new J9("Unauthorized",401);if(!$.ok){let X=await $.json().catch(()=>({message:"Request failed"}));throw new J9(X.message||`HTTP ${$.status}`,$.status)}let Z=await $.json();if(a.transformResponse)return a.transformResponse(Z);return Z}class c7{state;constructor($){this.state={table:$,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...$){return this.state.selectColumns=$,this}where($,Z,X){if(X===void 0)this.state.wheres.push({column:$,operator:"=",value:Z,boolean:"and"});else this.state.wheres.push({column:$,operator:Z,value:X,boolean:"and"});return this}orWhere($,Z,X){if(X===void 0)this.state.wheres.push({column:$,operator:"=",value:Z,boolean:"or"});else this.state.wheres.push({column:$,operator:Z,value:X,boolean:"or"});return this}andWhere($,Z,X){return this.where($,Z,X)}whereNull($){return this.where($,"is",null)}whereNotNull($){return this.where($,"is not",null)}whereIn($,Z){return this.where($,"in",Z)}whereNotIn($,Z){return this.where($,"not in",Z)}orderBy($,Z="asc"){return this.state.orderBy.push({column:$,direction:Z}),this}orderByDesc($){return this.orderBy($,"desc")}latest($="created_at"){return this.orderBy($,"desc")}oldest($="created_at"){return this.orderBy($,"asc")}limit($){return this.state.limitValue=$,this}offset($){return this.state.offsetValue=$,this}skip($){return this.offset($)}take($){return this.limit($)}with(...$){return this.state.withRelations.push(...$),this}buildQueryParams(){let $=new URLSearchParams;for(let Z of this.state.wheres)if(Z.operator==="=")$.append(Z.column,String(Z.value));else if(Z.operator==="in"&&Array.isArray(Z.value))$.append(`${Z.column}[]`,Z.value.join(","));else if(Z.operator==="is"&&Z.value===null)$.append(`filter[${Z.column}][is]`,"null");else if(Z.operator==="is not"&&Z.value===null)$.append(`filter[${Z.column}][is_not]`,"null");else $.append(`filter[${Z.column}][${Z.operator}]`,String(Z.value));if(this.state.orderBy.length>0){let Z=this.state.orderBy.map((X)=>`${X.direction==="desc"?"-":""}${X.column}`).join(",");$.append("sort",Z)}if(this.state.limitValue!==void 0)$.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)$.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))$.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)$.append("include",this.state.withRelations.join(","));return $}buildUrl($){let Z=`${a.baseUrl}/${this.state.table}`;if($!==void 0)return`${Z}/${$}`;let _=this.buildQueryParams().toString();return _?`${Z}?${_}`:Z}async get(){let $=this.buildUrl(),Z=await fetch($,{method:"GET",headers:await v0()}),X=await t0(Z);return Array.isArray(X)?X:X.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new J9(`No ${this.state.table} found`,404);return $}async find($){let Z=this.buildUrl($);try{let X=await fetch(Z,{method:"GET",headers:await v0()});if(X.status===404)return null;let _=await t0(X);return"data"in _&&!Array.isArray(_.data)?_.data:_}catch{return null}}async findOrFail($){let Z=await this.find($);if(!Z)throw new J9(`${this.state.table} with id ${$} not found`,404);return Z}async count(){let $=this.buildQueryParams();$.append("count","true");let Z=`${a.baseUrl}/${this.state.table}?${$.toString()}`,X=await fetch(Z,{method:"GET",headers:await v0()});return(await t0(X)).count}async exists(){return await this.count()>0}async create($){let Z=`${a.baseUrl}/${this.state.table}`,X=a.transformRequest?a.transformRequest($):$,_=await fetch(Z,{method:"POST",headers:await v0(),body:JSON.stringify(X)}),L=await t0(_);return"data"in L&&!Array.isArray(L.data)?L.data:L}async insert($){return this.create($)}async update($,Z){let X=`${a.baseUrl}/${this.state.table}/${$}`,_=a.transformRequest?a.transformRequest(Z):Z,L=await fetch(X,{method:"PATCH",headers:await v0(),body:JSON.stringify(_)}),j=await t0(L);return"data"in j&&!Array.isArray(j.data)?j.data:j}async delete($){let Z=`${a.baseUrl}/${this.state.table}/${$}`;return(await fetch(Z,{method:"DELETE",headers:await v0()})).ok}async destroy($){return this.delete($)}async paginate($=1,Z=15){this.limit(Z).offset(($-1)*Z);let X=this.buildQueryParams();X.append("paginate","true");let _=`${a.baseUrl}/${this.state.table}?${X.toString()}`,L=await fetch(_,{method:"GET",headers:await v0()});return t0(L)}toState(){return{...this.state}}}function m7($){return new c7($)}function Sz(){return new Proxy({},{get:($,Z)=>{return()=>m7(Z)}})}class O8{_attributes;_definition;constructor($,Z={}){this._definition=$,this._attributes={...Z}}get($){return this._attributes[$]}set($,Z){this._attributes[$]=Z}get attributes(){return{...this._attributes}}get id(){let $=this._definition.primaryKey||"id";return this._attributes[$]}toJSON(){let $=new Set;for(let[X,_]of Object.entries(this._definition.attributes))if(_.hidden)$.add(X);let Z={};for(let[X,_]of Object.entries(this._attributes))if(!$.has(X))Z[X]=_;return Z}}class z0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor($){this._definition=$}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"and"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"and"});return this}orWhere($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"or"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"or"});return this}whereIn($,Z){return this._wheres.push({column:$,operator:"in",value:Z,boolean:"and"}),this}whereNotIn($,Z){return this._wheres.push({column:$,operator:"not in",value:Z,boolean:"and"}),this}whereNull($){return this._wheres.push({column:$,operator:"is",value:null,boolean:"and"}),this}whereNotNull($){return this._wheres.push({column:$,operator:"is not",value:null,boolean:"and"}),this}whereLike($,Z){return this._wheres.push({column:$,operator:"like",value:Z,boolean:"and"}),this}orderBy($,Z="asc"){return this._orderBy.push({column:$,direction:Z}),this}orderByDesc($){return this.orderBy($,"desc")}orderByAsc($){return this.orderBy($,"asc")}limit($){return this._limit=$,this}take($){return this.limit($)}offset($){return this._offset=$,this}skip($){return this.offset($)}select(...$){return this._select=$,this}with(...$){return this._withRelations.push(...$),this}latest($="created_at"){return this.orderByDesc($)}oldest($="created_at"){return this.orderByAsc($)}buildQueryParams(){let $=new URLSearchParams;for(let Z of this._wheres)if(Z.operator==="=")$.append(Z.column,String(Z.value));else if((Z.operator==="in"||Z.operator==="not in")&&Array.isArray(Z.value))$.append(`${Z.column}[]`,Z.value.join(","));else if(Z.operator==="is"&&Z.value===null)$.append(`filter[${Z.column}][is]`,"null");else if(Z.operator==="is not"&&Z.value===null)$.append(`filter[${Z.column}][is_not]`,"null");else $.append(`filter[${Z.column}][${Z.operator}]`,String(Z.value));if(this._orderBy.length>0){let Z=this._orderBy.map((X)=>`${X.direction==="desc"?"-":""}${X.column}`).join(",");$.append("sort",Z)}if(this._limit!==void 0)$.append("limit",String(this._limit));if(this._offset!==void 0)$.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))$.append("fields",this._select.join(","));if(this._withRelations.length>0)$.append("include",this._withRelations.join(","));return $}buildUrl($){let Z=`${a.baseUrl}/${this.getTablePath()}`;if($!==void 0)return`${Z}/${$}`;let _=this.buildQueryParams().toString();return _?`${Z}?${_}`:Z}async get(){let $=this.buildUrl(),Z=await fetch($,{method:"GET",headers:await v0()}),X=await t0(Z);return(Array.isArray(X)?X:X.data).map((L)=>new O8(this._definition,L))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new J9(`No ${this._definition.name} found`,404);return $}async find($){let Z=this.buildUrl($);try{let X=await fetch(Z,{method:"GET",headers:await v0()});if(X.status===404)return null;let _=await t0(X),L="data"in _&&!Array.isArray(_.data)?_.data:_;return new O8(this._definition,L)}catch{return null}}async findOrFail($){let Z=await this.find($);if(!Z)throw new J9(`${this._definition.name} with id ${$} not found`,404);return Z}async count(){let $=this.buildQueryParams();$.append("count","true");let Z=`${a.baseUrl}/${this.getTablePath()}?${$.toString()}`,X=await fetch(Z,{method:"GET",headers:await v0()});return(await t0(X)).count}async exists(){return await this.count()>0}async pluck($){return this._select=[$],(await this.get()).map((X)=>X.get($))}async paginate($=1,Z=15){this._limit=Z,this._offset=($-1)*Z;let X=this.buildQueryParams();X.append("paginate","true");let _=`${a.baseUrl}/${this.getTablePath()}?${X.toString()}`,L=await fetch(_,{method:"GET",headers:await v0()}),j=await t0(L);return{...j,data:j.data.map((Y)=>new O8(this._definition,Y))}}}function aX($){return new Proxy({query:()=>new z0($),where(X,_,L){return new z0($).where(X,_,L)},orWhere(X,_,L){return new z0($).orWhere(X,_,L)},whereIn(X,_){return new z0($).whereIn(X,_)},whereNotIn(X,_){return new z0($).whereNotIn(X,_)},whereNull(X){return new z0($).whereNull(X)},whereNotNull(X){return new z0($).whereNotNull(X)},whereLike(X,_){return new z0($).whereLike(X,_)},orderBy(X,_="asc"){return new z0($).orderBy(X,_)},orderByDesc(X){return new z0($).orderByDesc(X)},select(...X){return new z0($).select(...X)},limit:(X)=>new z0($).limit(X),take:(X)=>new z0($).take(X),skip:(X)=>new z0($).skip(X),latest:(X="created_at")=>new z0($).latest(X),oldest:(X="created_at")=>new z0($).oldest(X),async find(X){return new z0($).find(X)},async findOrFail(X){return new z0($).findOrFail(X)},async all(){return new z0($).get()},async first(){return new z0($).first()},async firstOrFail(){return new z0($).firstOrFail()},async count(){return new z0($).count()},async exists(){return new z0($).exists()},async paginate(X,_){return new z0($).paginate(X,_)},async pluck(X){return new z0($).pluck(X)},async create(X){let _=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,L=`${a.baseUrl}/${_}`,j=a.transformRequest?a.transformRequest(X):X,Y=await fetch(L,{method:"POST",headers:await v0(),body:JSON.stringify(j)}),z=await t0(Y),F="data"in z&&!Array.isArray(z.data)?z.data:z;return new O8($,F)},async update(X,_){let L=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,j=`${a.baseUrl}/${L}/${X}`,Y=a.transformRequest?a.transformRequest(_):_,z=await fetch(j,{method:"PATCH",headers:await v0(),body:JSON.stringify(Y)}),F=await t0(z),E="data"in F&&!Array.isArray(F.data)?F.data:F;return new O8($,E)},async delete(X){let _=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,L=`${a.baseUrl}/${_}/${X}`;return(await fetch(L,{method:"DELETE",headers:await v0()})).ok},async destroy(X){return this.delete(X)},getDefinition:()=>$,getTable:()=>$.table},{get(X,_){if(typeof _==="string"&&_.startsWith("where")&&_.length>5){let L=_.slice(5),j=L.charAt(0).toLowerCase()+L.slice(1);if(j in $.attributes||j==="id"||j===$.primaryKey)return(Y)=>new z0($).where(j,Y)}return Reflect.get(X,_)}})}var a,J9,eX,$_,u7=n(()=>{a={baseUrl:""},J9=class extends Error{status;constructor(Z,X){super(Z);this.name="BrowserQueryError",this.status=X}},eX={async login($){let Z=await fetch(`${a.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...a.headers},body:JSON.stringify($)});if(!Z.ok){let L=await Z.json().catch(()=>({message:"Login failed"}));throw new J9(L.message||"Login failed",Z.status)}let X=await Z.json(),_=X.data||X;if(typeof localStorage<"u"&&_.token)localStorage.setItem("auth_token",_.token);return _},async register($){let Z=await fetch(`${a.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...a.headers},body:JSON.stringify($)});if(!Z.ok){let L=await Z.json().catch(()=>({message:"Registration failed"}));throw new J9(L.message||"Registration failed",Z.status)}let X=await Z.json(),_=X.data||X;if(typeof localStorage<"u"&&_.token)localStorage.setItem("auth_token",_.token);return _},async logout(){if(await p1())try{await fetch(`${a.baseUrl}/logout`,{method:"POST",headers:await v0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await p1())return null;try{let Z=await fetch(`${a.baseUrl}/user`,{method:"GET",headers:await v0()});if(Z.status===401)return a.onUnauthorized?.(),null;if(!Z.ok)return null;let X=await Z.json();return X.user||X}catch{return null}},async check(){return await this.user()!==null},getToken:p1},$_=m7});class n7{config;entityMappings=new Map;constructor($){if(this.config=$,$.entityMappings)for(let Z of $.entityMappings)this.registerEntity(Z)}createTable($){return{...$,billingMode:$.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable($){return{tableName:$}}registerEntity($){this.entityMappings.set($.entityType,$)}getEntityMapping($){return this.entityMappings.get($)}buildPrimaryKey($,Z){let X=this.entityMappings.get($);if(!X)throw Error(`No entity mapping found for type: ${$}`);let _=this.interpolatePattern(X.pkPattern,Z),L=this.interpolatePattern(X.skPattern,Z);return{pk:_,sk:L}}parseEntityFromItem($){let Z=$.pk||$.PK;if(!Z)return null;for(let[X,_]of this.entityMappings){let L=_.pkPattern.split("${")[0];if(Z.startsWith(L))return{entityType:X,data:this.unmarshall($)}}return null}buildQueryParams($){return{tableName:$.tableName??this.config.tableName??"",keyConditions:$.keyConditions??[],...$}}buildScanParams($){return{tableName:$.tableName??this.config.tableName??"",...$}}buildGetItemParams($){return{tableName:$.tableName??this.config.tableName??"",key:$.key??{},...$}}buildPutItemParams($){return{tableName:$.tableName??this.config.tableName??"",item:$.item??{},...$}}buildUpdateItemParams($){return{tableName:$.tableName??this.config.tableName??"",key:$.key??{},updateExpressions:$.updateExpressions??{},...$}}buildDeleteItemParams($){return{tableName:$.tableName??this.config.tableName??"",key:$.key??{},...$}}buildBatchGetItemParams($){return{requestItems:$.requestItems??{}}}buildBatchWriteItemParams($){return{requestItems:$.requestItems??{}}}buildTransactWriteParams($){return{transactItems:$.transactItems??[],...$}}buildKeyConditionExpression($){return this.buildExpression($,"AND")}buildFilterExpression($){return this.buildExpression($,"AND")}buildUpdateExpression($){let Z={},X={},_=[],L=0;if($.set&&Object.keys($.set).length>0){let j=[];for(let[Y,z]of Object.entries($.set)){let F=`#attr${L}`,E=`:val${L}`;Z[F]=Y,X[E]=this.marshallValue(z),j.push(`${F} = ${E}`),L++}_.push(`SET ${j.join(", ")}`)}if($.remove&&$.remove.length>0){let j=[];for(let Y of $.remove){let z=`#attr${L}`;Z[z]=Y,j.push(z),L++}_.push(`REMOVE ${j.join(", ")}`)}if($.add&&Object.keys($.add).length>0){let j=[];for(let[Y,z]of Object.entries($.add)){let F=`#attr${L}`,E=`:val${L}`;Z[F]=Y,X[E]=this.marshallValue(z),j.push(`${F} ${E}`),L++}_.push(`ADD ${j.join(", ")}`)}if($.delete&&Object.keys($.delete).length>0){let j=[];for(let[Y,z]of Object.entries($.delete)){let F=`#attr${L}`,E=`:val${L}`;Z[F]=Y,X[E]=this.marshallValue(z),j.push(`${F} ${E}`),L++}_.push(`DELETE ${j.join(", ")}`)}return{expression:_.join(" "),expressionAttributeNames:Z,expressionAttributeValues:X}}buildProjectionExpression($){let Z={},X=[];return $.forEach((_,L)=>{let j=`#proj${L}`;Z[j]=_,X.push(j)}),{expression:X.join(", "),expressionAttributeNames:Z}}marshall($){let Z={};for(let[X,_]of Object.entries($))Z[X]=this.marshallValue(_);return Z}unmarshall($){let Z={};for(let[X,_]of Object.entries($))Z[X]=this.unmarshallValue(_);return Z}interpolatePattern($,Z){return $.replace(/\$\{(\w+)\}/g,(X,_)=>{if(!(_ in Z))throw Error(`Missing value for pattern key: ${_}`);return String(Z[_])})}buildExpression($,Z){let X={},_={},L=[];return $.forEach((j,Y)=>{let z=`#attr${Y}`;X[z]=j.attribute;let F;switch(j.operator){case"=":case"<":case"<=":case">":case">=":{let E=`:val${Y}`;_[E]=this.marshallValue(j.value),F=`${z} ${j.operator} ${E}`;break}case"BETWEEN":{let E=`:val${Y}a`,U=`:val${Y}b`;_[E]=this.marshallValue(j.values?.[0]),_[U]=this.marshallValue(j.values?.[1]),F=`${z} BETWEEN ${E} AND ${U}`;break}case"begins_with":{let E=`:val${Y}`;_[E]=this.marshallValue(j.value),F=`begins_with(${z}, ${E})`;break}case"contains":{let E=`:val${Y}`;_[E]=this.marshallValue(j.value),F=`contains(${z}, ${E})`;break}case"attribute_exists":F=`attribute_exists(${z})`;break;case"attribute_not_exists":F=`attribute_not_exists(${z})`;break;case"attribute_type":{let E=`:val${Y}`;_[E]={S:j.value},F=`attribute_type(${z}, ${E})`;break}case"IN":{let E=(j.values??[]).map((U,V)=>`:val${Y}_${V}`);j.values?.forEach((U,V)=>{_[`:val${Y}_${V}`]=this.marshallValue(U)}),F=`${z} IN (${E.join(", ")})`;break}default:throw Error(`Unknown operator: ${j.operator}`)}L.push(F)}),{expression:L.join(` ${Z} `),expressionAttributeNames:X,expressionAttributeValues:_}}marshallValue($){if($===null||$===void 0)return{NULL:!0};if(typeof $==="string")return{S:$};if(typeof $==="number")return{N:String($)};if(typeof $==="boolean")return{BOOL:$};if($ instanceof Uint8Array||Buffer.isBuffer($))return{B:$};if(Array.isArray($)){if($.length===0)return{L:[]};let Z=typeof $[0],X=$.every((L)=>typeof L==="string"),_=$.every((L)=>typeof L==="number");if(X)return{SS:$};if(_)return{NS:$.map(String)};return{L:$.map((L)=>this.marshallValue(L))}}if(typeof $==="object"){let Z={};for(let[X,_]of Object.entries($))Z[X]=this.marshallValue(_);return{M:Z}}return{S:String($)}}unmarshallValue($){if(!$||typeof $!=="object")return $;if("S"in $)return $.S;if("N"in $)return Number($.N);if("BOOL"in $)return $.BOOL;if("NULL"in $)return null;if("B"in $)return $.B;if("SS"in $)return $.SS;if("NS"in $)return $.NS.map(Number);if("BS"in $)return $.BS;if("L"in $)return $.L.map((Z)=>this.unmarshallValue(Z));if("M"in $){let Z={};for(let[X,_]of Object.entries($.M))Z[X]=this.unmarshallValue(_);return Z}return $}}function V8($){return new n7($)}async function C8($,Z){let X=$ instanceof ArrayBuffer?$:$.buffer.slice($.byteOffset,$.byteOffset+$.byteLength),_=await crypto.subtle.importKey("raw",X,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",_,new TextEncoder().encode(Z))}async function dZ($){let Z=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return Array.from(new Uint8Array(Z)).map((X)=>X.toString(16).padStart(2,"0")).join("")}async function Z_($,Z,X,_){let L=await C8(new TextEncoder().encode(`AWS4${$}`),Z),j=await C8(L,X),Y=await C8(j,_);return C8(Y,"aws4_request")}async function X_($,Z,X,_,L,j,Y){let F=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),E=F.slice(0,8),U=Z.pathname,V=Z.search.slice(1),Q={...X,host:Z.host,"x-amz-date":F};if(L.sessionToken)Q["x-amz-security-token"]=L.sessionToken;let O=Object.keys(Q).sort(),K=O.map((g)=>`${g.toLowerCase()}:${Q[g].trim()}`).join(`
2
+ var p0=import.meta.require;import{existsSync as M5,statSync as H5}from"fs";import{existsSync as Q2,mkdirSync as uj,readdirSync as nj,readFileSync as z2,writeFileSync as ij}from"fs";import{homedir as zX}from"os";import{dirname as oj,resolve as L9}from"path";import N8 from"process";import{existsSync as C5,statSync as w5}from"fs";import{existsSync as G1,mkdirSync as L2,readdirSync as j2,writeFileSync as E2}from"fs";import{homedir as LX}from"os";import{dirname as q5,resolve as i0}from"path";import t9 from"process";import{join as G2,relative as F2,resolve as P5}from"path";import S8 from"process";import{existsSync as A6,mkdirSync as _E,readdirSync as QE,writeFileSync as zE}from"fs";import{homedir as GZ}from"os";import{dirname as EE,resolve as u0}from"path";import P$ from"process";import{join as O2,relative as J2,resolve as T5}from"path";import A8 from"process";import{existsSync as k6,mkdirSync as WE,readdirSync as VE,writeFileSync as IE}from"fs";import{dirname as RE,resolve as k8}from"path";import F1 from"process";import{Buffer as h9}from"buffer";import{createCipheriv as W2,createDecipheriv as V2,randomBytes as FZ}from"crypto";import{closeSync as OZ,createReadStream as N5,createWriteStream as I2,existsSync as JZ,fsyncSync as S5,openSync as A5,writeFileSync as K2}from"fs";import{access as R2,constants as k5,mkdir as D2,readdir as f$,rename as x5,stat as jX,unlink as g$,writeFile as WZ}from"fs/promises";import{join as EX}from"path";import b0 from"process";import{pipeline as M2}from"stream/promises";import{createGzip as B5}from"zlib";import GX from"process";import P9 from"process";import{Buffer as R9}from"buffer";import{createCipheriv as H2,createDecipheriv as C2,randomBytes as VZ}from"crypto";import{closeSync as IZ,createReadStream as y5,createWriteStream as w2,existsSync as d$,fsyncSync as h5,openSync as v5,writeFileSync as q2}from"fs";import{access as P2,constants as b5,mkdir as T2,readdir as p$,rename as f5,stat as FX,unlink as c$,writeFile as KZ}from"fs/promises";import{isAbsolute as N2,join as OX,resolve as S2}from"path";import z0 from"process";import{pipeline as A2}from"stream/promises";import{createGzip as g5}from"zlib";import JX from"process";import T9 from"process";import m$ from"process";import{existsSync as u$}from"fs";import{resolve as RZ}from"path";import{existsSync as k2}from"fs";import{existsSync as x2,readdirSync as B2}from"fs";import{extname as DZ,resolve as d5}from"path";import y2 from"process";import{join as h2,relative as v2,resolve as p5}from"path";import x8 from"process";import{Buffer as D9}from"buffer";import{createCipheriv as b2,createDecipheriv as f2,randomBytes as MZ}from"crypto";import{closeSync as HZ,createReadStream as c5,createWriteStream as g2,existsSync as n$,fsyncSync as m5,openSync as u5,writeFileSync as d2}from"fs";import{access as p2,constants as n5,mkdir as c2,readdir as i$,rename as i5,stat as WX,unlink as l$,writeFile as CZ}from"fs/promises";import{isAbsolute as m2,join as VX,resolve as u2}from"path";import L0 from"process";import{pipeline as n2}from"stream/promises";import{createGzip as l5}from"zlib";import IX from"process";import N9 from"process";import s$ from"process";import{existsSync as o$}from"fs";import{resolve as wZ}from"path";import{existsSync as i2}from"fs";import{Database as w_}from"bun:sqlite";import{mkdirSync as q_}from"fs";import{dirname as P_}from"path";import t$ from"process";import $8 from"process";import{createInterface as n_}from"readline";import{existsSync as s_,readFileSync as o_,writeFileSync as rX}from"fs";import NY from"process";import SY from"process";import{existsSync as P1,mkdirSync as IQ,writeFileSync as KQ}from"fs";import{dirname as AY,join as T1}from"path";import GU from"process";import{existsSync as g9,mkdirSync as IU,mkdtempSync as MQ,readdirSync as KU,readFileSync as RU,rmSync as HQ,unlinkSync as H8,writeFileSync as DU}from"fs";import{tmpdir as CQ}from"os";import{join as m0}from"path";import B$ from"process";import{existsSync as N1,readFileSync as yQ,unlinkSync as hQ}from"fs";import{dirname as xY,join as _5}from"path";import qU from"process";import{existsSync as PU,readdirSync as pQ}from"fs";import{dirname as BY,join as TU}from"path";import NU from"process";import{readdirSync as iQ}from"fs";import{extname as dZ,join as yY}from"path";import lQ from"process";import{readdirSync as rQ,readFileSync as hY,statSync as aQ}from"fs";import{extname as vY,join as tQ}from"path";import{writeFileSync as Xz}from"fs";import{join as $z}from"path";import Zz from"process";import{existsSync as p8,mkdirSync as Qz,readdirSync as zz,writeFileSync as Lz}from"fs";import{dirname as bY,join as c9}from"path";import y$ from"process";import{existsSync as Oz}from"fs";import{dirname as fY,join as AU}from"path";import kU from"process";import{existsSync as Rz}from"fs";import{join as Dz}from"path";import Mz from"process";import{existsSync as gY,statSync as dY}from"fs";import{join as Hz,relative as Cz,resolve as pY}from"path";import c8 from"process";import{Buffer as M9}from"buffer";import{createCipheriv as wz,createDecipheriv as qz,randomBytes as pZ}from"crypto";import{closeSync as cZ,createReadStream as cY,createWriteStream as Pz,existsSync as Z8,fsyncSync as mY,openSync as uY,writeFileSync as Tz}from"fs";import{access as Nz,constants as nY,mkdir as Sz,readdir as Y8,rename as iY,stat as RX,unlink as U8,writeFile as mZ}from"fs/promises";import{isAbsolute as Az,join as DX,resolve as kz}from"path";import F0 from"process";import{pipeline as xz}from"stream/promises";import{createGzip as lY}from"zlib";import MX from"process";import S9 from"process";import _8 from"process";import{existsSync as Q8}from"fs";import{resolve as uZ}from"path";import{existsSync as Bz}from"fs";import{existsSync as S1,mkdirSync as yz,readdirSync as hz,readFileSync as vz,writeFileSync as bz}from"fs";import{homedir as HX}from"os";import{dirname as sY,resolve as l0}from"path";import XX from"process";import{existsSync as fz,readdirSync as gz}from"fs";import{extname as nZ,resolve as oY}from"path";import dz from"process";import{spawnSync as pz}from"child_process";import{existsSync as TX,readFileSync as cz}from"fs";import{join as NX}from"path";import xU from"process";import{Database as b1}from"bun:sqlite";import{readdirSync as eL,statSync as Xj}from"fs";import{basename as $j,extname as Zj}from"path";import Yj from"process";import{existsSync as D7,mkdirSync as zj,writeFileSync as Lj}from"fs";import{dirname as O6,join as O5}from"path";import M7 from"process";var{defineProperty:E1,getOwnPropertyNames:b7,getOwnPropertyDescriptor:f7}=Object,g7=Object.prototype.hasOwnProperty;function d7(X){return this[X]}var p7=(X)=>{var $=(K5??=new WeakMap).get(X),Z;if($)return $;if($=E1({},"__esModule",{value:!0}),X&&typeof X==="object"||typeof X==="function"){for(var Y of b7(X))if(!g7.call($,Y))E1($,Y,{get:d7.bind(X,Y),enumerable:!(Z=f7(X,Y))||Z.enumerable})}return K5.set(X,$),$},K5,c7=(X)=>X;function m7(X,$){this[X]=c7.bind(null,$)}var n1=(X,$)=>{for(var Z in $)E1(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:m7.bind($,Z)})},e=(X,$)=>()=>(X&&($=X(X=0)),$),u7=import.meta.require;function yj(X){_0={..._0,...X}}function hj(){return _0}function vj(){return typeof window<"u"&&typeof document<"u"}async function E8(){if(_0.getToken){let X=_0.getToken();return X instanceof Promise?X:X}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function c0(){let X={"Content-Type":"application/json",Accept:"application/json",..._0.headers},$=await E8();if($)X.Authorization=`Bearer ${$}`;return X}async function E9(X){if(X.status===401)throw _0.onUnauthorized?.(),new B9("Unauthorized",401);if(!X.ok){let Z=await X.json().catch(()=>({message:"Request failed"}));throw new B9(Z.message||`HTTP ${X.status}`,X.status)}let $=await X.json();if(_0.transformResponse)return _0.transformResponse($);return $}class R6{state;constructor(X){this.state={table:X,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...X){return this.state.selectColumns=X,this}where(X,$,Z){if(Z===void 0)this.state.wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this.state.wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this.state.wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this.state.wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}andWhere(X,$,Z){return this.where(X,$,Z)}whereNull(X){return this.where(X,"is",null)}whereNotNull(X){return this.where(X,"is not",null)}whereIn(X,$){return this.where(X,"in",$)}whereNotIn(X,$){return this.where(X,"not in",$)}orderBy(X,$="asc"){return this.state.orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}latest(X="created_at"){return this.orderBy(X,"desc")}oldest(X="created_at"){return this.orderBy(X,"asc")}limit(X){return this.state.limitValue=X,this}offset(X){return this.state.offsetValue=X,this}skip(X){return this.offset(X)}take(X){return this.limit(X)}with(...X){return this.state.withRelations.push(...X),this}buildQueryParams(){let X=new URLSearchParams;for(let $ of this.state.wheres)if($.operator==="=")X.append($.column,String($.value));else if($.operator==="in"&&Array.isArray($.value))X.append(`${$.column}[]`,$.value.join(","));else if($.operator==="is"&&$.value===null)X.append(`filter[${$.column}][is]`,"null");else if($.operator==="is not"&&$.value===null)X.append(`filter[${$.column}][is_not]`,"null");else X.append(`filter[${$.column}][${$.operator}]`,String($.value));if(this.state.orderBy.length>0){let $=this.state.orderBy.map((Z)=>`${Z.direction==="desc"?"-":""}${Z.column}`).join(",");X.append("sort",$)}if(this.state.limitValue!==void 0)X.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)X.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))X.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)X.append("include",this.state.withRelations.join(","));return X}buildUrl(X){let $=`${_0.baseUrl}/${this.state.table}`;if(X!==void 0)return`${$}/${X}`;let Y=this.buildQueryParams().toString();return Y?`${$}?${Y}`:$}async get(){let X=this.buildUrl(),$=await fetch(X,{method:"GET",headers:await c0()}),Z=await E9($);return Array.isArray(Z)?Z:Z.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let X=await this.first();if(!X)throw new B9(`No ${this.state.table} found`,404);return X}async find(X){let $=this.buildUrl(X);try{let Z=await fetch($,{method:"GET",headers:await c0()});if(Z.status===404)return null;let Y=await E9(Z);return"data"in Y&&!Array.isArray(Y.data)?Y.data:Y}catch{return null}}async findOrFail(X){let $=await this.find(X);if(!$)throw new B9(`${this.state.table} with id ${X} not found`,404);return $}async count(){let X=this.buildQueryParams();X.append("count","true");let $=`${_0.baseUrl}/${this.state.table}?${X.toString()}`,Z=await fetch($,{method:"GET",headers:await c0()});return(await E9(Z)).count}async exists(){return await this.count()>0}async create(X){let $=`${_0.baseUrl}/${this.state.table}`,Z=_0.transformRequest?_0.transformRequest(X):X,Y=await fetch($,{method:"POST",headers:await c0(),body:JSON.stringify(Z)}),U=await E9(Y);return"data"in U&&!Array.isArray(U.data)?U.data:U}async insert(X){return this.create(X)}async update(X,$){let Z=`${_0.baseUrl}/${this.state.table}/${X}`,Y=_0.transformRequest?_0.transformRequest($):$,U=await fetch(Z,{method:"PATCH",headers:await c0(),body:JSON.stringify(Y)}),_=await E9(U);return"data"in _&&!Array.isArray(_.data)?_.data:_}async delete(X){let $=`${_0.baseUrl}/${this.state.table}/${X}`;return(await fetch($,{method:"DELETE",headers:await c0()})).ok}async destroy(X){return this.delete(X)}async paginate(X=1,$=15){this.limit($).offset((X-1)*$);let Z=this.buildQueryParams();Z.append("paginate","true");let Y=`${_0.baseUrl}/${this.state.table}?${Z.toString()}`,U=await fetch(Y,{method:"GET",headers:await c0()});return E9(U)}toState(){return{...this.state}}}function D6(X){return new R6(X)}function bj(){return new Proxy({},{get:(X,$)=>{return()=>D6($)}})}class kX{_attributes;_definition;constructor(X,$={}){this._definition=X,this._attributes={...$}}get(X){return this._attributes[X]}set(X,$){this._attributes[X]=$}get attributes(){return{...this._attributes}}get id(){let X=this._definition.primaryKey||"id";return this._attributes[X]}toJSON(){let X=new Set;for(let[Z,Y]of Object.entries(this._definition.attributes))if(Y.hidden)X.add(Z);let $={};for(let[Z,Y]of Object.entries(this._attributes))if(!X.has(Z))$[Z]=Y;return $}}class V0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(X){this._definition=X}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}whereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"and"}),this}whereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"and"}),this}whereNull(X){return this._wheres.push({column:X,operator:"is",value:null,boolean:"and"}),this}whereNotNull(X){return this._wheres.push({column:X,operator:"is not",value:null,boolean:"and"}),this}whereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"and"}),this}orderBy(X,$="asc"){return this._orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}orderByAsc(X){return this.orderBy(X,"asc")}limit(X){return this._limit=X,this}take(X){return this.limit(X)}offset(X){return this._offset=X,this}skip(X){return this.offset(X)}select(...X){return this._select=X,this}with(...X){return this._withRelations.push(...X),this}latest(X="created_at"){return this.orderByDesc(X)}oldest(X="created_at"){return this.orderByAsc(X)}buildQueryParams(){let X=new URLSearchParams;for(let $ of this._wheres)if($.operator==="=")X.append($.column,String($.value));else if(($.operator==="in"||$.operator==="not in")&&Array.isArray($.value))X.append(`${$.column}[]`,$.value.join(","));else if($.operator==="is"&&$.value===null)X.append(`filter[${$.column}][is]`,"null");else if($.operator==="is not"&&$.value===null)X.append(`filter[${$.column}][is_not]`,"null");else X.append(`filter[${$.column}][${$.operator}]`,String($.value));if(this._orderBy.length>0){let $=this._orderBy.map((Z)=>`${Z.direction==="desc"?"-":""}${Z.column}`).join(",");X.append("sort",$)}if(this._limit!==void 0)X.append("limit",String(this._limit));if(this._offset!==void 0)X.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))X.append("fields",this._select.join(","));if(this._withRelations.length>0)X.append("include",this._withRelations.join(","));return X}buildUrl(X){let $=`${_0.baseUrl}/${this.getTablePath()}`;if(X!==void 0)return`${$}/${X}`;let Y=this.buildQueryParams().toString();return Y?`${$}?${Y}`:$}async get(){let X=this.buildUrl(),$=await fetch(X,{method:"GET",headers:await c0()}),Z=await E9($);return(Array.isArray(Z)?Z:Z.data).map((U)=>new kX(this._definition,U))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let X=await this.first();if(!X)throw new B9(`No ${this._definition.name} found`,404);return X}async find(X){let $=this.buildUrl(X);try{let Z=await fetch($,{method:"GET",headers:await c0()});if(Z.status===404)return null;let Y=await E9(Z),U="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new kX(this._definition,U)}catch{return null}}async findOrFail(X){let $=await this.find(X);if(!$)throw new B9(`${this._definition.name} with id ${X} not found`,404);return $}async count(){let X=this.buildQueryParams();X.append("count","true");let $=`${_0.baseUrl}/${this.getTablePath()}?${X.toString()}`,Z=await fetch($,{method:"GET",headers:await c0()});return(await E9(Z)).count}async exists(){return await this.count()>0}async pluck(X){return this._select=[X],(await this.get()).map((Z)=>Z.get(X))}async paginate(X=1,$=15){this._limit=$,this._offset=(X-1)*$;let Z=this.buildQueryParams();Z.append("paginate","true");let Y=`${_0.baseUrl}/${this.getTablePath()}?${Z.toString()}`,U=await fetch(Y,{method:"GET",headers:await c0()}),_=await E9(U);return{..._,data:_.data.map((Q)=>new kX(this._definition,Q))}}}function n7(X){return new Proxy({query:()=>new V0(X),where(Z,Y,U){return new V0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new V0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new V0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new V0(X).whereNotIn(Z,Y)},whereNull(Z){return new V0(X).whereNull(Z)},whereNotNull(Z){return new V0(X).whereNotNull(Z)},whereLike(Z,Y){return new V0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new V0(X).orderBy(Z,Y)},orderByDesc(Z){return new V0(X).orderByDesc(Z)},select(...Z){return new V0(X).select(...Z)},limit:(Z)=>new V0(X).limit(Z),take:(Z)=>new V0(X).take(Z),skip:(Z)=>new V0(X).skip(Z),latest:(Z="created_at")=>new V0(X).latest(Z),oldest:(Z="created_at")=>new V0(X).oldest(Z),async find(Z){return new V0(X).find(Z)},async findOrFail(Z){return new V0(X).findOrFail(Z)},async all(){return new V0(X).get()},async first(){return new V0(X).first()},async firstOrFail(){return new V0(X).firstOrFail()},async count(){return new V0(X).count()},async exists(){return new V0(X).exists()},async paginate(Z,Y){return new V0(X).paginate(Z,Y)},async pluck(Z){return new V0(X).pluck(Z)},async create(Z){let Y=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,U=`${_0.baseUrl}/${Y}`,_=_0.transformRequest?_0.transformRequest(Z):Z,Q=await fetch(U,{method:"POST",headers:await c0(),body:JSON.stringify(_)}),L=await E9(Q),z="data"in L&&!Array.isArray(L.data)?L.data:L;return new kX(X,z)},async update(Z,Y){let U=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,_=`${_0.baseUrl}/${U}/${Z}`,Q=_0.transformRequest?_0.transformRequest(Y):Y,L=await fetch(_,{method:"PATCH",headers:await c0(),body:JSON.stringify(Q)}),z=await E9(L),j="data"in z&&!Array.isArray(z.data)?z.data:z;return new kX(X,j)},async delete(Z){let Y=typeof X.traits?.useApi==="object"&&X.traits.useApi?.uri||X.table,U=`${_0.baseUrl}/${Y}/${Z}`;return(await fetch(U,{method:"DELETE",headers:await c0()})).ok},async destroy(Z){return this.delete(Z)},getDefinition:()=>X,getTable:()=>X.table},{get(Z,Y){if(typeof Y==="string"&&Y.startsWith("where")&&Y.length>5){let U=Y.slice(5),_=U.charAt(0).toLowerCase()+U.slice(1);if(_ in X.attributes||_==="id"||_===X.primaryKey)return(Q)=>new V0(X).where(_,Q)}return Reflect.get(Z,Y)}})}var _0,B9,i7,l7,M6=e(()=>{_0={baseUrl:""},B9=class extends Error{status;constructor($,Z){super($);this.name="BrowserQueryError",this.status=Z}},i7={async login(X){let $=await fetch(`${_0.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",..._0.headers},body:JSON.stringify(X)});if(!$.ok){let U=await $.json().catch(()=>({message:"Login failed"}));throw new B9(U.message||"Login failed",$.status)}let Z=await $.json(),Y=Z.data||Z;if(typeof localStorage<"u"&&Y.token)localStorage.setItem("auth_token",Y.token);return Y},async register(X){let $=await fetch(`${_0.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",..._0.headers},body:JSON.stringify(X)});if(!$.ok){let U=await $.json().catch(()=>({message:"Registration failed"}));throw new B9(U.message||"Registration failed",$.status)}let Z=await $.json(),Y=Z.data||Z;if(typeof localStorage<"u"&&Y.token)localStorage.setItem("auth_token",Y.token);return Y},async logout(){if(await E8())try{await fetch(`${_0.baseUrl}/logout`,{method:"POST",headers:await c0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await E8())return null;try{let $=await fetch(`${_0.baseUrl}/user`,{method:"GET",headers:await c0()});if($.status===401)return _0.onUnauthorized?.(),null;if(!$.ok)return null;let Z=await $.json();return Z.user||Z}catch{return null}},async check(){return await this.user()!==null},getToken:E8},l7=D6});class H6{config;entityMappings=new Map;constructor(X){if(this.config=X,X.entityMappings)for(let $ of X.entityMappings)this.registerEntity($)}createTable(X){return{...X,billingMode:X.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(X){return{tableName:X}}registerEntity(X){this.entityMappings.set(X.entityType,X)}getEntityMapping(X){return this.entityMappings.get(X)}buildPrimaryKey(X,$){let Z=this.entityMappings.get(X);if(!Z)throw Error(`No entity mapping found for type: ${X}`);let Y=this.interpolatePattern(Z.pkPattern,$),U=this.interpolatePattern(Z.skPattern,$);return{pk:Y,sk:U}}parseEntityFromItem(X){let $=X.pk||X.PK;if(!$)return null;for(let[Z,Y]of this.entityMappings){let U=Y.pkPattern.split("${")[0];if($.startsWith(U))return{entityType:Z,data:this.unmarshall(X)}}return null}buildQueryParams(X){return{tableName:X.tableName??this.config.tableName??"",keyConditions:X.keyConditions??[],...X}}buildScanParams(X){return{tableName:X.tableName??this.config.tableName??"",...X}}buildGetItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},...X}}buildPutItemParams(X){return{tableName:X.tableName??this.config.tableName??"",item:X.item??{},...X}}buildUpdateItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},updateExpressions:X.updateExpressions??{},...X}}buildDeleteItemParams(X){return{tableName:X.tableName??this.config.tableName??"",key:X.key??{},...X}}buildBatchGetItemParams(X){return{requestItems:X.requestItems??{}}}buildBatchWriteItemParams(X){return{requestItems:X.requestItems??{}}}buildTransactWriteParams(X){return{transactItems:X.transactItems??[],...X}}buildKeyConditionExpression(X){return this.buildExpression(X,"AND")}buildFilterExpression(X){return this.buildExpression(X,"AND")}buildUpdateExpression(X){let $={},Z={},Y=[],U=0;if(X.set&&Object.keys(X.set).length>0){let _=[];for(let[Q,L]of Object.entries(X.set)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} = ${j}`),U++}Y.push(`SET ${_.join(", ")}`)}if(X.remove&&X.remove.length>0){let _=[];for(let Q of X.remove){let L=`#attr${U}`;$[L]=Q,_.push(L),U++}Y.push(`REMOVE ${_.join(", ")}`)}if(X.add&&Object.keys(X.add).length>0){let _=[];for(let[Q,L]of Object.entries(X.add)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} ${j}`),U++}Y.push(`ADD ${_.join(", ")}`)}if(X.delete&&Object.keys(X.delete).length>0){let _=[];for(let[Q,L]of Object.entries(X.delete)){let z=`#attr${U}`,j=`:val${U}`;$[z]=Q,Z[j]=this.marshallValue(L),_.push(`${z} ${j}`),U++}Y.push(`DELETE ${_.join(", ")}`)}return{expression:Y.join(" "),expressionAttributeNames:$,expressionAttributeValues:Z}}buildProjectionExpression(X){let $={},Z=[];return X.forEach((Y,U)=>{let _=`#proj${U}`;$[_]=Y,Z.push(_)}),{expression:Z.join(", "),expressionAttributeNames:$}}marshall(X){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.marshallValue(Y);return $}unmarshall(X){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.unmarshallValue(Y);return $}interpolatePattern(X,$){return X.replace(/\$\{(\w+)\}/g,(Z,Y)=>{if(!(Y in $))throw Error(`Missing value for pattern key: ${Y}`);return String($[Y])})}buildExpression(X,$){let Z={},Y={},U=[];return X.forEach((_,Q)=>{let L=`#attr${Q}`;Z[L]=_.attribute;let z;switch(_.operator){case"=":case"<":case"<=":case">":case">=":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`${L} ${_.operator} ${j}`;break}case"BETWEEN":{let j=`:val${Q}a`,E=`:val${Q}b`;Y[j]=this.marshallValue(_.values?.[0]),Y[E]=this.marshallValue(_.values?.[1]),z=`${L} BETWEEN ${j} AND ${E}`;break}case"begins_with":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`begins_with(${L}, ${j})`;break}case"contains":{let j=`:val${Q}`;Y[j]=this.marshallValue(_.value),z=`contains(${L}, ${j})`;break}case"attribute_exists":z=`attribute_exists(${L})`;break;case"attribute_not_exists":z=`attribute_not_exists(${L})`;break;case"attribute_type":{let j=`:val${Q}`;Y[j]={S:_.value},z=`attribute_type(${L}, ${j})`;break}case"IN":{let j=(_.values??[]).map((E,V)=>`:val${Q}_${V}`);_.values?.forEach((E,V)=>{Y[`:val${Q}_${V}`]=this.marshallValue(E)}),z=`${L} IN (${j.join(", ")})`;break}default:throw Error(`Unknown operator: ${_.operator}`)}U.push(z)}),{expression:U.join(` ${$} `),expressionAttributeNames:Z,expressionAttributeValues:Y}}marshallValue(X){if(X===null||X===void 0)return{NULL:!0};if(typeof X==="string")return{S:X};if(typeof X==="number")return{N:String(X)};if(typeof X==="boolean")return{BOOL:X};if(X instanceof Uint8Array||Buffer.isBuffer(X))return{B:X};if(Array.isArray(X)){if(X.length===0)return{L:[]};let $=typeof X[0],Z=X.every((U)=>typeof U==="string"),Y=X.every((U)=>typeof U==="number");if(Z)return{SS:X};if(Y)return{NS:X.map(String)};return{L:X.map((U)=>this.marshallValue(U))}}if(typeof X==="object"){let $={};for(let[Z,Y]of Object.entries(X))$[Z]=this.marshallValue(Y);return{M:$}}return{S:String(X)}}unmarshallValue(X){if(!X||typeof X!=="object")return X;if("S"in X)return X.S;if("N"in X)return Number(X.N);if("BOOL"in X)return X.BOOL;if("NULL"in X)return null;if("B"in X)return X.B;if("SS"in X)return X.SS;if("NS"in X)return X.NS.map(Number);if("BS"in X)return X.BS;if("L"in X)return X.L.map(($)=>this.unmarshallValue($));if("M"in X){let $={};for(let[Z,Y]of Object.entries(X.M))$[Z]=this.unmarshallValue(Y);return $}return X}}function bX(X){return new H6(X)}async function iX(X,$){let Z=X instanceof ArrayBuffer?X:X.buffer.slice(X.byteOffset,X.byteOffset+X.byteLength),Y=await crypto.subtle.importKey("raw",Z,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",Y,new TextEncoder().encode($))}async function R5(X){let $=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(X));return Array.from(new Uint8Array($)).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}async function s7(X,$,Z,Y){let U=await iX(new TextEncoder().encode(`AWS4${X}`),$),_=await iX(U,Z),Q=await iX(_,Y);return iX(Q,"aws4_request")}async function o7(X,$,Z,Y,U,_,Q){let z=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),j=z.slice(0,8),E=$.pathname,V=$.search.slice(1),G={...Z,host:$.host,"x-amz-date":z};if(U.sessionToken)G["x-amz-security-token"]=U.sessionToken;let J=Object.keys(G).sort(),W=J.map((y)=>`${y.toLowerCase()}:${G[y].trim()}`).join(`
3
3
  `)+`
4
- `,I=O.map((g)=>g.toLowerCase()).join(";"),C=await dZ(_),D=[$,U,V,K,I,C].join(`
5
- `),M=await dZ(D),J="AWS4-HMAC-SHA256",N=`${E}/${j}/${Y}/aws4_request`,T=[J,F,N,M].join(`
6
- `),v=await Z_(L.secretAccessKey,E,j,Y),b=await C8(v,T),f=Array.from(new Uint8Array(b)).map((g)=>g.toString(16).padStart(2,"0")).join(""),p=`${J} Credential=${L.accessKeyId}/${N}, SignedHeaders=${I}, Signature=${f}`;return{...Q,authorization:p}}class i7{config;endpoint;credentials;constructor($){if(this.config=$,this.endpoint=$.endpoint??`https://dynamodb.${$.region}.amazonaws.com`,this.credentials=$.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute($,Z){let X=new URL(this.endpoint),_=JSON.stringify(Z),L={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${$}`},j=await X_("POST",X,L,_,this.credentials,this.config.region,"dynamodb"),Y=await fetch(X.toString(),{method:"POST",headers:j,body:_});if(!Y.ok){let z=await Y.text(),F;try{let E=JSON.parse(z);F=E.message??E.Message??z}catch{F=z}throw Error(`DynamoDB ${$} failed: ${Y.status} - ${F}`)}return Y.json()}async query($){return this.execute("Query",$)}async scan($){return this.execute("Scan",$)}async getItem($){return this.execute("GetItem",$)}async putItem($){return this.execute("PutItem",$)}async updateItem($){return this.execute("UpdateItem",$)}async deleteItem($){return this.execute("DeleteItem",$)}async batchGetItem($){return this.execute("BatchGetItem",$)}async batchWriteItem($){return this.execute("BatchWriteItem",$)}async transactWriteItems($){return this.execute("TransactWriteItems",$)}async describeTable($){return this.execute("DescribeTable",{TableName:$})}async createTable($){return this.execute("CreateTable",$)}async deleteTable($){return this.execute("DeleteTable",{TableName:$})}async listTables($){return this.execute("ListTables",$??{})}async updateTable($){return this.execute("UpdateTable",$)}async updateTimeToLive($){return this.execute("UpdateTimeToLive",$)}async describeTimeToLive($){return this.execute("DescribeTimeToLive",{TableName:$})}}function l7($){return new i7($)}function Mz($){C9={...C9,...$},d1=null,c1=null}function A9(){if(!d1)d1=l7({region:C9.region??"us-east-1",endpoint:C9.endpoint,credentials:C9.credentials});return d1}function v9(){if(!c1)c1=V8({region:C9.region??"us-east-1",endpoint:C9.endpoint,credentials:C9.credentials});return c1}class __{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor($={}){this._attributes={...$},this._original={...$};for(let[Z,X]of Object.entries($))this[Z]=X}static query(){return new s7(this)}static async find($){let Z=this,X=A9(),_=v9(),L=`${Z.pkPrefix}${Z.keyDelimiter}${$}`,j=Z.skPrefix;try{let Y=await X.getItem({TableName:Z.tableName,Key:_.marshall({[Z.pkAttribute]:L,[Z.skAttribute]:j})});if(!Y.Item)return null;let z=_.unmarshall(Y.Item),F=new Z(z);return F._exists=!0,F}catch(Y){return console.error("Find error:",Y),null}}static async findOrFail($){let Z=await this.find($);if(!Z)throw Error(`${this.name} not found with id: ${$}`);return Z}static async all(){return this.query().get()}static async create($){let Z=this,X=A9(),_=v9(),L=$[Z.primaryKey];if(!L)throw Error(`${Z.primaryKey} is required`);let j=`${Z.pkPrefix}${Z.keyDelimiter}${L}`,Y=Z.skPrefix,z=new Date().toISOString(),F={...$,[Z.pkAttribute]:j,[Z.skAttribute]:Y,[Z.entityTypeAttribute]:Z.name};if(Z.timestamps)F[Z.createdAtField]=z,F[Z.updatedAtField]=z;await X.putItem({TableName:Z.tableName,Item:_.marshall(F),ConditionExpression:`attribute_not_exists(${Z.pkAttribute})`});let E=new Z(F);return E._exists=!0,E}static async updateOrCreate($,Z){let X=this,_=$[X.primaryKey],L=await X.find(_);if(L)return await L.update(Z),L;return X.create({...$,...Z})}static where($,Z,X){return this.query().where($,Z,X)}static wherePk($){return this.query().wherePk($)}getKey(){let $=this.constructor;return this[$.primaryKey]}getAttribute($){return this._attributes[$]}setAttribute($,Z){return this._attributes[$]=Z,this[$]=Z,this}getAttributes(){return{...this._attributes}}isDirty($){if($)return this._attributes[$]!==this._original[$];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let $={};for(let[Z,X]of Object.entries(this._attributes))if(X!==this._original[Z])$[Z]=X;return $}async save(){if(this._exists){let $=this.getDirty();if(Object.keys($).length>0)await this.update($)}else{let Z=await this.constructor.create(this._attributes);this._attributes=Z._attributes,this._original={...this._attributes},this._exists=!0}return this}async update($){let Z=this.constructor,X=A9(),_=v9(),L=this.getKey(),j=`${Z.pkPrefix}${Z.keyDelimiter}${L}`,Y=Z.skPrefix,z=new Date().toISOString(),F={...$};if(Z.timestamps)F[Z.updatedAtField]=z;let E=[],U={},V={},Q=0;for(let[O,K]of Object.entries(F)){let I=`#attr${Q}`,C=`:val${Q}`;U[I]=O,V[C]=_.marshall({v:K}).v,E.push(`${I} = ${C}`),Q++}await X.updateItem({TableName:Z.tableName,Key:_.marshall({[Z.pkAttribute]:j,[Z.skAttribute]:Y}),UpdateExpression:`SET ${E.join(", ")}`,ExpressionAttributeNames:U,ExpressionAttributeValues:V});for(let[O,K]of Object.entries(F))this._attributes[O]=K,this[O]=K;return this._original={...this._attributes},this}async delete(){let $=this.constructor,Z=A9(),X=v9(),_=this.getKey(),L=`${$.pkPrefix}${$.keyDelimiter}${_}`,j=$.skPrefix;return await Z.deleteItem({TableName:$.tableName,Key:X.marshall({[$.pkAttribute]:L,[$.skAttribute]:j})}),this._exists=!1,!0}async refresh(){let Z=await this.constructor.find(this.getKey());if(Z){this._attributes=Z._attributes,this._original={...this._attributes};for(let[X,_]of Object.entries(this._attributes))this[X]=_}return this}toObject(){let $=this.constructor,Z={...this._attributes};return delete Z[$.pkAttribute],delete Z[$.skAttribute],delete Z[$.entityTypeAttribute],Z}toJSON(){return this.toObject()}}class s7{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor($){this.ModelClass=$}wherePk($){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${$}`,this}where($,Z,X){if(X===void 0)this._filterConditions.push({attribute:$,operator:"=",value:Z});else this._filterConditions.push({attribute:$,operator:Z,value:X});return this}whereIn($,Z){return this._filterConditions.push({attribute:$,operator:"IN",values:Z}),this}whereBetween($,Z,X){return this._filterConditions.push({attribute:$,operator:"BETWEEN",value:Z,values:[Z,X]}),this}whereBeginsWith($,Z){return this._filterConditions.push({attribute:$,operator:"begins_with",value:Z}),this}whereExists($){return this._filterConditions.push({attribute:$,operator:"attribute_exists"}),this}whereNotExists($){return this._filterConditions.push({attribute:$,operator:"attribute_not_exists"}),this}orderBy($){return this._scanForward=$==="asc",this}limit($){return this._limitValue=$,this}select(...$){return this._projectionAttrs.push(...$),this}index($){return this._indexName=$,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom($){return this._startKey=$,this}buildRequest(){let $=v9(),Z={TableName:this.ModelClass.tableName};if(this._indexName)Z.IndexName=this._indexName;let X={},_={},L=0,j=[];if(this._pkValue){let Y=`#pk${L}`,z=`:pk${L}`;X[Y]=this.ModelClass.pkAttribute,_[z]={S:this._pkValue},j.push(`${Y} = ${z}`),L++}if(this._skCondition){let Y=`#sk${L}`;switch(X[Y]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let z=`:sk${L}`;_[z]={S:this._skCondition.value},j.push(`${Y} = ${z}`);break}case"begins_with":{let z=`:sk${L}`;_[z]={S:this._skCondition.value},j.push(`begins_with(${Y}, ${z})`);break}}L++}if(j.length>0)Z.KeyConditionExpression=j.join(" AND ");if(this._filterConditions.length>0){let Y=[];for(let z of this._filterConditions){let F=`#flt${L}`;if(X[F]=z.attribute,z.operator==="attribute_exists")Y.push(`attribute_exists(${F})`);else if(z.operator==="attribute_not_exists")Y.push(`attribute_not_exists(${F})`);else if(z.operator==="IN"&&z.values){let E=z.values.map((U,V)=>`:flt${L}_${V}`);z.values.forEach((U,V)=>{_[`:flt${L}_${V}`]=$.marshall({v:U}).v}),Y.push(`${F} IN (${E.join(", ")})`)}else if(z.operator==="BETWEEN"&&z.values){let E=`:flt${L}a`,U=`:flt${L}b`;_[E]=$.marshall({v:z.values[0]}).v,_[U]=$.marshall({v:z.values[1]}).v,Y.push(`${F} BETWEEN ${E} AND ${U}`)}else if(z.operator==="begins_with"){let E=`:flt${L}`;_[E]=$.marshall({v:z.value}).v,Y.push(`begins_with(${F}, ${E})`)}else{let E=`:flt${L}`;_[E]=$.marshall({v:z.value}).v,Y.push(`${F} ${z.operator} ${E}`)}L++}Z.FilterExpression=Y.join(" AND ")}if(this._projectionAttrs.length>0){let Y=[];for(let z of this._projectionAttrs){let F=`#proj${L}`;X[F]=z,Y.push(F),L++}Z.ProjectionExpression=Y.join(", ")}if(Object.keys(X).length>0)Z.ExpressionAttributeNames=X;if(Object.keys(_).length>0)Z.ExpressionAttributeValues=_;if(this._limitValue!==void 0)Z.Limit=this._limitValue;if(Z.ScanIndexForward=this._scanForward,this._consistentReadValue)Z.ConsistentRead=!0;if(this._startKey)Z.ExclusiveStartKey=$.marshall(this._startKey);return Z}async get(){let $=A9(),Z=v9(),X=this.buildRequest();return((this._pkValue!==void 0?await $.query(X):await $.scan(X)).Items??[]).map((Y)=>{let z=Z.unmarshall(Y),F=new this.ModelClass(z);return F._exists=!0,F})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let $=A9(),Z=this.buildRequest();return Z.Select="COUNT",(this._pkValue!==void 0?await $.query(Z):await $.scan(Z)).Count??0}async paginate($,Z){let X=v9();if(Z)this._startKey=Z;this._limitValue=$;let _=A9(),L=this.buildRequest(),Y=this._pkValue!==void 0?await _.query(L):await _.scan(L);return{items:(Y.Items??[]).map((F)=>{let E=X.unmarshall(F),U=new this.ModelClass(E);return U._exists=!0,U}),lastKey:Y.LastEvaluatedKey?X.unmarshall(Y.LastEvaluatedKey):void 0}}}var C9,d1=null,c1=null,L_=n(()=>{C9={region:process.env.AWS_REGION??"us-east-1"}});function F$($){let Z=JSON.stringify({tableName:$.tableName,keySchema:$.keySchema,attributeDefinitions:[...$.attributeDefinitions||[]].sort((_,L)=>_.name.localeCompare(L.name)),globalSecondaryIndexes:[...$.globalSecondaryIndexes||[]].sort((_,L)=>_.indexName.localeCompare(L.indexName)),localSecondaryIndexes:[...$.localSecondaryIndexes||[]].sort((_,L)=>_.indexName.localeCompare(L.indexName)),billingMode:$.billingMode,ttlAttribute:$.ttlAttribute,streamSpecification:$.streamSpecification}),X=0;for(let _=0;_<Z.length;_++){let L=Z.charCodeAt(_);X=(X<<5)-X+L,X=X&X}return Math.abs(X).toString(16).padStart(8,"0")}function j_($){let Z=Y_($);return F_(Z)}function Y_($){return{tableName:$.tableName||"",pkAttribute:$.pkAttribute||"pk",skAttribute:$.skAttribute||"sk",pkPrefix:$.pkPrefix||"",skPrefix:$.skPrefix||"METADATA",entityTypeAttribute:$.entityTypeAttribute||"_et",timestamps:$.timestamps!==!1,ttlAttribute:$.ttlAttribute,gsis:$.gsis,lsis:$.lsis,billingMode:$.billingMode||"PAY_PER_REQUEST",provisionedThroughput:$.provisionedThroughput,streamEnabled:$.streamEnabled,streamViewType:$.streamViewType}}function F_($){let Z=[{name:$.pkAttribute,type:"S"},{name:$.skAttribute,type:"S"}],X=[];if($.gsis)for(let _ of $.gsis){if(!Z.some((L)=>L.name===_.pkAttribute))Z.push({name:_.pkAttribute,type:"S"});if(_.skAttribute&&!Z.some((L)=>L.name===_.skAttribute))Z.push({name:_.skAttribute,type:"S"});X.push({indexName:_.indexName,keySchema:{partitionKey:_.pkAttribute,sortKey:_.skAttribute},projection:{type:Array.isArray(_.projection)?"INCLUDE":_.projection||"ALL",nonKeyAttributes:Array.isArray(_.projection)?_.projection:void 0},provisionedThroughput:_.provisionedThroughput})}return{tableName:$.tableName,keySchema:{partitionKey:$.pkAttribute,sortKey:$.skAttribute},attributeDefinitions:Z,globalSecondaryIndexes:X.length>0?X:void 0,billingMode:$.billingMode,provisionedThroughput:$.provisionedThroughput,ttlAttribute:$.ttlAttribute,streamSpecification:$.streamEnabled?{enabled:!0,viewType:$.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function z_($,Z){let X=[],_=Z.tableName;if(!$)X.push({type:"CREATE_TABLE",tableName:_,details:{definition:Z}});else{let L=$.keySchema.partitionKey!==Z.keySchema.partitionKey,j=$.keySchema.sortKey!==Z.keySchema.sortKey;if(L||j)console.warn(`[Migration] Table ${_}: Key schema changes require table recreation. Current: pk=${$.keySchema.partitionKey}, sk=${$.keySchema.sortKey}. Target: pk=${Z.keySchema.partitionKey}, sk=${Z.keySchema.sortKey}. This operation is not supported automatically.`);let Y=$.globalSecondaryIndexes||[],z=Z.globalSecondaryIndexes||[],F=new Set(Y.map((Q)=>Q.indexName)),E=new Set(z.map((Q)=>Q.indexName));for(let Q of z)if(!F.has(Q.indexName))X.push({type:"ADD_GSI",tableName:_,details:{gsi:Q}});for(let Q of Y)if(!E.has(Q.indexName))X.push({type:"DELETE_GSI",tableName:_,details:{indexName:Q.indexName}});if($.billingMode!==Z.billingMode&&Z.billingMode)X.push({type:"UPDATE_BILLING_MODE",tableName:_,details:{billingMode:Z.billingMode,provisionedThroughput:Z.provisionedThroughput}});if($.ttlAttribute!==Z.ttlAttribute)X.push({type:"UPDATE_TTL",tableName:_,details:{ttlAttribute:Z.ttlAttribute||null,enabled:!!Z.ttlAttribute}});let U=$.streamSpecification?.enabled,V=Z.streamSpecification?.enabled;if(U!==V)if(V)X.push({type:"ENABLE_STREAM",tableName:_,details:{viewType:Z.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else X.push({type:"DISABLE_STREAM",tableName:_,details:{}})}return{tableName:_,operations:X,timestamp:new Date().toISOString(),hash:F$(Z)}}function Rz($,Z){return F$($)===F$(Z)}class o7{client;initialized=!1;constructor($){this.client=$}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(E9),this.initialized=!0}catch($){if($.message?.includes("ResourceNotFoundException")||$.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${E9}`),await this.client.createTable({TableName:E9,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(E9),this.initialized=!0;else throw $}}async waitForTableActive($,Z=30){for(let X=0;X<Z;X++){try{if((await this.client.describeTable($)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((_)=>setTimeout(_,1000))}throw Error(`Table ${$} did not become active within ${Z} seconds`)}async getLatestState($){await this.ensureMigrationsTable();let Z=`${M8}#${$}`,X=await this.client.query({TableName:E9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:Z}},ScanIndexForward:!1,Limit:1});if(!X.Items||X.Items.length===0)return null;return this.unmarshallState(X.Items[0])}async getHistory($){await this.ensureMigrationsTable();let Z=`${M8}#${$}`,X=await this.client.query({TableName:E9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:Z}},ScanIndexForward:!1});if(!X.Items)return[];return X.Items.map((_)=>this.unmarshallState(_))}async recordMigration($,Z,X){await this.ensureMigrationsTable();let _=await this.getLatestState($),L=X??(_?_.version+1:1),j=`${M8}#${$}`,Y=`${cZ}#${String(L).padStart(6,"0")}`,z={tableName:$,hash:F$(Z),definition:Z,appliedAt:new Date().toISOString(),version:L};return await this.client.putItem({TableName:E9,Item:this.marshallState(z,j,Y)}),console.log(`[Migration] Recorded migration for ${$} (version ${L})`),z}async listTrackedTables(){await this.ensureMigrationsTable();let $=await this.client.scan({TableName:E9,ProjectionExpression:"pk"});if(!$.Items)return[];let Z=new Set;for(let X of $.Items){let L=(X.pk?.S||"").replace(`${M8}#`,"");if(L)Z.add(L)}return Array.from(Z)}async hasMigrations($){return await this.getLatestState($)!==null}async deleteMigrationHistory($){await this.ensureMigrationsTable();let Z=await this.getHistory($),X=`${M8}#${$}`;for(let _ of Z){let L=`${cZ}#${String(_.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:E9,Key:{pk:{S:X},sk:{S:L}}})}console.log(`[Migration] Deleted migration history for ${$}`)}marshallState($,Z,X){return{pk:{S:Z},sk:{S:X},tableName:{S:$.tableName},hash:{S:$.hash},definition:{S:JSON.stringify($.definition)},appliedAt:{S:$.appliedAt},version:{N:String($.version)}}}unmarshallState($){return{tableName:$.tableName?.S||"",hash:$.hash?.S||"",definition:JSON.parse($.definition?.S||"{}"),appliedAt:$.appliedAt?.S||"",version:Number($.version?.N||0)}}}var E9="_qb_migrations",M8="MIGRATION",cZ="VERSION",r7=()=>{};class t7{client;tracker;config;constructor($){this.config=$,this.client=l7({region:$.region,endpoint:$.endpoint,credentials:$.credentials}),this.tracker=new o7(this.client)}async execute($){let Z={tableName:$.tableName,success:!0,operations:[]};if($.operations.length===0)return this.log(`[Migration] No changes needed for ${$.tableName}`),Z;this.log(`[Migration] Executing ${$.operations.length} operations for ${$.tableName}`);try{for(let X of $.operations)await this.executeOperation(X),Z.operations.push(X.type);this.log(`[Migration] Successfully applied ${Z.operations.length} operations to ${$.tableName}`)}catch(X){Z.success=!1,Z.error=X.message,console.error(`[Migration] Failed to execute migration for ${$.tableName}:`,X)}return Z}async executeOperation($){if(this.log(`[Migration] Executing ${$.type} on ${$.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${$.type}`,$.details);return}switch($.type){case"CREATE_TABLE":await this.createTable($.details.definition);break;case"DELETE_TABLE":await this.deleteTable($.tableName);break;case"ADD_GSI":await this.addGSI($.tableName,$.details.gsi);break;case"DELETE_GSI":await this.deleteGSI($.tableName,$.details.indexName);break;case"UPDATE_TTL":await this.updateTTL($.tableName,$.details.ttlAttribute,$.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode($.tableName,$.details.billingMode,$.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream($.tableName,$.details.viewType);break;case"DISABLE_STREAM":await this.disableStream($.tableName);break;default:throw Error(`Unknown migration operation type: ${$.type}`)}}async createTable($){let Z={TableName:$.tableName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:$.attributeDefinitions.map((X)=>({AttributeName:X.name,AttributeType:X.type})),BillingMode:$.billingMode||"PAY_PER_REQUEST"};if($.keySchema.sortKey)Z.KeySchema.push({AttributeName:$.keySchema.sortKey,KeyType:"RANGE"});if($.billingMode==="PROVISIONED"&&$.provisionedThroughput)Z.ProvisionedThroughput={ReadCapacityUnits:$.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:$.provisionedThroughput.writeCapacityUnits};if($.globalSecondaryIndexes&&$.globalSecondaryIndexes.length>0)Z.GlobalSecondaryIndexes=$.globalSecondaryIndexes.map((X)=>({IndexName:X.indexName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"},...X.keySchema.sortKey?[{AttributeName:X.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:X.projection.type,...X.projection.nonKeyAttributes?{NonKeyAttributes:X.projection.nonKeyAttributes}:{}},...X.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:X.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:X.provisionedThroughput.writeCapacityUnits}}:{}}));if($.localSecondaryIndexes&&$.localSecondaryIndexes.length>0)Z.LocalSecondaryIndexes=$.localSecondaryIndexes.map((X)=>({IndexName:X.indexName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:X.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:X.projection.type,...X.projection.nonKeyAttributes?{NonKeyAttributes:X.projection.nonKeyAttributes}:{}}}));if($.streamSpecification?.enabled)Z.StreamSpecification={StreamEnabled:!0,StreamViewType:$.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${$.tableName}`),await this.client.createTable(Z),await this.waitForTableActive($.tableName),$.ttlAttribute)await this.updateTTL($.tableName,$.ttlAttribute,!0);this.log(`[Migration] Table created: ${$.tableName}`)}async deleteTable($){this.log(`[Migration] Deleting table: ${$}`),await this.client.deleteTable($),this.log(`[Migration] Table deleted: ${$}`)}async addGSI($,Z){this.log(`[Migration] Adding GSI ${Z.indexName} to ${$}`);let X=await this.client.describeTable($),_=new Set(X.Table?.AttributeDefinitions?.map((Y)=>Y.AttributeName)||[]),L=[];if(!_.has(Z.keySchema.partitionKey))L.push({AttributeName:Z.keySchema.partitionKey,AttributeType:"S"});if(Z.keySchema.sortKey&&!_.has(Z.keySchema.sortKey))L.push({AttributeName:Z.keySchema.sortKey,AttributeType:"S"});let j={TableName:$,AttributeDefinitions:L.length>0?L:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:Z.indexName,KeySchema:[{AttributeName:Z.keySchema.partitionKey,KeyType:"HASH"},...Z.keySchema.sortKey?[{AttributeName:Z.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}},...Z.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:Z.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:Z.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(j),await this.waitForGSIActive($,Z.indexName),this.log(`[Migration] GSI ${Z.indexName} added to ${$}`)}async deleteGSI($,Z){this.log(`[Migration] Deleting GSI ${Z} from ${$}`);let X={TableName:$,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:Z}}]};await this.executeUpdateTable(X),this.log(`[Migration] GSI ${Z} deleted from ${$}`)}async updateTTL($,Z,X){this.log(`[Migration] Updating TTL on ${$}: ${X?Z:"disabled"}`);let _={TableName:$,TimeToLiveSpecification:{Enabled:X,AttributeName:Z||"ttl"}};await this.executeUpdateTimeToLive(_),this.log(`[Migration] TTL updated on ${$}`)}async updateBillingMode($,Z,X){this.log(`[Migration] Updating billing mode on ${$} to ${Z}`);let _={TableName:$,BillingMode:Z};if(Z==="PROVISIONED"&&X)_.ProvisionedThroughput={ReadCapacityUnits:X.readCapacityUnits,WriteCapacityUnits:X.writeCapacityUnits};await this.executeUpdateTable(_),await this.waitForTableActive($),this.log(`[Migration] Billing mode updated on ${$}`)}async enableStream($,Z){this.log(`[Migration] Enabling stream on ${$} with view type ${Z}`);let X={TableName:$,StreamSpecification:{StreamEnabled:!0,StreamViewType:Z}};await this.executeUpdateTable(X),await this.waitForTableActive($),this.log(`[Migration] Stream enabled on ${$}`)}async disableStream($){this.log(`[Migration] Disabling stream on ${$}`);let Z={TableName:$,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(Z),await this.waitForTableActive($),this.log(`[Migration] Stream disabled on ${$}`)}async executeUpdateTable($){await this.client.updateTable($)}async executeUpdateTimeToLive($){await this.client.updateTimeToLive($)}async waitForTableActive($,Z=60){this.log(`[Migration] Waiting for table ${$} to become active...`);for(let X=0;X<Z;X++){try{let L=(await this.client.describeTable($)).Table?.TableStatus;if(L==="ACTIVE")return;this.log(`[Migration] Table status: ${L}, waiting...`)}catch{}await new Promise((_)=>setTimeout(_,2000))}throw Error(`Table ${$} did not become active within ${Z*2} seconds`)}async waitForGSIActive($,Z,X=120){this.log(`[Migration] Waiting for GSI ${Z} to become active...`);for(let _=0;_<X;_++){try{let j=(await this.client.describeTable($)).Table?.GlobalSecondaryIndexes?.find((z)=>z.IndexName===Z);if(j?.IndexStatus==="ACTIVE")return;let Y=j?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${Y}, waiting...`)}catch{}await new Promise((L)=>setTimeout(L,5000))}throw Error(`GSI ${Z} did not become active within ${X*5} seconds`)}async migrateModel($){let Z=j_($),X=null;try{let j=await this.client.describeTable(Z.tableName);if(j.Table)X=this.tableInfoToDefinition(j.Table)}catch(j){if(!j.message?.includes("ResourceNotFoundException")&&!j.message?.includes("not found"))throw j}let _=z_(X,Z),L=await this.execute(_);if(L.success&&!this.config.dryRun)L.state=await this.tracker.recordMigration(Z.tableName,Z);return L}async migrateModels($){let Z=[];for(let X of $)try{let _=await this.migrateModel(X);Z.push(_)}catch(_){Z.push({tableName:X.tableName||"unknown",success:!1,operations:[],error:_.message})}return Z}async getStatus(){let $=new Map,Z=await this.tracker.listTrackedTables();for(let X of Z){let _=await this.tracker.getLatestState(X);$.set(X,_)}return $}tableInfoToDefinition($){let Z={partitionKey:"",sortKey:void 0};for(let L of $.KeySchema||[])if(L.KeyType==="HASH")Z.partitionKey=L.AttributeName;else if(L.KeyType==="RANGE")Z.sortKey=L.AttributeName;let X=($.AttributeDefinitions||[]).map((L)=>({name:L.AttributeName,type:L.AttributeType})),_=($.GlobalSecondaryIndexes||[]).map((L)=>{let j={partitionKey:"",sortKey:void 0};for(let Y of L.KeySchema||[])if(Y.KeyType==="HASH")j.partitionKey=Y.AttributeName;else if(Y.KeyType==="RANGE")j.sortKey=Y.AttributeName;return{indexName:L.IndexName,keySchema:j,projection:{type:L.Projection?.ProjectionType||"ALL",nonKeyAttributes:L.Projection?.NonKeyAttributes},provisionedThroughput:L.ProvisionedThroughput?{readCapacityUnits:L.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:L.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:$.TableName,keySchema:Z,attributeDefinitions:X,globalSecondaryIndexes:_.length>0?_:void 0,billingMode:$.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:$.ProvisionedThroughput?{readCapacityUnits:$.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:$.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:$.TimeToLiveDescription?.AttributeName,streamSpecification:$.StreamSpecification?{enabled:$.StreamSpecification.StreamEnabled,viewType:$.StreamSpecification.StreamViewType}:void 0}}log(...$){if(this.config.verbose||this.config.dryRun)console.log(...$)}}function U_($){return new t7($)}async function Jz($,Z){return U_(Z).migrateModels($)}var E_=n(()=>{r7()});class a7{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor($,Z,X,_){this.driver=$,this.client=Z,this.tableName=X,this.pkAttribute=_.pkAttribute,this.skAttribute=_.skAttribute,this.entityTypeAttr=_.entityTypeAttribute,this.delimiter=_.keyDelimiter}entity($){return this._entityType=$,this}pk($){return this._pkValue=$,this}get sk(){let $=this;return{equals(Z){return $._skCondition={type:"eq",value:Z},$},beginsWith(Z){return $._skCondition={type:"begins_with",value:Z},$},between(Z,X){return $._skCondition={type:"between",value:Z,value2:X},$},lt(Z){return $._skCondition={type:"lt",value:Z},$},lte(Z){return $._skCondition={type:"lte",value:Z},$},gt(Z){return $._skCondition={type:"gt",value:Z},$},gte(Z){return $._skCondition={type:"gte",value:Z},$}}}index($){return this._indexName=$,this}project(...$){return this._projectionAttrs.push(...$),this}filter($,Z,X){return this._filterConditions.push({attribute:$,operator:Z,value:X}),this}where($,Z){return this.filter($,"=",Z)}whereIn($,Z){return this._filterConditions.push({attribute:$,operator:"IN",values:Z}),this}limit($){return this._limitValue=$,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom($){return this._startKey=$,this}toRequest(){let $={TableName:this.tableName};if(this._indexName)$.IndexName=this._indexName;let Z=[],X={},_={},L=0;if(this._pkValue){let j=`#pk${L}`,Y=`:pk${L}`;X[j]=this.pkAttribute,_[Y]={S:this._pkValue},Z.push(`${j} = ${Y}`),L++}if(this._skCondition){let j=`#sk${L}`;switch(X[j]=this.skAttribute,this._skCondition.type){case"eq":{let Y=`:sk${L}`;_[Y]={S:this._skCondition.value},Z.push(`${j} = ${Y}`);break}case"begins_with":{let Y=`:sk${L}`;_[Y]={S:this._skCondition.value},Z.push(`begins_with(${j}, ${Y})`);break}case"between":{let Y=`:sk${L}a`,z=`:sk${L}b`;_[Y]={S:this._skCondition.value},_[z]={S:this._skCondition.value2},Z.push(`${j} BETWEEN ${Y} AND ${z}`);break}case"lt":{let Y=`:sk${L}`;_[Y]={S:this._skCondition.value},Z.push(`${j} < ${Y}`);break}case"lte":{let Y=`:sk${L}`;_[Y]={S:this._skCondition.value},Z.push(`${j} <= ${Y}`);break}case"gt":{let Y=`:sk${L}`;_[Y]={S:this._skCondition.value},Z.push(`${j} > ${Y}`);break}case"gte":{let Y=`:sk${L}`;_[Y]={S:this._skCondition.value},Z.push(`${j} >= ${Y}`);break}}L++}if(Z.length>0)$.KeyConditionExpression=Z.join(" AND ");if(this._filterConditions.length>0){let j=[];for(let Y of this._filterConditions){let z=`#flt${L}`;if(X[z]=Y.attribute,Y.operator==="IN"&&Y.values){let F=Y.values.map((E,U)=>`:flt${L}_${U}`);Y.values.forEach((E,U)=>{_[`:flt${L}_${U}`]=this.driver.marshall({v:E}).v}),j.push(`${z} IN (${F.join(", ")})`)}else{let F=`:flt${L}`;_[F]=this.driver.marshall({v:Y.value}).v,j.push(`${z} ${Y.operator} ${F}`)}L++}$.FilterExpression=j.join(" AND ")}if(this._projectionAttrs.length>0){let j=[];for(let Y of this._projectionAttrs){let z=`#proj${L}`;X[z]=Y,j.push(z),L++}$.ProjectionExpression=j.join(", ")}if(Object.keys(X).length>0)$.ExpressionAttributeNames=X;if(Object.keys(_).length>0)$.ExpressionAttributeValues=_;if(this._limitValue!==void 0)$.Limit=this._limitValue;if($.ScanIndexForward=this._scanForward,this._consistentRead)$.ConsistentRead=!0;if(this._startKey)$.ExclusiveStartKey=this.driver.marshall(this._startKey);return $}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let $=this.toRequest();return((this._pkValue!==void 0?await this.client.query($):await this.client.scan($)).Items??[]).map((_)=>this.driver.unmarshall(_))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let $=[],Z;do{if(Z)this._startKey=Z;let X=this.toRequest(),L=this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X),j=(L.Items??[]).map((Y)=>this.driver.unmarshall(Y));$.push(...j),Z=L.LastEvaluatedKey?this.driver.unmarshall(L.LastEvaluatedKey):void 0}while(Z);return $}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let $=this.toRequest();return $.Select="COUNT",(this._pkValue!==void 0?await this.client.query($):await this.client.scan($)).Count??0}}class WZ{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection($){let Z={region:$.region,tableName:$.table,endpoint:$.endpoint,credentials:$.credentials};return this.driver=V8(Z),this.tableName=$.table,this.pkAttribute=$.pkAttribute??"pk",this.skAttribute=$.skAttribute??"sk",this.entityTypeAttr=$.entityTypeAttribute??"_et",this.delimiter=$.keyDelimiter??"#",this}setClient($){return this.client=$,this}registerEntity($){if(this.entityMappings.set($.entityType,$),this.driver)this.driver.registerEntity($);return this}entity($){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new a7(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity($)}async batchWrite($){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let Z=[];for(let X of $)if(X.put){let _={...X.put.item,[this.entityTypeAttr]:X.put.entity};Z.push({PutRequest:{Item:this.driver.marshall(_)}})}else if(X.delete)Z.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:X.delete.pk,[this.skAttribute]:X.delete.sk})}});if(Z.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:Z}})}async transactWrite($){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let Z=[];for(let X of $)if(X.put){let _={...X.put.item,[this.entityTypeAttr]:X.put.entity},L={Put:{TableName:this.tableName,Item:this.driver.marshall(_)}};if(X.put.condition)L.Put.ConditionExpression=X.put.condition;Z.push(L)}else if(X.update){let _={[this.pkAttribute]:X.update.pk};if(X.update.sk)_[this.skAttribute]=X.update.sk;let L=[],j={},Y={},z=0;if(X.update.set){let F=[];for(let[E,U]of Object.entries(X.update.set)){let V=`#set${z}`,Q=`:set${z}`;j[V]=E,Y[Q]=this.driver.marshall({v:U}).v,F.push(`${V} = ${Q}`),z++}if(F.length>0)L.push(`SET ${F.join(", ")}`)}if(X.update.add){let F=[];for(let[E,U]of Object.entries(X.update.add)){let V=`#add${z}`,Q=`:add${z}`;j[V]=E,Y[Q]={N:String(U)},F.push(`${V} ${Q}`),z++}if(F.length>0)L.push(`ADD ${F.join(", ")}`)}if(X.update.remove&&X.update.remove.length>0){let F=[];for(let E of X.update.remove){let U=`#rem${z}`;j[U]=E,F.push(U),z++}L.push(`REMOVE ${F.join(", ")}`)}Z.push({Update:{TableName:this.tableName,Key:this.driver.marshall(_),UpdateExpression:L.join(" "),ExpressionAttributeNames:j,ExpressionAttributeValues:Y}})}else if(X.delete){let _={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:X.delete.pk,[this.skAttribute]:X.delete.sk})}};if(X.delete.condition)_.Delete.ConditionExpression=X.delete.condition;Z.push(_)}else if(X.conditionCheck)Z.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:X.conditionCheck.pk,[this.skAttribute]:X.conditionCheck.sk}),ConditionExpression:X.conditionCheck.condition}});if(Z.length>0)await this.client.transactWriteItems({TransactItems:Z})}getDriver(){return this.driver}}function Cz(){return new WZ}var O_,Q_=n(()=>{L_(),E_(),r7(),O_=new WZ});class Z2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let X=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${X}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,X],[,_])=>X.timestamp.getTime()-_.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let X=0;X<Z;X++)this.cache.delete($[X][0])}set($,Z,X,_){if(!this.options.enabled)return;let L=this.generateKey($,X),j=_??this.options.ttl,Y=this.estimateSize(Z);this.cache.set(L,{value:Z,timestamp:new Date,ttl:j,hits:0,size:Y}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey($,Z),_=this.cache.get(X);if(!_){this.totalMisses++;return}if(this.isExpired(_)){this.cache.delete(X),this.totalMisses++;return}return _.hits++,this.totalHits++,_.value}isFileModified($,Z){try{if(!mZ($))return!0;return uZ($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let X=this.get($,Z);if(!X)return;if(this.isFileModified(Z,X.fileTimestamp)){this.delete($,Z);return}return X.value}setWithFileCheck($,Z,X,_){try{let L=mZ(X)?uZ(X):null,j=L?L.mtime:new Date;this.set($,{value:Z,fileTimestamp:j},X,_)}catch{this.set($,Z,X,_)}}delete($,Z){let X=this.generateKey($,Z);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((_,L)=>_+L.size,0),X=$.map((_)=>_.timestamp).sort();return{size:Z,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:X[0],newestEntry:X[X.length-1]}}export(){let $={};for(let[Z,X]of this.cache.entries())$[Z]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return $}import($){this.cache.clear();for(let[Z,X]of Object.entries($))if(typeof X==="object"&&X!==null){let _=X;this.cache.set(Z,{value:_.value,timestamp:new Date(_.timestamp),ttl:_.ttl,hits:_.hits,size:_.size})}}}class X2{metrics=[];maxMetrics=1000;async track($,Z,X={}){let _=performance.now(),L=new Date;try{let j=await Z(),Y=performance.now()-_;return this.recordMetric({operation:$,duration:Y,timestamp:L,...X}),j}catch(j){let Y=performance.now()-_;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:L,...X}),j}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((L)=>L.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=Z.map((L)=>L.duration),_=X.reduce((L,j)=>L+j,0);return{count:Z.length,averageDuration:_/Z.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:_,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function $4($,Z){this[$]=v4.bind(null,Z)}class n5{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let X=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${X}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,X],[,_])=>X.timestamp.getTime()-_.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let X=0;X<Z;X++)this.cache.delete($[X][0])}set($,Z,X,_){if(!this.options.enabled)return;let L=this.generateKey($,X),j=_??this.options.ttl,Y=this.estimateSize(Z);this.cache.set(L,{value:Z,timestamp:new Date,ttl:j,hits:0,size:Y}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey($,Z),_=this.cache.get(X);if(!_){this.totalMisses++;return}if(this.isExpired(_)){this.cache.delete(X),this.totalMisses++;return}return _.hits++,this.totalHits++,_.value}isFileModified($,Z){try{if(!nZ($))return!0;return iZ($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let X=this.get($,Z);if(!X)return;if(this.isFileModified(Z,X.fileTimestamp)){this.delete($,Z);return}return X.value}setWithFileCheck($,Z,X,_){try{let L=nZ(X)?iZ(X):null,j=L?L.mtime:new Date;this.set($,{value:Z,fileTimestamp:j},X,_)}catch{this.set($,Z,X,_)}}delete($,Z){let X=this.generateKey($,Z);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((_,L)=>_+L.size,0),X=$.map((_)=>_.timestamp).sort();return{size:Z,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:X[0],newestEntry:X[X.length-1]}}export(){let $={};for(let[Z,X]of this.cache.entries())$[Z]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return $}import($){this.cache.clear();for(let[Z,X]of Object.entries($))if(typeof X==="object"&&X!==null){let _=X;this.cache.set(Z,{value:_.value,timestamp:new Date(_.timestamp),ttl:_.ttl,hits:_.hits,size:_.size})}}}class i5{metrics=[];maxMetrics=1000;async track($,Z,X={}){let _=performance.now(),L=new Date;try{let j=await Z(),Y=performance.now()-_;return this.recordMetric({operation:$,duration:Y,timestamp:L,...X}),j}catch(j){let Y=performance.now()-_;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:L,...X}),j}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((L)=>L.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=Z.map((L)=>L.duration),_=X.reduce((L,j)=>L+j,0);return{count:Z.length,averageDuration:_/Z.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:_,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function Z4($,Z={}){let _=Object.keys(Z).sort().map((L)=>`${L}:${Z[L]}`).join("|");return _?`${$}:${_}`:$}function X4($,Z){try{return JSON.stringify($)===JSON.stringify(Z)}catch{return $===Z}}function _4($){return $.getStats().size*2}function DZ($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&K0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&K0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(K0(Z)&&K0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(K0($)&&"arr"in $&&Array.isArray($.arr)&&K0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&K0(Z[0])&&K0($[0])){let _=[...Z];for(let L of $)if(K0(L)&&"name"in L){if(!_.find((Y)=>K0(Y)&&("name"in Y)&&Y.name===L.name))_.push(L)}else if(K0(L)&&"path"in L){if(!_.find((Y)=>K0(Y)&&("path"in Y)&&Y.path===L.path))_.push(L)}else if(!_.some((j)=>V$(j,L)))_.push(L);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}if(!K0(Z)||!K0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let L=Z[_];if(L===null||L===void 0)continue;else if(K0(L)&&K0(X[_]))X[_]=DZ(X[_],L);else if(Array.isArray(L)&&Array.isArray(X[_]))if(L.length>0&&X[_].length>0&&K0(L[0])&&K0(X[_][0])){let j=[...L];for(let Y of X[_])if(K0(Y)&&"name"in Y){if(!j.find((F)=>K0(F)&&("name"in F)&&F.name===Y.name))j.push(Y)}else if(K0(Y)&&"path"in Y){if(!j.find((F)=>K0(F)&&("path"in F)&&F.path===Y.path))j.push(Y)}else if(!j.some((z)=>V$(z,Y)))j.push(Y);X[_]=j}else if(L.every((j)=>typeof j==="string")&&X[_].every((j)=>typeof j==="string")){let j=[...L];for(let Y of X[_])if(!j.includes(Y))j.push(Y);X[_]=j}else X[_]=L;else X[_]=L}return X}function V$($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!V$($[X],Z[X]))return!1;return!0}if(K0($)&&K0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!V$($[L],Z[L]))return!1}return!0}return!1}function K0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function L4($,Z){if(!$2($))return null;try{let X=await import($),_=X.default||X;if(typeof _!=="object"||_===null||Array.isArray(_))return null;try{return DZ(Z,_)}catch{return null}}catch{return null}}async function j4({name:$="",cwd:Z,defaultConfig:X}){let _=Z||u5.cwd(),L=[".ts",".js",".mjs",".cjs",".json"],j=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of j)for(let z of L){let F=O$(_,`${Y}${z}`),E=await L4(F,X);if(E!==null)return E}try{let Y=O$(_,"package.json");if($2(Y)){let F=(await import(Y))[$];if(F&&typeof F==="object"&&!Array.isArray(F))try{return DZ(X,F)}catch{}}}catch{}return X}function Y4($,Z={}){let X=E$.cwd();while(X.includes("storage"))X=oZ(X,"..");let _=oZ(X,$||"");if(Z?.relative)return R_(E$.cwd(),_);return _}async function F4(){try{let $=await j4({name:"clarity",defaultConfig:u1,cwd:E$.cwd(),endpoint:"",headers:{}});return{...u1,...$}}catch{return u1}}function M0(){if(G9.env.NODE_ENV==="test"||G9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function z4(){if(G9.env.NODE_ENV==="test"||G9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof G9<"u"){let $=G9.type;if($==="renderer"||$==="worker")return!1;return!!(G9.versions&&(G9.versions.node||G9.versions.bun))}return!1}class _2{async format($){let Z=await z4(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:i9.pid,hostname:Z(),environment:i9.env.NODE_ENV||"development",platform:i9.platform,version:i9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:i9.env.NODE_ENV||i9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class G${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=$,this.config={...r5},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new _2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??T0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let L=this.generateKeyId(),j=this.generateKey();this.currentKeyId=L,this.keys.set(L,j),this.encryptionKeys.set(L,{key:j,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...n1,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...n1};return{...n1,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:r5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}async writeToFile($){let X=(async()=>{let L,j=0,Y=3,z=1000;while(j<Y)try{try{try{await H_(this.config.logDirectory,eZ.F_OK|eZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await N_(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let F=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:H9.from($);try{if(!X5(this.currentLogFile))await _5(this.currentLogFile,"",{mode:420});if(L=aZ(this.currentLogFile,"a",420),q_(L,F,{flag:"a"}),tZ(L),L!==void 0)Z5(L),L=void 0;if((await u9(this.currentLogFile)).size===0){if(await _5(this.currentLogFile,F,{flag:"w",mode:420}),(await u9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let U=E;if(U.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(U.code)){if(j<Y-1){let V=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${j+1}/${Y}:`,V);let Q=z*2**j;await new Promise((O)=>setTimeout(O,Q)),j++;continue}}if(U?.code&&["ENOSPC","EDQUOT"].includes(U.code))throw Error(`Disk quota exceeded or no space left on device: ${U.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",U),U}finally{if(L!==void 0)try{Z5(L)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(F){if(j===Y-1){let U=F,V=typeof U.message==="string"?U.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),F}j++;let E=z*2**(j-1);await new Promise((U)=>setTimeout(U,E))}})();this.pendingOperations.push(X);let _=this.pendingOperations.length-1;try{await X}catch(L){throw console.error("Debug: [writeToFile] Error in operation:",L),L}finally{this.pendingOperations.splice(_,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 n9(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 n9(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return n9(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let X=typeof Z.interval==="number"?Z.interval:60,_=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((L)=>{console.error("Error rotating keys:",L)})},_)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,X=this.generateKeyId(),_=this.generateKey();this.currentKeyId=X,this.keys.set(X,_),this.encryptionKeys.set(X,{key:_,createdAt:new Date});let L=Array.from(this.encryptionKeys.entries()).sort(([,z],[,F])=>F.createdAt.getTime()-z.createdAt.getTime()),j=typeof Z.maxKeys==="number"?Z.maxKeys:1,Y=Math.max(1,j);if(L.length>Y)for(let[z]of L.slice(Y))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return $5(16).toString("hex")}generateKey(){return $5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=$5(16),_=J_("aes-256-gcm",Z,X),L=H9.concat([_.update($,"utf8"),_.final()]),j=_.getAuthTag();return{encrypted:H9.concat([X,L,j]),iv:X}}async compressData($){return new Promise((Z,X)=>{let _=Z6(),L=[];_.on("data",(j)=>L.push(j)),_.on("end",()=>Z(H9.from(H9.concat(L)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(M0())return;let $=await u9(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let L=await Q1(this.config.logDirectory),j=L.filter((F)=>F.startsWith(this.name)&&/\.log\.\d+$/.test(F)).sort((F,E)=>{let U=Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),Y=j.length>0?Number.parseInt(j[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${X}.${Y}`;if(await u9(X).catch(()=>null))try{if(await $6(X,z),Z.compress)try{let F=`${z}.gz`;await this.compressLogFile(z,F),await V1(z)}catch(F){console.error("Error compressing rotated file:",F)}if(j.length===0&&!L.some((F)=>F.endsWith(".log.1")))try{let F=`${X}.1`;await _5(F,"")}catch(F){console.error("Error creating backup file:",F)}}catch(F){console.error(`Error during rotation: ${F instanceof Error?F.message:String(F)}`)}}else{let L=new Date().toISOString().replace(/[:.]/g,"-"),j=X.replace(/\.log$/,`-${L}.log`);if(await u9(X).catch(()=>null))await $6(X,j)}if(this.currentLogFile=_,Z.maxFiles){let j=(await Q1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,z)=>z.localeCompare(Y));for(let Y of j.slice(Z.maxFiles))await V1(n9(this.config.logDirectory,Y))}}}async compressLogFile($,Z){let X=rZ($),_=w_(Z),L=Z6();await P_(X,L,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);await this.writeToFile(_),console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(Z),console.log(Z);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:$,message:Z,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),X5(this.currentLogFile))try{let $=aZ(this.currentLogFile,"r+");tZ($),Z5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await Q1(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of Z)try{await V1(n9(this.config.logDirectory,X))}catch(_){console.error(`Failed to delete temp file ${X}:`,_)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?O0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:L,level:j,showTimestamp:Y=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(Y)O.push(Z);if(j==="warning")O.push("WARN");else if(j==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(L),O.join(" ")}let F=T0.stdout.columns||120,E="";if(j==="warning"||j==="error")E=`${X} ${L}`;else if(j==="info"||j==="success")E=`${X} ${_} ${L}`;else E=`${X} ${_} ${O0.cyan(L)}`;if(!Y)return E.trim();let U=z(E).trim().length,V=z(Z).length,Q=Math.max(1,F-2-U-V);return`${E.trim()}${" ".repeat(Q)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(j,Y)=>{let z=Number.parseInt(Y,10);return z<Z[0].length?String(Z[0][z]):j});let X=/%([sdijfo%])/g,_=0,L=$.replace(X,(j,Y)=>{if(Y==="%")return"%";if(_>=Z.length)return j;let z=Z[_++];switch(Y){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return j}});if(_<Z.length)L+=` ${Z.slice(_).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`;return L}async log($,Z,...X){let _=new Date,L=this.formatConsoleTimestamp(_),j=this.formatFileTimestamp(_),Y,z;if(Z instanceof Error)Y=Z.message,z=Z.stack;else Y=this.formatMessage(Z,X);if(this.fancy&&!M0()){let E=M2[$],U=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"",V;switch($){case"debug":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:O0.gray(Y),level:$}),console.error(V);break;case"info":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Y,level:$}),console.error(V);break;case"success":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:O0.green(Y),level:$}),console.error(V);break;case"warning":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Y,level:$}),console.warn(V);break;case"error":if(V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Y,level:$}),console.error(V),z){let Q=z.split(`
7
- `);for(let O of Q)if(O.trim()&&!O.includes(Y))console.error(this.formatConsoleMessage({timestamp:L,message:O0.gray(` ${O}`),level:$,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${j} ${this.environment}.${$.toUpperCase()}: ${Y}`),z)console.error(z)}if(!this.shouldLog($))return;let F=`${j} ${this.environment}.${$.toUpperCase()}: ${Y}
8
- `;if(z)F+=`${z}
9
- `;F=F.replace(this.ANSI_PATTERN,""),await this.writeToFile(F)}time($){let Z=performance.now();if(this.fancy&&!M0()){let X=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:O0.blue("\u25D0"),tag:X,message:`${O0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),L=Math.round(_-Z),j=`${$} completed in ${L}ms`,Y=new Date,z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${j}`;if(X)E+=` ${JSON.stringify(X)}`;if(E+=`
10
- `,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!M0()){let U=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:O0.green("\u2713"),tag:U,message:`${j}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!M0())console.error(E.trim());await this.writeToFile(E)}}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 $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new G$(Z,{...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(X),X}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!X5(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=H9.isBuffer($)?$:H9.from($,"base64"),L=_.slice(0,16),j=_.slice(-16),Y=_.slice(16,-16),z=C_("aes-256-gcm",X,L);return z.setAuthTag(j),H9.concat([z.update(Y),z.final()]).toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey($,Z){this.currentKeyId=$,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($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z);if(this.fancy&&!M0()){let j=$.split(`
11
- `),Y=Math.max(...j.map((U)=>U.length))+2,z=`\u250C${"\u2500".repeat(Y)}\u2510`,F=`\u2514${"\u2500".repeat(Y)}\u2518`,E=j.map((U)=>{let V=" ".repeat(Y-U.length-2);return`\u2502 ${U}${V} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:O0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:O0.cyan(z)})),E.forEach((U)=>console.error(this.formatConsoleMessage({timestamp:X,message:O0.cyan(U),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:O0.cyan(F),showTimestamp:!1}))}else if(!M0())console.error(`${_} ${this.environment}.INFO: [BOX] ${$}`);let L=`${_} ${this.environment}.INFO: [BOX] ${$}
12
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(L)}async prompt($){if(M0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${O0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let L=_.toString().trim().toLowerCase();T0.stdin.removeListener("data",X);try{if(typeof T0.stdin.setRawMode==="function")T0.stdin.setRawMode(!1)}catch{}T0.stdin.pause(),console.error(""),Z(L==="y"||L==="yes")};try{if(typeof T0.stdin.setRawMode==="function")T0.stdin.setRawMode(!0)}catch{}T0.stdin.resume(),T0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let Y=/%([sdijfo%])/g,z=0;if(X=$.replace(Y,(F,E)=>{if(E==="%")return"%";if(z>=Z.length)return F;let U=Z[z++];switch(E){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return F}}),z<Z.length)X+=` ${Z.slice(z).map((F)=>typeof F==="object"?JSON.stringify(F,null,2):String(F)).join(" ")}`}if(this.fancy&&!M0()){let Y=this.options.showTags!==!1&&this.name?O0.gray(this.formatTag(this.name)):"",z=O0.blue("\u25D0");console.error(`${z} ${Y} ${O0.cyan(X)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
13
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(j)}progress($,Z=""){if(!this.enabled||!this.fancy||M0()||$<=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 X=20;return this.activeProgressBar={total:$,current:0,message:Z,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Y,z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||M0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),z!==void 0)this.activeProgressBar.message=z;let F=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,F)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||M0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||M0())return;T0.stdout.write(`${"\r".padEnd(T0.stdout.columns||80)}\r`),this.log(z,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,Z=!1){if(!this.enabled||!this.fancy||M0()||!T0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),L=$.barLength-_,j=O0.green("\u2501".repeat(_)),Y=O0.gray("\u2501".repeat(L)),z=`[${j}${Y}]`,F=`${X}%`.padStart(4),E=$.message?` ${$.message}`:"",U=Z||X===100?O0.green("\u2713"):O0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${O0.gray(this.formatTag(this.name))}`:"",Q=`\r${U}${V} ${z} ${F}${E}`,O=T0.stdout.columns||80,K=" ".repeat(Math.max(0,O-Q.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${Q}${K}`,T0.stdout.write($.lastRenderedLine),Z)T0.stdout.write(`
14
- `)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||M0()||!T0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await Q1(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let j=n9(this.config.logDirectory,_);if($.before)try{if((await u9(j)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${j}:`,Y);continue}X.push(j)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await V1(_),console.warn(`Deleted log file: ${_}`)}catch(L){console.error(`Failed to delete log file ${_}:`,L)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}function m1($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&Y0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&Y0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(Y0(Z)&&Y0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(Y0($)&&"arr"in $&&Array.isArray($.arr)&&Y0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&Y0(Z[0])&&Y0($[0])){let _=[...Z];for(let L of $)if(Y0(L)&&"name"in L){if(!_.find((Y)=>Y0(Y)&&("name"in Y)&&Y.name===L.name))_.push(L)}else if(Y0(L)&&"path"in L){if(!_.find((Y)=>Y0(Y)&&("path"in Y)&&Y.path===L.path))_.push(L)}else if(!_.some((j)=>K$(j,L)))_.push(L);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}if(!Y0(Z)||!Y0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let L=Z[_];if(L===null||L===void 0)continue;else if(Y0(L)&&Y0(X[_]))X[_]=m1(X[_],L);else if(Array.isArray(L)&&Array.isArray(X[_]))if(L.length>0&&X[_].length>0&&Y0(L[0])&&Y0(X[_][0])){let j=[...L];for(let Y of X[_])if(Y0(Y)&&"name"in Y){if(!j.find((F)=>Y0(F)&&("name"in F)&&F.name===Y.name))j.push(Y)}else if(Y0(Y)&&"path"in Y){if(!j.find((F)=>Y0(F)&&("path"in F)&&F.path===Y.path))j.push(Y)}else if(!j.some((z)=>K$(z,Y)))j.push(Y);X[_]=j}else if(L.every((j)=>typeof j==="string")&&X[_].every((j)=>typeof j==="string")){let j=[...L];for(let Y of X[_])if(!j.includes(Y))j.push(Y);X[_]=j}else X[_]=L;else X[_]=L}return X}function SZ($,Z,X="replace"){if(Z===null||Z===void 0)return $;if(Array.isArray(Z))return X==="replace"?Z:m1($,Z);if(Array.isArray($))return X==="replace"?Z:m1($,Z);if(!Y0(Z)||!Y0($))return Z;let _={...$};for(let L of Object.keys(Z)){if(!Object.prototype.hasOwnProperty.call(Z,L))continue;let j=Z[L],Y=_[L];if(j===null||j===void 0)continue;if(Array.isArray(j)||Array.isArray(Y))if(X==="replace")_[L]=j;else _[L]=m1(Y,j);else if(Y0(j)&&Y0(Y))_[L]=SZ(Y,j,X);else _[L]=j}return _}function K$($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!K$($[X],Z[X]))return!1;return!0}if(Y0($)&&Y0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!K$($[L],Z[L]))return!1}return!0}return!1}function Y0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function w1($,Z,X="replace"){if(!e7($))return null;try{let _=await import($),L=_.default||_;if(typeof L!=="object"||L===null||Array.isArray(L))return null;try{return SZ(Z,L,X)}catch{return null}}catch{return null}}function U4($,Z,X=!1){if(!$)return Z;let _=$.toUpperCase().replace(/-/g,"_"),L={...Z};function j(Y,z=[]){let F={...Y};for(let[E,U]of Object.entries(Y)){let V=[...z,E],Q=(I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${_}_${V.map(Q).join("_")}`,K=`${_}_${V.map((I)=>I.toUpperCase()).join("_")}`;if(X)h0.info(`Checking environment variable ${O} for config ${$}.${V.join(".")}`);if(typeof U==="object"&&U!==null&&!Array.isArray(U))F[E]=j(U,V);else{let I=a8.env[O]||a8.env[K];if(I!==void 0){if(X)h0.info(`Using environment variable ${I?O:K} for config ${$}.${V.join(".")}`);if(typeof U==="number")F[E]=Number(I);else if(typeof U==="boolean")F[E]=I.toLowerCase()==="true";else if(Array.isArray(U))try{let C=JSON.parse(I);if(Array.isArray(C))F[E]=C;else F[E]=I.split(",").map((D)=>D.trim())}catch{F[E]=I.split(",").map((C)=>C.trim())}else F[E]=I}}}return F}return j(L)}async function E4({name:$="",alias:Z,cwd:X,configDir:_,defaultConfig:L,verbose:j=!1,checkEnv:Y=!0,arrayStrategy:z="replace"}){let F=Y&&typeof L==="object"&&L!==null&&!Array.isArray(L)?U4($,L,j):L,E=X||a8.cwd(),U=[".ts",".js",".mjs",".cjs",".json"];if(j)h0.info(`Loading configuration for "${$}"${Z?` (alias: "${Z}")`:""} from ${E}`);let V=[$,`.${$}`].filter(Boolean),Q=[`${$}.config`,`.${$}.config`].filter(Boolean),O=Z?[Z,`.${Z}`]:[],K=Z?[`${Z}.config`,`.${Z}.config`]:[],I=Array.from(new Set([E,g0(E,"config"),g0(E,".config"),_?g0(E,_):void 0].filter(Boolean)));for(let C of I){if(j)h0.info(`Searching for configuration in: ${C}`);let M=[g0(E,"config"),g0(E,".config")].concat(_?[g0(E,_)]:[]).includes(C)?[...V,...Q,...O,...K]:[...Q,...V,...K,...O];for(let J of M)for(let N of U){let T=g0(C,`${J}${N}`),v=await w1(T,F,z);if(v!==null){if(j)h0.success(`Configuration loaded from: ${T}`);return v}}}if($){let C=g0(e$(),".config",$),D=["config",`${$}.config`];if(Z)D.push(`${Z}.config`);if(j)h0.info(`Checking user config directory: ${C}`);for(let M of D)for(let J of U){let N=g0(C,`${M}${J}`),T=await w1(N,F,z);if(T!==null){if(j)h0.success(`Configuration loaded from user config directory: ${N}`);return T}}}if($){let C=g0(e$(),".config"),D=[`.${$}.config`];if(Z)D.push(`.${Z}.config`);if(j)h0.info(`Checking user config directory for dotfile configs: ${C}`);for(let M of D)for(let J of U){let N=g0(C,`${M}${J}`),T=await w1(N,F,z);if(T!==null){if(j)h0.success(`Configuration loaded from user config directory dotfile: ${N}`);return T}}}if($){let C=e$(),D=[`.${$}.config`,`.${$}`];if(Z)D.push(`.${Z}.config`),D.push(`.${Z}`);if(j)h0.info(`Checking user home directory for dotfile configs: ${C}`);for(let M of D)for(let J of U){let N=g0(C,`${M}${J}`),T=await w1(N,F,z);if(T!==null){if(j)h0.success(`Configuration loaded from user home directory: ${N}`);return T}}}try{let C=g0(E,"package.json");if(e7(C)){let D=await import(C),M=D[$];if(!M&&Z){if(M=D[Z],M&&j)h0.success(`Using alias "${Z}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(j)h0.success(`Configuration loaded from package.json: ${M===D[$]?$:Z}`);return SZ(F,M,z)}catch(J){if(j)h0.warn("Failed to merge package.json config:",J)}}}catch(C){if(j)h0.warn("Failed to load package.json:",C)}if(j)h0.info(`No configuration found for "${$}"${Z?` or alias "${Z}"`:""}, using default configuration with environment variables`);return F}function O4($,Z={}){let X=U$.cwd();while(X.includes("storage"))X=sZ(X,"..");let _=sZ(X,$||"");if(Z?.relative)return S_(U$.cwd(),_);return _}async function Q4(){try{let $=await E4({name:"clarity",alias:"logging",defaultConfig:i1,cwd:U$.cwd()});return{...i1,...$||{}}}catch{return i1}}function J0(){if(K9.env.NODE_ENV==="test"||K9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V4(){if(K9.env.NODE_ENV==="test"||K9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof K9<"u"){let $=K9.type;if($==="renderer"||$==="worker")return!1;return!!(K9.versions&&(K9.versions.node||K9.versions.bun))}return!1}class L2{async format($){let Z=await V4(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:o9.pid,hostname:Z(),environment:o9.env.NODE_ENV||"development",platform:o9.platform,version:o9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:o9.env.NODE_ENV||o9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class I${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=$,this.config={...t5},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new L2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??$0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let L=this.generateKeyId(),j=this.generateKey();this.currentKeyId=L,this.keys.set(L,j),this.encryptionKeys.set(L,{key:j,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[X]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...l1,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...l1};return{...l1,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:t5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}shouldWriteToFile(){return!J0()&&this.config.writeToFile===!0}async writeToFile($){let X=(async()=>{let L,j=0,Y=3,z=1000;while(j<Y)try{try{try{await h_(this.config.logDirectory,j6.F_OK|j6.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await y_(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let F=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O9.from($);try{if(!G1(this.currentLogFile))await Y5(this.currentLogFile,"",{mode:420});if(L=L6(this.currentLogFile,"a",420),B_(L,F,{flag:"a"}),_6(L),L!==void 0)j5(L),L=void 0;if((await l9(this.currentLogFile)).size===0){if(await Y5(this.currentLogFile,F,{flag:"w",mode:420}),(await l9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let U=E;if(U.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(U.code)){if(j<Y-1){let V=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${j+1}/${Y}:`,V);let Q=z*2**j;await new Promise((O)=>setTimeout(O,Q)),j++;continue}}if(U?.code&&["ENOSPC","EDQUOT"].includes(U.code))throw Error(`Disk quota exceeded or no space left on device: ${U.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",U),U}finally{if(L!==void 0)try{j5(L)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(F){if(j===Y-1){let U=F,V=typeof U.message==="string"?U.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),F}j++;let E=z*2**(j-1);await new Promise((U)=>setTimeout(U,E))}})();this.pendingOperations.push(X);let _=this.pendingOperations.length-1;try{await X}catch(L){throw console.error("Debug: [writeToFile] Error in operation:",L),L}finally{this.pendingOperations.splice(_,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 s9(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 s9(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return s9(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let X=typeof Z.interval==="number"?Z.interval:60,_=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((L)=>{console.error("Error rotating keys:",L)})},_)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,X=this.generateKeyId(),_=this.generateKey();this.currentKeyId=X,this.keys.set(X,_),this.encryptionKeys.set(X,{key:_,createdAt:new Date});let L=Array.from(this.encryptionKeys.entries()).sort(([,z],[,F])=>F.createdAt.getTime()-z.createdAt.getTime()),j=typeof Z.maxKeys==="number"?Z.maxKeys:1,Y=Math.max(1,j);if(L.length>Y)for(let[z]of L.slice(Y))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return L5(16).toString("hex")}generateKey(){return L5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=L5(16),_=T_("aes-256-gcm",Z,X),L=O9.isBuffer($)?$:O9.from($,"utf8"),j=_.update(L),Y=_.final(),z=j.length+Y.length,F=_.getAuthTag(),E=O9.allocUnsafe(16+z+16);return X.copy(E,0),j.copy(E,16),Y.copy(E,16+j.length),F.copy(E,16+z),{encrypted:E,iv:X}}async compressData($){return new Promise((Z,X)=>{let _=F6(),L=[];_.on("data",(j)=>L.push(j)),_.on("end",()=>Z(O9.from(O9.concat(L)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(J0())return;if(!this.shouldWriteToFile())return;let $=await l9(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let L=await K1(this.config.logDirectory),j=L.filter((F)=>F.startsWith(this.name)&&/\.log\.\d+$/.test(F)).sort((F,E)=>{let U=Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),Y=j.length>0?Number.parseInt(j[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${X}.${Y}`;if(await l9(X).catch(()=>null))try{if(await Y6(X,z),Z.compress)try{let F=`${z}.gz`;await this.compressLogFile(z,F),await I1(z)}catch(F){console.error("Error compressing rotated file:",F)}if(j.length===0&&!L.some((F)=>F.endsWith(".log.1")))try{let F=`${X}.1`;await Y5(F,"")}catch(F){console.error("Error creating backup file:",F)}}catch(F){console.error(`Error during rotation: ${F instanceof Error?F.message:String(F)}`)}}else{let L=new Date().toISOString().replace(/[:.]/g,"-"),j=X.replace(/\.log$/,`-${L}.log`);if(await l9(X).catch(()=>null))await Y6(X,j)}if(this.currentLogFile=_,Z.maxFiles){let j=(await K1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,z)=>z.localeCompare(Y));for(let Y of j.slice(Z.maxFiles))await I1(s9(this.config.logDirectory,Y))}}}async compressLogFile($,Z){let X=X6($),_=x_(Z),L=F6();await b_(X,L,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(_);console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),G1(this.currentLogFile))try{let $=L6(this.currentLogFile,"r+");_6($),j5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await K1(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of Z)try{await I1(s9(this.config.logDirectory,X))}catch(_){console.error(`Failed to delete temp file ${X}:`,_)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?X0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||J0())return!1;let $=typeof $0.env.NO_COLOR<"u",Z=$0.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof $0.stderr<"u"&&$0.stderr.isTTY||typeof $0.stdout<"u"&&$0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:L,level:j,showTimestamp:Y=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(Y)O.push(Z);if(j==="warning")O.push("WARN");else if(j==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(L),O.join(" ")}let F=$0.stdout.columns||120,E="";if(j==="warning"||j==="error")E=`${X} ${L}`;else if(j==="info"||j==="success")E=`${X} ${_} ${L}`;else E=`${X} ${_} ${X0.cyan(L)}`;if(!Y)return E.trim();let U=z(E).trim().length,V=z(Z).length,Q=Math.max(1,F-2-U-V);return`${E.trim()}${" ".repeat(Q)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(j,Y)=>{let z=Number.parseInt(Y,10);return z<Z[0].length?String(Z[0][z]):j});let X=/%([sdijfo%])/g,_=0,L=$.replace(X,(j,Y)=>{if(Y==="%")return"%";if(_>=Z.length)return j;let z=Z[_++];switch(Y){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return j}});if(_<Z.length)L+=` ${Z.slice(_).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`;return L}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,_,L)=>{let j=X0.underline(X0.blue(_)),Y=this.toAbsoluteFilePath(L);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(Y)}`,F="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${z}\x1B\\${j}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${L}\x1B\\${j}\x1B]8;;\x1B\\`;return j}),Z=Z.replace(/`([^`]+)`/g,(X,_)=>X0.bgGray(_)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(X,_)=>X0.bold(_)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,_)=>X0.italic(_)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,_)=>X0.italic(_)),Z=Z.replace(/~([^~]+)~/g,(X,_)=>X0.strikethrough(_)),Z}supportsHyperlinks(){if(J0())return!1;let $=$0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let X=$0.env.HOME||"";if(X)Z=Z.replace(/^~(?=$|\/)/,X)}if(A_(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=v_(Z);else return null;return G1(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,X=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:X}}async log($,Z,...X){let _=new Date,L=this.formatConsoleTimestamp(_),j=this.formatFileTimestamp(_),Y,z;if(Z instanceof Error)Y=Z.message,z=Z.stack;else Y=this.formatMessage(Z,X);let{consoleText:F,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":R2[$],Q=this.options.showTags!==!1&&this.name?X0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:X0.gray(F),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:X0.green(F),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.error(O),z){let K=z.split(`
15
- `);for(let I of K)if(I.trim()&&!I.includes(Y))console.error(this.formatConsoleMessage({timestamp:L,message:X0.gray(` ${I}`),level:$,showTimestamp:!1}))}break}}else if(!J0()){if(console.error(`${j} ${this.environment}.${$.toUpperCase()}: ${Y}`),z)console.error(z)}if(!this.shouldLog($))return;let U=`${j} ${this.environment}.${$.toUpperCase()}: ${E}
16
- `;if(z)U+=`${z}
17
- `;if(U=U.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(U)}progress($,Z=""){let X={update:(z,F)=>{},finish:(z)=>{},interrupt:(z,F)=>{}};if(!this.enabled)return X;let _=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:_,lastRenderedLine:""},this.shouldStyleConsole()&&!J0()&&$0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(z,F)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,z),this.activeProgressBar.total),F!==void 0)this.activeProgressBar.message=F;if(this.shouldStyleConsole()&&!J0()&&$0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,F="info")=>{if(!J0()&&$0.stdout.isTTY)$0.stdout.write(`
18
- `);if(this[F==="warning"?"warn":F](z),this.activeProgressBar&&this.shouldStyleConsole()&&!J0()&&$0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?X0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":X0.blue("\u25D0"),tag:X,message:`${X0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),L=Math.round(_-Z),j=`${$} completed in ${L}ms`,Y=new Date,z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${j}`;if(X)E+=` ${JSON.stringify(X)}`;if(E+=`
19
- `,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?X0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:this.options.showIcons===!1?"":X0.green("\u2713"),tag:U,message:`${j}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!J0())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}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 $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new I$(Z,{...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(X),X}createReadStream(){if(J0())throw Error("createReadStream is not supported in browser environments");if(!G1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return X6(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=O9.isBuffer($)?$:O9.from($,"base64"),L=_.subarray(0,16),j=_.subarray(_.length-16),Y=_.subarray(16,_.length-16),z=k_("aes-256-gcm",X,L);z.setAuthTag(j);let F=z.update(Y),E=z.final(),U=F.length+E.length,V=O9.allocUnsafe(U);return F.copy(V,0),E.copy(V,F.length),V.toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J0()}isServerMode(){return!J0()}setTestEncryptionKey($,Z){this.currentKeyId=$,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($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),{consoleText:L,fileText:j}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let z=L.split(`
20
- `),F=Math.max(...z.map((Q)=>Q.length))+2,E=`\u250C${"\u2500".repeat(F)}\u2510`,U=`\u2514${"\u2500".repeat(F)}\u2518`,V=z.map((Q)=>{return this.formatConsoleMessage({timestamp:X,message:X0.cyan(Q),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:X0.cyan(E),showTimestamp:!1})),V.forEach((Q)=>console.error(Q)),console.error(this.formatConsoleMessage({timestamp:X,message:X0.cyan(U),showTimestamp:!1}))}else if(!J0())console.error(`${_} ${this.environment}.INFO: [BOX] ${j}`);let Y=`${_} ${this.environment}.INFO: [BOX] ${j}
21
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(J0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${X0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let L=_.toString().trim().toLowerCase();$0.stdin.removeListener("data",X);try{if(typeof $0.stdin.setRawMode==="function")$0.stdin.setRawMode(!1)}catch{}$0.stdin.pause(),console.error(""),Z(L==="y"||L==="yes")};try{if(typeof $0.stdin.setRawMode==="function")$0.stdin.setRawMode(!0)}catch{}$0.stdin.resume(),$0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let F=/%([sdijfo%])/g,E=0;if(X=$.replace(F,(U,V)=>{if(V==="%")return"%";if(E>=Z.length)return U;let Q=Z[E++];switch(V){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return U}}),E<Z.length)X+=` ${Z.slice(E).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}let{consoleText:_,fileText:L}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let F=this.options.showTags!==!1&&this.name?X0.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${X0.blue("\u25D0")} `;console.error(`${E}${F} ${X0.cyan(_)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${L}
22
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!$0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),L=$.barLength-_,j=X0.green("\u2501".repeat(_)),Y=X0.gray("\u2501".repeat(L)),z=`[${j}${Y}]`,F=`${X}%`.padStart(4),E=$.message?` ${$.message}`:"",U=this.options.showIcons===!1?"":Z||X===100?X0.green("\u2713"):X0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${X0.gray(this.formatTag(this.name))}`:"",Q=`\r${U}${V} ${z} ${F}${E}`,O=$0.stdout.columns||80,K=" ".repeat(Math.max(0,O-Q.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${Q}${K}`,$0.stdout.write($.lastRenderedLine),Z)$0.stdout.write(`
23
- `)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||J0()||!$0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await K1(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let j=s9(this.config.logDirectory,_);if($.before)try{if((await l9(j)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${j}:`,Y);continue}X.push(j)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await I1(_),console.warn(`Deleted log file: ${_}`)}catch(L){console.error(`Failed to delete log file ${_}:`,L)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function j2($,Z={}){let{maxRetries:X=3,retryDelay:_=1000,isRetryable:L=()=>!0,fallback:j}=Z,Y=Error("Unknown error occurred");for(let z=0;z<=X;z++)try{return await $()}catch(F){if(Y=F instanceof Error?F:Error(String(F)),z===X||!L(Y))break;if(_>0)await new Promise((E)=>setTimeout(E,_))}if(j!==void 0)return j;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}function Y2($){return $ instanceof u0}function G4($){return $ instanceof s1}function K4($){if(Y2($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((X)=>$.message.toLowerCase().includes(X.toLowerCase()))}class m${defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,X={}){let{prefix:_,useCamelCase:L=!0,useBackwardCompatibility:j=!0,customParsers:Y={},verbose:z=!1,trackPerformance:F=!0}=X,E=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let U=_||this.generateEnvPrefix($),V={...Z};return this.processObject(V,[],U,{useCamelCase:L,useBackwardCompatibility:j,customParsers:Y,verbose:z,configName:$}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(F)return $1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,X,_){for(let[L,j]of Object.entries($)){let Y=[...Z,L],z=Y.map((U)=>this.formatEnvKey(U,_.useCamelCase)),F=`${X}_${z.join("_")}`,E=_.useBackwardCompatibility?`${X}_${Y.map((U)=>U.toUpperCase()).join("_")}`:null;if(_.verbose);if(typeof j==="object"&&j!==null&&!Array.isArray(j))this.processObject(j,Y,X,_);else{let U=W1.env[F]||(E?W1.env[E]:void 0);if(U!==void 0){if(_.verbose){let V=W1.env[F]?F:E}try{$[L]=this.parseEnvironmentValue(U,typeof j,F,_.customParsers,_.configName)}catch(V){if(V instanceof o1)throw V;throw B9.envVar(F,U,typeof j,_.configName)}}}}}parseEnvironmentValue($,Z,X,_,L){for(let[j,Y]of Object.entries(_))try{return Y($)}catch{continue}for(let j of this.defaultParsers)if(j.canParse($,Z))try{return j.parse($)}catch{throw B9.envVar(X,$,`${Z} (via ${j.name} parser)`,L)}return $}getEnvironmentVariables($){let Z={},X=$.toUpperCase();for(let[_,L]of Object.entries(W1.env))if(_.startsWith(X)&&L!==void 0)Z[_]=L;return Z}validateEnvironmentVariable($,Z,X){let _=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))_.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue($,Z,X,{})}catch(L){_.push(`Cannot parse value "${Z}" as ${X}: ${L}`)}return{isValid:_.length===0,errors:_}}generateEnvVarDocs($,Z,X={}){let{prefix:_,format:L="text"}=X,j=_||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(Z,[],j,Y),L){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,Z,X,_){for(let[L,j]of Object.entries($)){let Y=[...Z,L],z=`${X}_${Y.map((F)=>this.formatEnvKey(F,!0)).join("_")}`;if(typeof j==="object"&&j!==null&&!Array.isArray(j))this.extractEnvVarInfo(j,Y,X,_);else _.push({key:z,type:Array.isArray(j)?"array":typeof j,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(j)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let X=`Environment Variables for ${Z}:
4
+ `,F=J.map((y)=>y.toLowerCase()).join(";"),K=await R5(Y),D=[X,E,V,W,F,K].join(`
5
+ `),w=await R5(D),T="AWS4-HMAC-SHA256",N=`${j}/${_}/${Q}/aws4_request`,q=[T,z,N,w].join(`
6
+ `),H=await s7(U.secretAccessKey,j,_,Q),x=await iX(H,q),h=Array.from(new Uint8Array(x)).map((y)=>y.toString(16).padStart(2,"0")).join(""),c=`${T} Credential=${U.accessKeyId}/${N}, SignedHeaders=${F}, Signature=${h}`;return{...G,authorization:c}}class C6{config;endpoint;credentials;constructor(X){if(this.config=X,this.endpoint=X.endpoint??`https://dynamodb.${X.region}.amazonaws.com`,this.credentials=X.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(X,$){let Z=new URL(this.endpoint),Y=JSON.stringify($),U={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${X}`},_=await o7("POST",Z,U,Y,this.credentials,this.config.region,"dynamodb"),Q=await fetch(Z.toString(),{method:"POST",headers:_,body:Y});if(!Q.ok){let L=await Q.text(),z;try{let j=JSON.parse(L);z=j.message??j.Message??L}catch{z=L}throw Error(`DynamoDB ${X} failed: ${Q.status} - ${z}`)}return Q.json()}async query(X){return this.execute("Query",X)}async scan(X){return this.execute("Scan",X)}async getItem(X){return this.execute("GetItem",X)}async putItem(X){return this.execute("PutItem",X)}async updateItem(X){return this.execute("UpdateItem",X)}async deleteItem(X){return this.execute("DeleteItem",X)}async batchGetItem(X){return this.execute("BatchGetItem",X)}async batchWriteItem(X){return this.execute("BatchWriteItem",X)}async transactWriteItems(X){return this.execute("TransactWriteItems",X)}async describeTable(X){return this.execute("DescribeTable",{TableName:X})}async createTable(X){return this.execute("CreateTable",X)}async deleteTable(X){return this.execute("DeleteTable",{TableName:X})}async listTables(X){return this.execute("ListTables",X??{})}async updateTable(X){return this.execute("UpdateTable",X)}async updateTimeToLive(X){return this.execute("UpdateTimeToLive",X)}async describeTimeToLive(X){return this.execute("DescribeTimeToLive",{TableName:X})}}function w6(X){return new C6(X)}function fj(X){y9={...y9,...X},G8=null,F8=null}function l9(){if(!G8)G8=w6({region:y9.region??"us-east-1",endpoint:y9.endpoint,credentials:y9.credentials});return G8}function s9(){if(!F8)F8=bX({region:y9.region??"us-east-1",endpoint:y9.endpoint,credentials:y9.credentials});return F8}class r7{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(X={}){this._attributes={...X},this._original={...X};for(let[$,Z]of Object.entries(X))this[$]=Z}static query(){return new q6(this)}static async find(X){let $=this,Z=l9(),Y=s9(),U=`${$.pkPrefix}${$.keyDelimiter}${X}`,_=$.skPrefix;try{let Q=await Z.getItem({TableName:$.tableName,Key:Y.marshall({[$.pkAttribute]:U,[$.skAttribute]:_})});if(!Q.Item)return null;let L=Y.unmarshall(Q.Item),z=new $(L);return z._exists=!0,z}catch(Q){return console.error("Find error:",Q),null}}static async findOrFail(X){let $=await this.find(X);if(!$)throw Error(`${this.name} not found with id: ${X}`);return $}static async all(){return this.query().get()}static async create(X){let $=this,Z=l9(),Y=s9(),U=X[$.primaryKey];if(!U)throw Error(`${$.primaryKey} is required`);let _=`${$.pkPrefix}${$.keyDelimiter}${U}`,Q=$.skPrefix,L=new Date().toISOString(),z={...X,[$.pkAttribute]:_,[$.skAttribute]:Q,[$.entityTypeAttribute]:$.name};if($.timestamps)z[$.createdAtField]=L,z[$.updatedAtField]=L;await Z.putItem({TableName:$.tableName,Item:Y.marshall(z),ConditionExpression:`attribute_not_exists(${$.pkAttribute})`});let j=new $(z);return j._exists=!0,j}static async updateOrCreate(X,$){let Z=this,Y=X[Z.primaryKey],U=await Z.find(Y);if(U)return await U.update($),U;return Z.create({...X,...$})}static where(X,$,Z){return this.query().where(X,$,Z)}static wherePk(X){return this.query().wherePk(X)}getKey(){let X=this.constructor;return this[X.primaryKey]}getAttribute(X){return this._attributes[X]}setAttribute(X,$){return this._attributes[X]=$,this[X]=$,this}getAttributes(){return{...this._attributes}}isDirty(X){if(X)return this._attributes[X]!==this._original[X];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let X={};for(let[$,Z]of Object.entries(this._attributes))if(Z!==this._original[$])X[$]=Z;return X}async save(){if(this._exists){let X=this.getDirty();if(Object.keys(X).length>0)await this.update(X)}else{let $=await this.constructor.create(this._attributes);this._attributes=$._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(X){let $=this.constructor,Z=l9(),Y=s9(),U=this.getKey(),_=`${$.pkPrefix}${$.keyDelimiter}${U}`,Q=$.skPrefix,L=new Date().toISOString(),z={...X};if($.timestamps)z[$.updatedAtField]=L;let j=[],E={},V={},G=0;for(let[J,W]of Object.entries(z)){let F=`#attr${G}`,K=`:val${G}`;E[F]=J,V[K]=Y.marshall({v:W}).v,j.push(`${F} = ${K}`),G++}await Z.updateItem({TableName:$.tableName,Key:Y.marshall({[$.pkAttribute]:_,[$.skAttribute]:Q}),UpdateExpression:`SET ${j.join(", ")}`,ExpressionAttributeNames:E,ExpressionAttributeValues:V});for(let[J,W]of Object.entries(z))this._attributes[J]=W,this[J]=W;return this._original={...this._attributes},this}async delete(){let X=this.constructor,$=l9(),Z=s9(),Y=this.getKey(),U=`${X.pkPrefix}${X.keyDelimiter}${Y}`,_=X.skPrefix;return await $.deleteItem({TableName:X.tableName,Key:Z.marshall({[X.pkAttribute]:U,[X.skAttribute]:_})}),this._exists=!1,!0}async refresh(){let $=await this.constructor.find(this.getKey());if($){this._attributes=$._attributes,this._original={...this._attributes};for(let[Z,Y]of Object.entries(this._attributes))this[Z]=Y}return this}toObject(){let X=this.constructor,$={...this._attributes};return delete $[X.pkAttribute],delete $[X.skAttribute],delete $[X.entityTypeAttribute],$}toJSON(){return this.toObject()}}class q6{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(X){this.ModelClass=X}wherePk(X){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${X}`,this}where(X,$,Z){if(Z===void 0)this._filterConditions.push({attribute:X,operator:"=",value:$});else this._filterConditions.push({attribute:X,operator:$,value:Z});return this}whereIn(X,$){return this._filterConditions.push({attribute:X,operator:"IN",values:$}),this}whereBetween(X,$,Z){return this._filterConditions.push({attribute:X,operator:"BETWEEN",value:$,values:[$,Z]}),this}whereBeginsWith(X,$){return this._filterConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereExists(X){return this._filterConditions.push({attribute:X,operator:"attribute_exists"}),this}whereNotExists(X){return this._filterConditions.push({attribute:X,operator:"attribute_not_exists"}),this}orderBy(X){return this._scanForward=X==="asc",this}limit(X){return this._limitValue=X,this}select(...X){return this._projectionAttrs.push(...X),this}index(X){return this._indexName=X,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(X){return this._startKey=X,this}buildRequest(){let X=s9(),$={TableName:this.ModelClass.tableName};if(this._indexName)$.IndexName=this._indexName;let Z={},Y={},U=0,_=[];if(this._pkValue){let Q=`#pk${U}`,L=`:pk${U}`;Z[Q]=this.ModelClass.pkAttribute,Y[L]={S:this._pkValue},_.push(`${Q} = ${L}`),U++}if(this._skCondition){let Q=`#sk${U}`;switch(Z[Q]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let L=`:sk${U}`;Y[L]={S:this._skCondition.value},_.push(`${Q} = ${L}`);break}case"begins_with":{let L=`:sk${U}`;Y[L]={S:this._skCondition.value},_.push(`begins_with(${Q}, ${L})`);break}}U++}if(_.length>0)$.KeyConditionExpression=_.join(" AND ");if(this._filterConditions.length>0){let Q=[];for(let L of this._filterConditions){let z=`#flt${U}`;if(Z[z]=L.attribute,L.operator==="attribute_exists")Q.push(`attribute_exists(${z})`);else if(L.operator==="attribute_not_exists")Q.push(`attribute_not_exists(${z})`);else if(L.operator==="IN"&&L.values){let j=L.values.map((E,V)=>`:flt${U}_${V}`);L.values.forEach((E,V)=>{Y[`:flt${U}_${V}`]=X.marshall({v:E}).v}),Q.push(`${z} IN (${j.join(", ")})`)}else if(L.operator==="BETWEEN"&&L.values){let j=`:flt${U}a`,E=`:flt${U}b`;Y[j]=X.marshall({v:L.values[0]}).v,Y[E]=X.marshall({v:L.values[1]}).v,Q.push(`${z} BETWEEN ${j} AND ${E}`)}else if(L.operator==="begins_with"){let j=`:flt${U}`;Y[j]=X.marshall({v:L.value}).v,Q.push(`begins_with(${z}, ${j})`)}else{let j=`:flt${U}`;Y[j]=X.marshall({v:L.value}).v,Q.push(`${z} ${L.operator} ${j}`)}U++}$.FilterExpression=Q.join(" AND ")}if(this._projectionAttrs.length>0){let Q=[];for(let L of this._projectionAttrs){let z=`#proj${U}`;Z[z]=L,Q.push(z),U++}$.ProjectionExpression=Q.join(", ")}if(Object.keys(Z).length>0)$.ExpressionAttributeNames=Z;if(Object.keys(Y).length>0)$.ExpressionAttributeValues=Y;if(this._limitValue!==void 0)$.Limit=this._limitValue;if($.ScanIndexForward=this._scanForward,this._consistentReadValue)$.ConsistentRead=!0;if(this._startKey)$.ExclusiveStartKey=X.marshall(this._startKey);return $}async get(){let X=l9(),$=s9(),Z=this.buildRequest();return((this._pkValue!==void 0?await X.query(Z):await X.scan(Z)).Items??[]).map((Q)=>{let L=$.unmarshall(Q),z=new this.ModelClass(L);return z._exists=!0,z})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let X=l9(),$=this.buildRequest();return $.Select="COUNT",(this._pkValue!==void 0?await X.query($):await X.scan($)).Count??0}async paginate(X,$){let Z=s9();if($)this._startKey=$;this._limitValue=X;let Y=l9(),U=this.buildRequest(),Q=this._pkValue!==void 0?await Y.query(U):await Y.scan(U);return{items:(Q.Items??[]).map((z)=>{let j=Z.unmarshall(z),E=new this.ModelClass(j);return E._exists=!0,E}),lastKey:Q.LastEvaluatedKey?Z.unmarshall(Q.LastEvaluatedKey):void 0}}}var y9,G8=null,F8=null,a7=e(()=>{y9={region:process.env.AWS_REGION??"us-east-1"}});function T8(X){let $=JSON.stringify({tableName:X.tableName,keySchema:X.keySchema,attributeDefinitions:[...X.attributeDefinitions||[]].sort((Y,U)=>Y.name.localeCompare(U.name)),globalSecondaryIndexes:[...X.globalSecondaryIndexes||[]].sort((Y,U)=>Y.indexName.localeCompare(U.indexName)),localSecondaryIndexes:[...X.localSecondaryIndexes||[]].sort((Y,U)=>Y.indexName.localeCompare(U.indexName)),billingMode:X.billingMode,ttlAttribute:X.ttlAttribute,streamSpecification:X.streamSpecification}),Z=0;for(let Y=0;Y<$.length;Y++){let U=$.charCodeAt(Y);Z=(Z<<5)-Z+U,Z=Z&Z}return Math.abs(Z).toString(16).padStart(8,"0")}function t7(X){let $=e7(X);return X2($)}function e7(X){return{tableName:X.tableName||"",pkAttribute:X.pkAttribute||"pk",skAttribute:X.skAttribute||"sk",pkPrefix:X.pkPrefix||"",skPrefix:X.skPrefix||"METADATA",entityTypeAttribute:X.entityTypeAttribute||"_et",timestamps:X.timestamps!==!1,ttlAttribute:X.ttlAttribute,gsis:X.gsis,lsis:X.lsis,billingMode:X.billingMode||"PAY_PER_REQUEST",provisionedThroughput:X.provisionedThroughput,streamEnabled:X.streamEnabled,streamViewType:X.streamViewType}}function X2(X){let $=[{name:X.pkAttribute,type:"S"},{name:X.skAttribute,type:"S"}],Z=[];if(X.gsis)for(let Y of X.gsis){if(!$.some((U)=>U.name===Y.pkAttribute))$.push({name:Y.pkAttribute,type:"S"});if(Y.skAttribute&&!$.some((U)=>U.name===Y.skAttribute))$.push({name:Y.skAttribute,type:"S"});Z.push({indexName:Y.indexName,keySchema:{partitionKey:Y.pkAttribute,sortKey:Y.skAttribute},projection:{type:Array.isArray(Y.projection)?"INCLUDE":Y.projection||"ALL",nonKeyAttributes:Array.isArray(Y.projection)?Y.projection:void 0},provisionedThroughput:Y.provisionedThroughput})}return{tableName:X.tableName,keySchema:{partitionKey:X.pkAttribute,sortKey:X.skAttribute},attributeDefinitions:$,globalSecondaryIndexes:Z.length>0?Z:void 0,billingMode:X.billingMode,provisionedThroughput:X.provisionedThroughput,ttlAttribute:X.ttlAttribute,streamSpecification:X.streamEnabled?{enabled:!0,viewType:X.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function $2(X,$){let Z=[],Y=$.tableName;if(!X)Z.push({type:"CREATE_TABLE",tableName:Y,details:{definition:$}});else{let U=X.keySchema.partitionKey!==$.keySchema.partitionKey,_=X.keySchema.sortKey!==$.keySchema.sortKey;if(U||_)console.warn(`[Migration] Table ${Y}: Key schema changes require table recreation. Current: pk=${X.keySchema.partitionKey}, sk=${X.keySchema.sortKey}. Target: pk=${$.keySchema.partitionKey}, sk=${$.keySchema.sortKey}. This operation is not supported automatically.`);let Q=X.globalSecondaryIndexes||[],L=$.globalSecondaryIndexes||[],z=new Set(Q.map((G)=>G.indexName)),j=new Set(L.map((G)=>G.indexName));for(let G of L)if(!z.has(G.indexName))Z.push({type:"ADD_GSI",tableName:Y,details:{gsi:G}});for(let G of Q)if(!j.has(G.indexName))Z.push({type:"DELETE_GSI",tableName:Y,details:{indexName:G.indexName}});if(X.billingMode!==$.billingMode&&$.billingMode)Z.push({type:"UPDATE_BILLING_MODE",tableName:Y,details:{billingMode:$.billingMode,provisionedThroughput:$.provisionedThroughput}});if(X.ttlAttribute!==$.ttlAttribute)Z.push({type:"UPDATE_TTL",tableName:Y,details:{ttlAttribute:$.ttlAttribute||null,enabled:!!$.ttlAttribute}});let E=X.streamSpecification?.enabled,V=$.streamSpecification?.enabled;if(E!==V)if(V)Z.push({type:"ENABLE_STREAM",tableName:Y,details:{viewType:$.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else Z.push({type:"DISABLE_STREAM",tableName:Y,details:{}})}return{tableName:Y,operations:Z,timestamp:new Date().toISOString(),hash:T8($)}}function gj(X,$){return T8(X)===T8($)}class P6{client;initialized=!1;constructor(X){this.client=X}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(K9),this.initialized=!0}catch(X){if(X.message?.includes("ResourceNotFoundException")||X.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${K9}`),await this.client.createTable({TableName:K9,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(K9),this.initialized=!0;else throw X}}async waitForTableActive(X,$=30){for(let Z=0;Z<$;Z++){try{if((await this.client.describeTable(X)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((Y)=>setTimeout(Y,1000))}throw Error(`Table ${X} did not become active within ${$} seconds`)}async getLatestState(X){await this.ensureMigrationsTable();let $=`${cX}#${X}`,Z=await this.client.query({TableName:K9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:$}},ScanIndexForward:!1,Limit:1});if(!Z.Items||Z.Items.length===0)return null;return this.unmarshallState(Z.Items[0])}async getHistory(X){await this.ensureMigrationsTable();let $=`${cX}#${X}`,Z=await this.client.query({TableName:K9,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:$}},ScanIndexForward:!1});if(!Z.Items)return[];return Z.Items.map((Y)=>this.unmarshallState(Y))}async recordMigration(X,$,Z){await this.ensureMigrationsTable();let Y=await this.getLatestState(X),U=Z??(Y?Y.version+1:1),_=`${cX}#${X}`,Q=`${D5}#${String(U).padStart(6,"0")}`,L={tableName:X,hash:T8($),definition:$,appliedAt:new Date().toISOString(),version:U};return await this.client.putItem({TableName:K9,Item:this.marshallState(L,_,Q)}),console.log(`[Migration] Recorded migration for ${X} (version ${U})`),L}async listTrackedTables(){await this.ensureMigrationsTable();let X=await this.client.scan({TableName:K9,ProjectionExpression:"pk"});if(!X.Items)return[];let $=new Set;for(let Z of X.Items){let U=(Z.pk?.S||"").replace(`${cX}#`,"");if(U)$.add(U)}return Array.from($)}async hasMigrations(X){return await this.getLatestState(X)!==null}async deleteMigrationHistory(X){await this.ensureMigrationsTable();let $=await this.getHistory(X),Z=`${cX}#${X}`;for(let Y of $){let U=`${D5}#${String(Y.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:K9,Key:{pk:{S:Z},sk:{S:U}}})}console.log(`[Migration] Deleted migration history for ${X}`)}marshallState(X,$,Z){return{pk:{S:$},sk:{S:Z},tableName:{S:X.tableName},hash:{S:X.hash},definition:{S:JSON.stringify(X.definition)},appliedAt:{S:X.appliedAt},version:{N:String(X.version)}}}unmarshallState(X){return{tableName:X.tableName?.S||"",hash:X.hash?.S||"",definition:JSON.parse(X.definition?.S||"{}"),appliedAt:X.appliedAt?.S||"",version:Number(X.version?.N||0)}}}var K9="_qb_migrations",cX="MIGRATION",D5="VERSION",T6=()=>{};class N6{client;tracker;config;constructor(X){this.config=X,this.client=w6({region:X.region,endpoint:X.endpoint,credentials:X.credentials}),this.tracker=new P6(this.client)}async execute(X){let $={tableName:X.tableName,success:!0,operations:[]};if(X.operations.length===0)return this.log(`[Migration] No changes needed for ${X.tableName}`),$;this.log(`[Migration] Executing ${X.operations.length} operations for ${X.tableName}`);try{for(let Z of X.operations)await this.executeOperation(Z),$.operations.push(Z.type);this.log(`[Migration] Successfully applied ${$.operations.length} operations to ${X.tableName}`)}catch(Z){$.success=!1,$.error=Z.message,console.error(`[Migration] Failed to execute migration for ${X.tableName}:`,Z)}return $}async executeOperation(X){if(this.log(`[Migration] Executing ${X.type} on ${X.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${X.type}`,X.details);return}switch(X.type){case"CREATE_TABLE":await this.createTable(X.details.definition);break;case"DELETE_TABLE":await this.deleteTable(X.tableName);break;case"ADD_GSI":await this.addGSI(X.tableName,X.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(X.tableName,X.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(X.tableName,X.details.ttlAttribute,X.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(X.tableName,X.details.billingMode,X.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(X.tableName,X.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(X.tableName);break;default:throw Error(`Unknown migration operation type: ${X.type}`)}}async createTable(X){let $={TableName:X.tableName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:X.attributeDefinitions.map((Z)=>({AttributeName:Z.name,AttributeType:Z.type})),BillingMode:X.billingMode||"PAY_PER_REQUEST"};if(X.keySchema.sortKey)$.KeySchema.push({AttributeName:X.keySchema.sortKey,KeyType:"RANGE"});if(X.billingMode==="PROVISIONED"&&X.provisionedThroughput)$.ProvisionedThroughput={ReadCapacityUnits:X.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:X.provisionedThroughput.writeCapacityUnits};if(X.globalSecondaryIndexes&&X.globalSecondaryIndexes.length>0)$.GlobalSecondaryIndexes=X.globalSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:Z.keySchema.partitionKey,KeyType:"HASH"},...Z.keySchema.sortKey?[{AttributeName:Z.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}},...Z.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:Z.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:Z.provisionedThroughput.writeCapacityUnits}}:{}}));if(X.localSecondaryIndexes&&X.localSecondaryIndexes.length>0)$.LocalSecondaryIndexes=X.localSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:X.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:Z.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}}}));if(X.streamSpecification?.enabled)$.StreamSpecification={StreamEnabled:!0,StreamViewType:X.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${X.tableName}`),await this.client.createTable($),await this.waitForTableActive(X.tableName),X.ttlAttribute)await this.updateTTL(X.tableName,X.ttlAttribute,!0);this.log(`[Migration] Table created: ${X.tableName}`)}async deleteTable(X){this.log(`[Migration] Deleting table: ${X}`),await this.client.deleteTable(X),this.log(`[Migration] Table deleted: ${X}`)}async addGSI(X,$){this.log(`[Migration] Adding GSI ${$.indexName} to ${X}`);let Z=await this.client.describeTable(X),Y=new Set(Z.Table?.AttributeDefinitions?.map((Q)=>Q.AttributeName)||[]),U=[];if(!Y.has($.keySchema.partitionKey))U.push({AttributeName:$.keySchema.partitionKey,AttributeType:"S"});if($.keySchema.sortKey&&!Y.has($.keySchema.sortKey))U.push({AttributeName:$.keySchema.sortKey,AttributeType:"S"});let _={TableName:X,AttributeDefinitions:U.length>0?U:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:$.indexName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"},...$.keySchema.sortKey?[{AttributeName:$.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:$.projection.type,...$.projection.nonKeyAttributes?{NonKeyAttributes:$.projection.nonKeyAttributes}:{}},...$.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:$.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:$.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(_),await this.waitForGSIActive(X,$.indexName),this.log(`[Migration] GSI ${$.indexName} added to ${X}`)}async deleteGSI(X,$){this.log(`[Migration] Deleting GSI ${$} from ${X}`);let Z={TableName:X,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:$}}]};await this.executeUpdateTable(Z),this.log(`[Migration] GSI ${$} deleted from ${X}`)}async updateTTL(X,$,Z){this.log(`[Migration] Updating TTL on ${X}: ${Z?$:"disabled"}`);let Y={TableName:X,TimeToLiveSpecification:{Enabled:Z,AttributeName:$||"ttl"}};await this.executeUpdateTimeToLive(Y),this.log(`[Migration] TTL updated on ${X}`)}async updateBillingMode(X,$,Z){this.log(`[Migration] Updating billing mode on ${X} to ${$}`);let Y={TableName:X,BillingMode:$};if($==="PROVISIONED"&&Z)Y.ProvisionedThroughput={ReadCapacityUnits:Z.readCapacityUnits,WriteCapacityUnits:Z.writeCapacityUnits};await this.executeUpdateTable(Y),await this.waitForTableActive(X),this.log(`[Migration] Billing mode updated on ${X}`)}async enableStream(X,$){this.log(`[Migration] Enabling stream on ${X} with view type ${$}`);let Z={TableName:X,StreamSpecification:{StreamEnabled:!0,StreamViewType:$}};await this.executeUpdateTable(Z),await this.waitForTableActive(X),this.log(`[Migration] Stream enabled on ${X}`)}async disableStream(X){this.log(`[Migration] Disabling stream on ${X}`);let $={TableName:X,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable($),await this.waitForTableActive(X),this.log(`[Migration] Stream disabled on ${X}`)}async executeUpdateTable(X){await this.client.updateTable(X)}async executeUpdateTimeToLive(X){await this.client.updateTimeToLive(X)}async waitForTableActive(X,$=60){this.log(`[Migration] Waiting for table ${X} to become active...`);for(let Z=0;Z<$;Z++){try{let U=(await this.client.describeTable(X)).Table?.TableStatus;if(U==="ACTIVE")return;this.log(`[Migration] Table status: ${U}, waiting...`)}catch{}await new Promise((Y)=>setTimeout(Y,2000))}throw Error(`Table ${X} did not become active within ${$*2} seconds`)}async waitForGSIActive(X,$,Z=120){this.log(`[Migration] Waiting for GSI ${$} to become active...`);for(let Y=0;Y<Z;Y++){try{let _=(await this.client.describeTable(X)).Table?.GlobalSecondaryIndexes?.find((L)=>L.IndexName===$);if(_?.IndexStatus==="ACTIVE")return;let Q=_?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${Q}, waiting...`)}catch{}await new Promise((U)=>setTimeout(U,5000))}throw Error(`GSI ${$} did not become active within ${Z*5} seconds`)}async migrateModel(X){let $=t7(X),Z=null;try{let _=await this.client.describeTable($.tableName);if(_.Table)Z=this.tableInfoToDefinition(_.Table)}catch(_){if(!_.message?.includes("ResourceNotFoundException")&&!_.message?.includes("not found"))throw _}let Y=$2(Z,$),U=await this.execute(Y);if(U.success&&!this.config.dryRun)U.state=await this.tracker.recordMigration($.tableName,$);return U}async migrateModels(X){let $=[];for(let Z of X)try{let Y=await this.migrateModel(Z);$.push(Y)}catch(Y){$.push({tableName:Z.tableName||"unknown",success:!1,operations:[],error:Y.message})}return $}async getStatus(){let X=new Map,$=await this.tracker.listTrackedTables();for(let Z of $){let Y=await this.tracker.getLatestState(Z);X.set(Z,Y)}return X}tableInfoToDefinition(X){let $={partitionKey:"",sortKey:void 0};for(let U of X.KeySchema||[])if(U.KeyType==="HASH")$.partitionKey=U.AttributeName;else if(U.KeyType==="RANGE")$.sortKey=U.AttributeName;let Z=(X.AttributeDefinitions||[]).map((U)=>({name:U.AttributeName,type:U.AttributeType})),Y=(X.GlobalSecondaryIndexes||[]).map((U)=>{let _={partitionKey:"",sortKey:void 0};for(let Q of U.KeySchema||[])if(Q.KeyType==="HASH")_.partitionKey=Q.AttributeName;else if(Q.KeyType==="RANGE")_.sortKey=Q.AttributeName;return{indexName:U.IndexName,keySchema:_,projection:{type:U.Projection?.ProjectionType||"ALL",nonKeyAttributes:U.Projection?.NonKeyAttributes},provisionedThroughput:U.ProvisionedThroughput?{readCapacityUnits:U.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:U.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:X.TableName,keySchema:$,attributeDefinitions:Z,globalSecondaryIndexes:Y.length>0?Y:void 0,billingMode:X.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:X.ProvisionedThroughput?{readCapacityUnits:X.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:X.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:X.TimeToLiveDescription?.AttributeName,streamSpecification:X.StreamSpecification?{enabled:X.StreamSpecification.StreamEnabled,viewType:X.StreamSpecification.StreamViewType}:void 0}}log(...X){if(this.config.verbose||this.config.dryRun)console.log(...X)}}function Z2(X){return new N6(X)}async function dj(X,$){return Z2($).migrateModels(X)}var Y2=e(()=>{T6()});class S6{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(X,$,Z,Y){this.driver=X,this.client=$,this.tableName=Z,this.pkAttribute=Y.pkAttribute,this.skAttribute=Y.skAttribute,this.entityTypeAttr=Y.entityTypeAttribute,this.delimiter=Y.keyDelimiter}entity(X){return this._entityType=X,this}pk(X){return this._pkValue=X,this}get sk(){let X=this;return{equals($){return X._skCondition={type:"eq",value:$},X},beginsWith($){return X._skCondition={type:"begins_with",value:$},X},between($,Z){return X._skCondition={type:"between",value:$,value2:Z},X},lt($){return X._skCondition={type:"lt",value:$},X},lte($){return X._skCondition={type:"lte",value:$},X},gt($){return X._skCondition={type:"gt",value:$},X},gte($){return X._skCondition={type:"gte",value:$},X}}}index(X){return this._indexName=X,this}project(...X){return this._projectionAttrs.push(...X),this}filter(X,$,Z){return this._filterConditions.push({attribute:X,operator:$,value:Z}),this}where(X,$){return this.filter(X,"=",$)}whereIn(X,$){return this._filterConditions.push({attribute:X,operator:"IN",values:$}),this}limit(X){return this._limitValue=X,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(X){return this._startKey=X,this}toRequest(){let X={TableName:this.tableName};if(this._indexName)X.IndexName=this._indexName;let $=[],Z={},Y={},U=0;if(this._pkValue){let _=`#pk${U}`,Q=`:pk${U}`;Z[_]=this.pkAttribute,Y[Q]={S:this._pkValue},$.push(`${_} = ${Q}`),U++}if(this._skCondition){let _=`#sk${U}`;switch(Z[_]=this.skAttribute,this._skCondition.type){case"eq":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} = ${Q}`);break}case"begins_with":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`begins_with(${_}, ${Q})`);break}case"between":{let Q=`:sk${U}a`,L=`:sk${U}b`;Y[Q]={S:this._skCondition.value},Y[L]={S:this._skCondition.value2},$.push(`${_} BETWEEN ${Q} AND ${L}`);break}case"lt":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} < ${Q}`);break}case"lte":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} <= ${Q}`);break}case"gt":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} > ${Q}`);break}case"gte":{let Q=`:sk${U}`;Y[Q]={S:this._skCondition.value},$.push(`${_} >= ${Q}`);break}}U++}if($.length>0)X.KeyConditionExpression=$.join(" AND ");if(this._filterConditions.length>0){let _=[];for(let Q of this._filterConditions){let L=`#flt${U}`;if(Z[L]=Q.attribute,Q.operator==="IN"&&Q.values){let z=Q.values.map((j,E)=>`:flt${U}_${E}`);Q.values.forEach((j,E)=>{Y[`:flt${U}_${E}`]=this.driver.marshall({v:j}).v}),_.push(`${L} IN (${z.join(", ")})`)}else{let z=`:flt${U}`;Y[z]=this.driver.marshall({v:Q.value}).v,_.push(`${L} ${Q.operator} ${z}`)}U++}X.FilterExpression=_.join(" AND ")}if(this._projectionAttrs.length>0){let _=[];for(let Q of this._projectionAttrs){let L=`#proj${U}`;Z[L]=Q,_.push(L),U++}X.ProjectionExpression=_.join(", ")}if(Object.keys(Z).length>0)X.ExpressionAttributeNames=Z;if(Object.keys(Y).length>0)X.ExpressionAttributeValues=Y;if(this._limitValue!==void 0)X.Limit=this._limitValue;if(X.ScanIndexForward=this._scanForward,this._consistentRead)X.ConsistentRead=!0;if(this._startKey)X.ExclusiveStartKey=this.driver.marshall(this._startKey);return X}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let X=this.toRequest();return((this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X)).Items??[]).map((Y)=>this.driver.unmarshall(Y))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let X=[],$;do{if($)this._startKey=$;let Z=this.toRequest(),U=this._pkValue!==void 0?await this.client.query(Z):await this.client.scan(Z),_=(U.Items??[]).map((Q)=>this.driver.unmarshall(Q));X.push(..._),$=U.LastEvaluatedKey?this.driver.unmarshall(U.LastEvaluatedKey):void 0}while($);return X}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let X=this.toRequest();return X.Select="COUNT",(this._pkValue!==void 0?await this.client.query(X):await this.client.scan(X)).Count??0}}class i1{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(X){let $={region:X.region,tableName:X.table,endpoint:X.endpoint,credentials:X.credentials};return this.driver=bX($),this.tableName=X.table,this.pkAttribute=X.pkAttribute??"pk",this.skAttribute=X.skAttribute??"sk",this.entityTypeAttr=X.entityTypeAttribute??"_et",this.delimiter=X.keyDelimiter??"#",this}setClient(X){return this.client=X,this}registerEntity(X){if(this.entityMappings.set(X.entityType,X),this.driver)this.driver.registerEntity(X);return this}entity(X){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new S6(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(X)}async batchWrite(X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let $=[];for(let Z of X)if(Z.put){let Y={...Z.put.item,[this.entityTypeAttr]:Z.put.entity};$.push({PutRequest:{Item:this.driver.marshall(Y)}})}else if(Z.delete)$.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}});if($.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:$}})}async transactWrite(X){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let $=[];for(let Z of X)if(Z.put){let Y={...Z.put.item,[this.entityTypeAttr]:Z.put.entity},U={Put:{TableName:this.tableName,Item:this.driver.marshall(Y)}};if(Z.put.condition)U.Put.ConditionExpression=Z.put.condition;$.push(U)}else if(Z.update){let Y={[this.pkAttribute]:Z.update.pk};if(Z.update.sk)Y[this.skAttribute]=Z.update.sk;let U=[],_={},Q={},L=0;if(Z.update.set){let z=[];for(let[j,E]of Object.entries(Z.update.set)){let V=`#set${L}`,G=`:set${L}`;_[V]=j,Q[G]=this.driver.marshall({v:E}).v,z.push(`${V} = ${G}`),L++}if(z.length>0)U.push(`SET ${z.join(", ")}`)}if(Z.update.add){let z=[];for(let[j,E]of Object.entries(Z.update.add)){let V=`#add${L}`,G=`:add${L}`;_[V]=j,Q[G]={N:String(E)},z.push(`${V} ${G}`),L++}if(z.length>0)U.push(`ADD ${z.join(", ")}`)}if(Z.update.remove&&Z.update.remove.length>0){let z=[];for(let j of Z.update.remove){let E=`#rem${L}`;_[E]=j,z.push(E),L++}U.push(`REMOVE ${z.join(", ")}`)}$.push({Update:{TableName:this.tableName,Key:this.driver.marshall(Y),UpdateExpression:U.join(" "),ExpressionAttributeNames:_,ExpressionAttributeValues:Q}})}else if(Z.delete){let Y={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}};if(Z.delete.condition)Y.Delete.ConditionExpression=Z.delete.condition;$.push(Y)}else if(Z.conditionCheck)$.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.conditionCheck.pk,[this.skAttribute]:Z.conditionCheck.sk}),ConditionExpression:Z.conditionCheck.condition}});if($.length>0)await this.client.transactWriteItems({TransactItems:$})}getDriver(){return this.driver}}function pj(){return new i1}var U2,_2=e(()=>{a7(),Y2(),T6(),U2=new i1});class x6{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!M5(X))return!0;return H5(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=M5(Z)?H5(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class B6{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function l2(X,$){this[X]=A4.bind(null,$)}class O1{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!C5(X))return!0;return w5(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=C5(Z)?w5(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class J1{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function s2(X,$={}){let Y=Object.keys($).sort().map((U)=>`${U}:${$[U]}`).join("|");return Y?`${X}:${Y}`:X}function o2(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function r2(X){return X.getStats().size*2}function l1(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&C0($[0])&&"id"in $[0]&&$[0].id===3&&C0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(C0($)&&C0(X)&&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 X;if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray($)&&Array.isArray(X)){if(C0(X)&&"arr"in X&&Array.isArray(X.arr)&&C0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&C0($[0])&&C0(X[0])){let Y=[...$];for(let U of X)if(C0(U)&&"name"in U){if(!Y.find((Q)=>C0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(C0(U)&&"path"in U){if(!Y.find((Q)=>C0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>B8(_,U)))Y.push(U);return Y}if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}if(!C0($)||!C0(X))return $;let Z={...X};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let U=$[Y];if(U===null||U===void 0)continue;else if(C0(U)&&C0(Z[Y]))Z[Y]=l1(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&C0(U[0])&&C0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(C0(Q)&&"name"in Q){if(!_.find((z)=>C0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(C0(Q)&&"path"in Q){if(!_.find((z)=>C0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>B8(L,Q)))_.push(Q);Z[Y]=_}else if(U.every((_)=>typeof _==="string")&&Z[Y].every((_)=>typeof _==="string")){let _=[...U];for(let Q of Z[Y])if(!_.includes(Q))_.push(Q);Z[Y]=_}else Z[Y]=U;else Z[Y]=U}return Z}function B8(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!B8(X[Z],$[Z]))return!1;return!0}if(C0(X)&&C0($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!B8(X[U],$[U]))return!1}return!0}return!1}function C0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function a2(X,$){if(!k6(X))return null;try{let Z=await import(X),Y=Z.default||Z;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return l1($,Y)}catch{return null}}catch{return null}}async function t2({name:X="",cwd:$,defaultConfig:Z}){let Y=$||F1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],_=[`${X}.config`,`.${X}.config`,X,`.${X}`];for(let Q of _)for(let L of U){let z=k8(Y,`${Q}${L}`),j=await a2(z,Z);if(j!==null)return j}try{let Q=k8(Y,"package.json");if(k6(Q)){let z=(await import(Q))[X];if(z&&typeof z==="object"&&!Array.isArray(z))try{return l1(Z,z)}catch{}}}catch{}return Z}function e2(X,$={}){let Z=A8.cwd();while(Z.includes("storage"))Z=T5(Z,"..");let Y=T5(Z,X||"");if($?.relative)return J2(A8.cwd(),Y);return Y}async function X4(){try{let X=await t2({name:"clarity",defaultConfig:J8,cwd:A8.cwd(),endpoint:"",headers:{}});return{...J8,...X}}catch{return J8}}function P0(){if(P9.env.NODE_ENV==="test"||P9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $4(){if(P9.env.NODE_ENV==="test"||P9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P9<"u"){let X=P9.type;if(X==="renderer"||X==="worker")return!1;return!!(P9.versions&&(P9.versions.node||P9.versions.bun))}return!1}class y6{async format(X){let $=await $4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:GX.pid,hostname:$(),environment:GX.env.NODE_ENV||"development",platform:GX.platform,version:GX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:GX.env.NODE_ENV||GX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class y8{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(X,$={}){this.name=X,this.config={...K1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new y6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??b0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...W8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...W8};return{...W8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:K1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await R2(this.config.logDirectory,k5.F_OK|k5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await D2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:h9.from(X);try{if(!JZ(this.currentLogFile))await WZ(this.currentLogFile,"",{mode:420});if(U=A5(this.currentLogFile,"a",420),K2(U,z,{flag:"a"}),S5(U),U!==void 0)OZ(U),U=void 0;if((await jX(this.currentLogFile)).size===0){if(await WZ(this.currentLogFile,z,{flag:"w",mode:420}),(await jX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{OZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 EX(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 EX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return EX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(P0())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.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 Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return FZ(16).toString("hex")}generateKey(){return FZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=FZ(16),Y=W2("aes-256-gcm",$,Z),U=h9.concat([Y.update(X,"utf8"),Y.final()]),_=Y.getAuthTag();return{encrypted:h9.concat([Z,U,_]),iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=B5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(h9.from(h9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(P0())return;let X=await jX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await f$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await jX(Z).catch(()=>null))try{if(await x5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await g$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await WZ(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 U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await jX(Z).catch(()=>null))await x5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await f$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await g$(EX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=N5(X),Y=I2($),U=B5();await M2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);await this.writeToFile(Y),console.log(Y)}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 Z={timestamp:new Date,level:X,message:$,name:this.name};this.logBuffer.push(Z)}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(X)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(X){return{debug:0,info:1,success:2,warning:3,error:4}[X]}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),JZ(this.currentLogFile))try{let X=A5(this.currentLogFile,"r+");S5(X),OZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!P0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await f$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await g$(EX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.fancy?R0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=b0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${R0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}async log(X,$,...Z){let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);if(this.fancy&&!P0()){let j=a6[X],E=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",V;switch(X){case"debug":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:R0.gray(Q),level:X}),console.error(V);break;case"info":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.error(V);break;case"success":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:R0.green(Q),level:X}),console.error(V);break;case"warning":V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.warn(V);break;case"error":if(V=this.formatConsoleMessage({timestamp:U,icon:j,tag:E,message:Q,level:X}),console.error(V),L){let G=L.split(`
7
+ `);for(let J of G)if(J.trim()&&!J.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:R0.gray(` ${J}`),level:X,showTimestamp:!1}))}break}}else if(!P0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}if(!this.shouldLog(X))return;let z=`${_} ${this.environment}.${X.toUpperCase()}: ${Q}
8
+ `;if(L)z+=`${L}
9
+ `;z=z.replace(this.ANSI_PATTERN,""),await this.writeToFile(z)}time(X){let $=performance.now();if(this.fancy&&!P0()){let Z=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:R0.blue("\u25D0"),tag:Z,message:`${R0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),j=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)j+=` ${JSON.stringify(Z)}`;if(j+=`
10
+ `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!P0()){let E=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:R0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!P0())console.error(j.trim());await this.writeToFile(j)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new y8($,{...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(Z),Z}createReadStream(){if(P0())throw Error("createReadStream is not supported in browser environments");if(!JZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return N5(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){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 Z=this.keys.get(this.currentKeyId);try{let Y=h9.isBuffer(X)?X:h9.from(X,"base64"),U=Y.slice(0,16),_=Y.slice(-16),Q=Y.slice(16,-16),L=V2("aes-256-gcm",Z,U);return L.setAuthTag(_),h9.concat([L.update(Q),L.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P0()}isServerMode(){return!P0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}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(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($);if(this.fancy&&!P0()){let _=X.split(`
11
+ `),Q=Math.max(..._.map((E)=>E.length))+2,L=`\u250C${"\u2500".repeat(Q)}\u2510`,z=`\u2514${"\u2500".repeat(Q)}\u2518`,j=_.map((E)=>{let V=" ".repeat(Q-E.length-2);return`\u2502 ${E}${V} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Z,message:R0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Z,message:R0.cyan(L)})),j.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:Z,message:R0.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Z,message:R0.cyan(z),showTimestamp:!1}))}else if(!P0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
12
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt(X){if(P0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${R0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();b0.stdin.removeListener("data",Z);try{if(typeof b0.stdin.setRawMode==="function")b0.stdin.setRawMode(!1)}catch{}b0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof b0.stdin.setRawMode==="function")b0.stdin.setRawMode(!0)}catch{}b0.stdin.resume(),b0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let Q=/%([sdijfo%])/g,L=0;if(Z=X.replace(Q,(z,j)=>{if(j==="%")return"%";if(L>=$.length)return z;let E=$[L++];switch(j){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return z}}),L<$.length)Z+=` ${$.slice(L).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}if(this.fancy&&!P0()){let Q=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",L=R0.blue("\u25D0");console.error(`${L} ${Q} ${R0.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Z}
13
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress(X,$=""){if(!this.enabled||!this.fancy||P0()||X<=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 Z=20;return this.activeProgressBar={total:X,current:0,message:$,barLength:Z,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Q,L)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(X,Q)),L!==void 0)this.activeProgressBar.message=L;let z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,z)},finish:(Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Q!==void 0)this.activeProgressBar.message=Q;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Q,L="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P0())return;b0.stdout.write(`${"\r".padEnd(b0.stdout.columns||80)}\r`),this.log(L,Q),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(X,$=!1){if(!this.enabled||!this.fancy||P0()||!b0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=R0.green("\u2501".repeat(Y)),Q=R0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=$||Z===100?R0.green("\u2713"):R0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${R0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=b0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,b0.stdout.write(X.lastRenderedLine),$)b0.stdout.write(`
14
+ `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||P0()||!b0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(P0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await f$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=EX(this.config.logDirectory,Y);if(X.before)try{if((await jX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await g$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function O8(X,$){if(Array.isArray($)&&Array.isArray(X)&&$.length===2&&X.length===2&&O0($[0])&&"id"in $[0]&&$[0].id===3&&O0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(O0($)&&O0(X)&&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 X;if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray($)&&Array.isArray(X)){if(O0(X)&&"arr"in X&&Array.isArray(X.arr)&&O0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&X.length>0&&O0($[0])&&O0(X[0])){let Y=[...$];for(let U of X)if(O0(U)&&"name"in U){if(!Y.find((Q)=>O0(Q)&&("name"in Q)&&Q.name===U.name))Y.push(U)}else if(O0(U)&&"path"in U){if(!Y.find((Q)=>O0(Q)&&("path"in Q)&&Q.path===U.path))Y.push(U)}else if(!Y.some((_)=>h8(_,U)))Y.push(U);return Y}if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}if(!O0($)||!O0(X))return $;let Z={...X};for(let Y in $)if(Object.prototype.hasOwnProperty.call($,Y)){let U=$[Y];if(U===null||U===void 0)continue;else if(O0(U)&&O0(Z[Y]))Z[Y]=O8(Z[Y],U);else if(Array.isArray(U)&&Array.isArray(Z[Y]))if(U.length>0&&Z[Y].length>0&&O0(U[0])&&O0(Z[Y][0])){let _=[...U];for(let Q of Z[Y])if(O0(Q)&&"name"in Q){if(!_.find((z)=>O0(z)&&("name"in z)&&z.name===Q.name))_.push(Q)}else if(O0(Q)&&"path"in Q){if(!_.find((z)=>O0(z)&&("path"in z)&&z.path===Q.path))_.push(Q)}else if(!_.some((L)=>h8(L,Q)))_.push(Q);Z[Y]=_}else if(U.every((_)=>typeof _==="string")&&Z[Y].every((_)=>typeof _==="string")){let _=[...U];for(let Q of Z[Y])if(!_.includes(Q))_.push(Q);Z[Y]=_}else Z[Y]=U;else Z[Y]=U}return Z}function s1(X,$,Z="replace"){if($===null||$===void 0)return X;if(Array.isArray($))return Z==="replace"?$:O8(X,$);if(Array.isArray(X))return Z==="replace"?$:O8(X,$);if(!O0($)||!O0(X))return $;let Y={...X};for(let U of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],Q=Y[U];if(_===null||_===void 0)continue;if(Array.isArray(_)||Array.isArray(Q))if(Z==="replace")Y[U]=_;else Y[U]=O8(Q,_);else if(O0(_)&&O0(Q))Y[U]=s1(Q,_,Z);else Y[U]=_}return Y}function h8(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!h8(X[Z],$[Z]))return!1;return!0}if(O0(X)&&O0($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!h8(X[U],$[U]))return!1}return!0}return!1}function O0(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}async function r$(X,$,Z="replace"){if(!A6(X))return null;try{let Y=await import(X),U=Y.default||Y;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return s1($,U,Z)}catch{return null}}catch{return null}}function Z4(X,$,Z=!1){if(!X)return $;let Y=X.toUpperCase().replace(/-/g,"_"),U={...$};function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),J=`${Y}_${V.map(G).join("_")}`,W=`${Y}_${V.map((F)=>F.toUpperCase()).join("_")}`;if(Z)g0.info(`Checking environment variable ${J} for config ${X}.${V.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))z[j]=_(E,V);else{let F=P$.env[J]||P$.env[W];if(F!==void 0){if(Z)g0.info(`Using environment variable ${F?J:W} for config ${X}.${V.join(".")}`);if(typeof E==="number")z[j]=Number(F);else if(typeof E==="boolean")z[j]=F.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(F);if(Array.isArray(K))z[j]=K;else z[j]=F.split(",").map((D)=>D.trim())}catch{z[j]=F.split(",").map((K)=>K.trim())}else z[j]=F}}}return z}return _(U)}async function Y4({name:X="",alias:$,cwd:Z,configDir:Y,defaultConfig:U,verbose:_=!1,checkEnv:Q=!0,arrayStrategy:L="replace"}){let z=Q&&typeof U==="object"&&U!==null&&!Array.isArray(U)?Z4(X,U,_):U,j=Z||P$.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(_)g0.info(`Loading configuration for "${X}"${$?` (alias: "${$}")`:""} from ${j}`);let V=[X,`.${X}`].filter(Boolean),G=[`${X}.config`,`.${X}.config`].filter(Boolean),J=$?[$,`.${$}`]:[],W=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([j,u0(j,"config"),u0(j,".config"),Y?u0(j,Y):void 0].filter(Boolean)));for(let K of F){if(_)g0.info(`Searching for configuration in: ${K}`);let w=[u0(j,"config"),u0(j,".config")].concat(Y?[u0(j,Y)]:[]).includes(K)?[...V,...G,...J,...W]:[...G,...V,...W,...J];for(let T of w)for(let N of E){let q=u0(K,`${T}${N}`),H=await r$(q,z,L);if(H!==null){if(_)g0.success(`Configuration loaded from: ${q}`);return H}}}if(X){let K=u0(GZ(),".config",X),D=["config",`${X}.config`];if($)D.push(`${$}.config`);if(_)g0.info(`Checking user config directory: ${K}`);for(let w of D)for(let T of E){let N=u0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user config directory: ${N}`);return q}}}if(X){let K=u0(GZ(),".config"),D=[`.${X}.config`];if($)D.push(`.${$}.config`);if(_)g0.info(`Checking user config directory for dotfile configs: ${K}`);for(let w of D)for(let T of E){let N=u0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user config directory dotfile: ${N}`);return q}}}if(X){let K=GZ(),D=[`.${X}.config`,`.${X}`];if($)D.push(`.${$}.config`),D.push(`.${$}`);if(_)g0.info(`Checking user home directory for dotfile configs: ${K}`);for(let w of D)for(let T of E){let N=u0(K,`${w}${T}`),q=await r$(N,z,L);if(q!==null){if(_)g0.success(`Configuration loaded from user home directory: ${N}`);return q}}}try{let K=u0(j,"package.json");if(A6(K)){let D=await import(K),w=D[X];if(!w&&$){if(w=D[$],w&&_)g0.success(`Using alias "${$}" configuration from package.json`)}if(w&&typeof w==="object"&&!Array.isArray(w))try{if(_)g0.success(`Configuration loaded from package.json: ${w===D[X]?X:$}`);return s1(z,w,L)}catch(T){if(_)g0.warn("Failed to merge package.json config:",T)}}}catch(K){if(_)g0.warn("Failed to load package.json:",K)}if(_)g0.info(`No configuration found for "${X}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return z}function U4(X,$={}){let Z=S8.cwd();while(Z.includes("storage"))Z=P5(Z,"..");let Y=P5(Z,X||"");if($?.relative)return F2(S8.cwd(),Y);return Y}async function _4(){try{let X=await Y4({name:"clarity",alias:"logging",defaultConfig:V8,cwd:S8.cwd()});return{...V8,...X||{}}}catch{return V8}}function N0(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Q4(){if(T9.env.NODE_ENV==="test"||T9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof T9<"u"){let X=T9.type;if(X==="renderer"||X==="worker")return!1;return!!(T9.versions&&(T9.versions.node||T9.versions.bun))}return!1}class h6{async format(X){let $=await Q4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:JX.pid,hostname:$(),environment:JX.env.NODE_ENV||"development",platform:JX.platform,version:JX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JX.env.NODE_ENV||JX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class v8{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(X,$={}){this.name=X,this.config={...R1},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new h6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??z0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...I8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...I8};return{...I8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:R1.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await P2(this.config.logDirectory,b5.F_OK|b5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await T2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:R9.from(X);try{if(!d$(this.currentLogFile))await KZ(this.currentLogFile,"",{mode:420});if(U=v5(this.currentLogFile,"a",420),q2(U,z,{flag:"a"}),h5(U),U!==void 0)IZ(U),U=void 0;if((await FX(this.currentLogFile)).size===0){if(await KZ(this.currentLogFile,z,{flag:"w",mode:420}),(await FX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{IZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 OX(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 OX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return OX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.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 Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return VZ(16).toString("hex")}generateKey(){return VZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=VZ(16),Y=H2("aes-256-gcm",$,Z),U=R9.isBuffer(X)?X:R9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=R9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=g5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(R9.from(R9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let X=await FX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await p$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await FX(Z).catch(()=>null))try{if(await f5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await c$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await KZ(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 U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await FX(Z).catch(()=>null))await f5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await p$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await c$(OX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=y5(X),Y=w2($),U=g5();await A2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),d$(this.currentLogFile))try{let X=v5(this.currentLogFile,"r+");h5(X),IZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await p$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await c$(OX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?j0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let X=typeof z0.env.NO_COLOR<"u",$=z0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof z0.stderr<"u"&&z0.stderr.isTTY||typeof z0.stdout<"u"&&z0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=z0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${j0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=j0.underline(j0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>j0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>j0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>j0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>j0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>j0.strikethrough(Y)),$}supportsHyperlinks(){if(N0())return!1;let X=z0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=z0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(N2($)||$.startsWith("./")||$.startsWith("../"))$=S2($);else return null;return d$($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":t6[X],G=this.options.showTags!==!1&&this.name?j0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:j0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:j0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
15
+ `);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:j0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}if(!this.shouldLog(X))return;let E=`${_} ${this.environment}.${X.toUpperCase()}: ${j}
16
+ `;if(L)E+=`${L}
17
+ `;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(L,z)=>{},finish:(L)=>{},interrupt:(L,z)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&z0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!N0()&&z0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,z="info")=>{if(!N0()&&z0.stdout.isTTY)z0.stdout.write(`
18
+ `);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&z0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?j0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":j0.blue("\u25D0"),tag:Z,message:`${j0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),j=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)j+=` ${JSON.stringify(Z)}`;if(j+=`
19
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?j0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":j0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!N0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new v8($,{...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(Z),Z}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!d$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return y5(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){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 Z=this.keys.get(this.currentKeyId);try{let Y=R9.isBuffer(X)?X:R9.from(X,"base64"),U=Y.subarray(0,16),_=Y.subarray(Y.length-16),Q=Y.subarray(16,Y.length-16),L=C2("aes-256-gcm",Z,U);L.setAuthTag(_);let z=L.update(Q),j=L.final(),E=z.length+j.length,V=R9.allocUnsafe(E);return z.copy(V,0),j.copy(V,z.length),V.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}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(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($),{consoleText:U,fileText:_}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let L=U.split(`
20
+ `),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:j0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:j0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:j0.cyan(E),showTimestamp:!1}))}else if(!N0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
21
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${j0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();z0.stdin.removeListener("data",Z);try{if(typeof z0.stdin.setRawMode==="function")z0.stdin.setRawMode(!1)}catch{}z0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof z0.stdin.setRawMode==="function")z0.stdin.setRawMode(!0)}catch{}z0.stdin.resume(),z0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let z=/%([sdijfo%])/g,j=0;if(Z=X.replace(z,(E,V)=>{if(V==="%")return"%";if(j>=$.length)return E;let G=$[j++];switch(V){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return E}}),j<$.length)Z+=` ${$.slice(j).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:U}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?j0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${j0.blue("\u25D0")} `;console.error(`${j}${z} ${j0.cyan(Y)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
22
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!z0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=j0.green("\u2501".repeat(Y)),Q=j0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?j0.green("\u2713"):j0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${j0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=z0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,z0.stdout.write(X.lastRenderedLine),$)z0.stdout.write(`
23
+ `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||N0()||!z0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await p$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=OX(this.config.logDirectory,Y);if(X.before)try{if((await FX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await c$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function v6(X,$={}){let{maxRetries:Z=3,retryDelay:Y=1000,isRetryable:U=()=>!0,fallback:_}=$,Q=Error("Unknown error occurred");for(let L=0;L<=Z;L++)try{return await X()}catch(z){if(Q=z instanceof Error?z:Error(String(z)),L===Z||!U(Q))break;if(Y>0)await new Promise((j)=>setTimeout(j,Y))}if(_!==void 0)return _;throw Q instanceof Error?Q:Error(`Unknown error: ${String(Q)}`)}function b6(X){return X instanceof $9}function z4(X){return X instanceof K8}function L4(X){if(b6(X))return X.code==="FILE_SYSTEM_ERROR"||X.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Z)=>X.message.toLowerCase().includes(Z.toLowerCase()))}class $Z{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(X,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(X.toLowerCase()),parse:(X)=>{let $=X.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(X,$)=>$==="number"||!Number.isNaN(Number(X))&&!Number.isNaN(Number.parseFloat(X)),parse:(X)=>{let $=Number(X);if(Number.isNaN($))throw TypeError(`Cannot parse "${X}" as number`);return $}},{name:"array",canParse:(X,$)=>$==="array"||X.startsWith("[")||X.includes(","),parse:(X)=>{try{let $=JSON.parse(X);if(Array.isArray($))return $}catch{}return X.split(",").map(($)=>$.trim())}},{name:"json",canParse:(X,$)=>$==="object"||(X.startsWith("{")&&X.endsWith("}")||X.startsWith("[")&&X.endsWith("]")),parse:(X)=>{try{return JSON.parse(X)}catch($){throw Error(`Cannot parse "${X}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(X,$,Z={}){let{prefix:Y,useCamelCase:U=!0,useBackwardCompatibility:_=!0,customParsers:Q={},verbose:L=!1,trackPerformance:z=!0}=Z,j=async()=>{if(!X)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix(X),V={...$};return this.processObject(V,[],E,{useCamelCase:U,useBackwardCompatibility:_,customParsers:Q,verbose:L,configName:X}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return N$.track("applyEnvironmentVariables",j,{configName:X});return j()}generateEnvPrefix(X){return X.toUpperCase().replace(/-/g,"_")}formatEnvKey(X,$){if(!$)return X.toUpperCase();return X.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=Q.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),z=`${Z}_${L.join("_")}`,j=Y.useBackwardCompatibility?`${Z}_${Q.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.processObject(_,Q,Z,Y);else{let E=m$.env[z]||(j?m$.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=m$.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof R8)throw V;throw p9.envVar(z,E,typeof _,Y.configName)}}}}}parseEnvironmentValue(X,$,Z,Y,U){for(let[_,Q]of Object.entries(Y))try{return Q(X)}catch{continue}for(let _ of this.defaultParsers)if(_.canParse(X,$))try{return _.parse(X)}catch{throw p9.envVar(Z,X,`${$} (via ${_.name} parser)`,U)}return X}getEnvironmentVariables(X){let $={},Z=X.toUpperCase();for(let[Y,U]of Object.entries(m$.env))if(Y.startsWith(Z)&&U!==void 0)$[Y]=U;return $}validateEnvironmentVariable(X,$,Z){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(X))Y.push(`Environment variable key "${X}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(X,$,Z,{})}catch(U){Y.push(`Cannot parse value "${$}" as ${Z}: ${U}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(X,$,Z={}){let{prefix:Y,format:U="text"}=Z,_=Y||this.generateEnvPrefix(X),Q=[];switch(this.extractEnvVarInfo($,[],_,Q),U){case"markdown":return this.formatAsMarkdown(Q,X);case"json":return JSON.stringify(Q,null,2);default:return this.formatAsText(Q,X)}}extractEnvVarInfo(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=`${Z}_${Q.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.extractEnvVarInfo(_,Q,Z,Y);else Y.push({key:L,type:Array.isArray(_)?"array":typeof _,description:`Configuration for ${Q.join(".")}`,example:this.generateExample(_)})}}generateExample(X){if(Array.isArray(X))return JSON.stringify(X);if(typeof X==="object"&&X!==null)return JSON.stringify(X);return String(X)}formatAsText(X,$){let Z=`Environment Variables for ${$}:
24
24
 
25
- `;for(let _ of $)X+=`${_.key}
26
- `,X+=` Type: ${_.type}
27
- `,X+=` Description: ${_.description}
28
- `,X+=` Example: ${_.example}
25
+ `;for(let Y of X)Z+=`${Y.key}
26
+ `,Z+=` Type: ${Y.type}
27
+ `,Z+=` Description: ${Y.description}
28
+ `,Z+=` Example: ${Y.example}
29
29
 
30
- `;return X}formatAsMarkdown($,Z){let X=`# Environment Variables for ${Z}
30
+ `;return Z}formatAsMarkdown(X,$){let Z=`# Environment Variables for ${$}
31
31
 
32
- `;X+=`| Variable | Type | Description | Example |
33
- `,X+=`|----------|------|-------------|----------|
34
- `;for(let _ of $)X+=`| \`${_.key}\` | ${_.type} | ${_.description} | \`${_.example}\` |
35
- `;return X}}function I4($,Z){let X=S2("process");if(typeof X>"u"||!X.env)return Z;let _=X.env[$];return _!==void 0?_:Z}function F2($,Z,X={}){return z2($,Z,X,new WeakMap)}function z2($,Z,X,_){let{arrayMergeMode:L="replace",skipNullish:j=!1,customMerger:Y}=X;if(Z===null||Z===void 0)return j?$:Z;if(Y){let z=Y($,Z);if(z!==void 0)return z}if(Array.isArray(Z)||Array.isArray($))return U2($,Z,L,_);if(!a0(Z)||!a0($))return Z;return M4($,Z,X,_)}function U2($,Z,X,_){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(X){case"replace":return Z;case"concat":return W4($,Z);case"smart":return D4($,Z,_);default:return Z}return Z}function W4($,Z){let X=[...Z];for(let _ of $)if(!X.some((L)=>l5(L,_)))X.push(_);return X}function D4($,Z,X){if(Z.length===0)return $;if($.length===0)return Z;if(a0(Z[0])&&a0($[0]))return S4($,Z,X);if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}function S4($,Z,X){let _=[...Z];for(let L of $){if(!a0(L)){_.push(L);continue}let j=["id","name","key","path","type"],Y=!1;for(let z of j)if(z in L){if(_.find((E)=>a0(E)&&(z in E)&&E[z]===L[z])){Y=!0;break}}if(!Y)_.push(L)}return _}function M4($,Z,X,_){let L=Z;if(a0(L)&&_.has(L))return _.get(L);let j={...$};if(a0(L))_.set(L,j);for(let Y in L){if(!Object.prototype.hasOwnProperty.call(L,Y))continue;let z=L[Y],F=j[Y];if(X.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){j[Y]=z;continue}if(a0(z)&&a0(F))j[Y]=z2(F,z,X,_);else if(Array.isArray(z)||Array.isArray(F))j[Y]=U2(F,z,X.arrayMergeMode||"smart",_);else j[Y]=z}return j}function MZ($,Z,X="replace"){return F2($,Z,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function l5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!l5($[X],Z[X]))return!1;return!0}if(a0($)&&a0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!l5($[L],Z[L]))return!1}return!0}return!1}function a0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class u${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,X={}){let{arrayStrategy:_="replace",useCache:L=!0,cacheTtl:j,trackPerformance:Y=!0,verbose:z=!1}=X;if(L){let E=Q8.getWithFileCheck("file",$);if(E){if(z)console.log(`Configuration loaded from cache: ${$}`);return E}}let F=async()=>{if(!D1($))return null;try{let E=`?t=${Date.now()}`,U=await import($+E),V=U.default||U,Q="default"in U,O=Object.keys(U).length>0;if(!Q&&!O)throw new P8($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new P8($,Error("Configuration must export a valid object"),"unknown");let C={config:MZ(Z,V,_),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(L)Q8.setWithFileCheck("file",C,$,j);return C}catch(E){throw E instanceof Error?B9.configLoad($,E):B9.configLoad($,Error(String(E)))}};if(Y)return $1.track("loadFromPath",F,{path:$});return F()}async tryLoadFromPaths($,Z,X={}){for(let _ of $)try{let L=await this.loadFromPath(_,Z,X);if(L)return L}catch(L){if(L instanceof Error&&L.name==="ConfigLoadError")throw L;if(X.verbose)console.warn(`Failed to load config from ${_}:`,L)}return null}generateConfigPaths($,Z,X){let _=this.generateNamePatterns($,X),L=[];for(let j of _)for(let Y of this.extensions)L.push(F5(Z,`${j}${Y}`));return L}generateNamePatterns($,Z){let X=[];if(X.push("config",".config"),$)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(Z){if(X.push(Z,`.${Z}.config`,`${Z}.config`,`.${Z}`),$)X.push(`${$}.${Z}.config`,`.${$}.${Z}.config`)}return X.filter(Boolean)}checkFileAccess($){return j2(async()=>{return D1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,X){let _=[];if(!D1($))return _;if(Z||X){let L=this.generateNamePatterns(Z||"",X);for(let j of L)for(let Y of this.extensions){let z=F5($,`${j}${Y}`);if(await this.checkFileAccess(z))_.push(z)}}else try{let{readdirSync:L}=await import("fs"),j=L($);for(let Y of j)if(this.looksLikeConfigFile(Y)){let z=F5($,Y);if(await this.checkFileAccess(z))_.push(z)}}catch{return[]}return _}looksLikeConfigFile($){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((X)=>X.test($))}async validateConfigFile($){let Z=[];try{if(!D1($))return Z.push("Configuration file does not exist"),Z;let X=await import($),_=X.default||X;if(_===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof _!=="object"||_===null)Z.push("Configuration must be an object");else if(Array.isArray(_))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:L}=await import("fs"),j=L($,"utf8");JSON.parse(j)}catch(L){Z.push(`Invalid JSON syntax: ${L}`)}}catch(X){Z.push(`Failed to load configuration file: ${X}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let X=new Map;return await Promise.allSettled($.map(async(_)=>{try{let L=await this.loadFromPath(_,{},Z);if(L)X.set(_,L.config)}catch(L){if(Z.verbose)console.warn(`Failed to preload ${_}:`,L)}})),X}}class RZ{async validateConfiguration($,Z,X={}){let{stopOnFirstError:_=!1,validateRequired:L=!0,validateTypes:j=!0,customRules:Y=[],trackPerformance:z=!0,verbose:F=!1}=X,E=async()=>{let U=[],V=[],Q={stopOnFirstError:_,validateRequired:L,validateTypes:j,customRules:Y,trackPerformance:z,verbose:F};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,Q);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...Y],Q);else return this.validateWithJSONSchema($,Z,Q)}catch(O){return U.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:U,warnings:V}}};if(z)return await $1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,Z,X){try{if(!f_(Z))throw new T8(Z,[{path:"",message:"Schema file does not exist"}]);let _=await import(Z),L=_.default||_;if(Array.isArray(L))return this.validateWithRules($,L,X);else return this.validateWithJSONSchema($,L,X)}catch(_){throw new T8(Z,[{path:"",message:`Failed to load schema: ${_}`}])}}validateWithJSONSchema($,Z,X){let _=[],L=[];return this.validateObjectAgainstSchema($,Z,"",_,L,X),{isValid:_.length===0,errors:_,warnings:L}}validateObjectAgainstSchema($,Z,X,_,L,j){if(j.validateTypes&&Z.type){let Y=Array.isArray($)?"array":typeof $,z=Array.isArray(Z.type)?Z.type:[Z.type];if(!z.includes(Y)){if(_.push({path:X,message:`Expected type ${z.join(" or ")}, got ${Y}`,expected:z.join(" or "),actual:Y,rule:"type"}),j.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(_.push({path:X,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),j.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)_.push({path:X,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)_.push({path:X,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))_.push({path:X,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)_.push({path:X,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)_.push({path:X,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let Y=0;Y<$.length;Y++){let z=X?`${X}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],Z.items,z,_,L,j),j.stopOnFirstError&&_.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(j.validateRequired&&Z.required){for(let z of Z.required)if(!(z in Y)){if(_.push({path:X?`${X}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),j.stopOnFirstError)return}}if(Z.properties){for(let[z,F]of Object.entries(Z.properties))if(z in Y){let E=X?`${X}.${z}`:z;if(this.validateObjectAgainstSchema(Y[z],F,E,_,L,j),j.stopOnFirstError&&_.length>0)return}}if(Z.additionalProperties===!1){let z=new Set(Object.keys(Z.properties||{}));for(let F of Object.keys(Y))if(!z.has(F))L.push({path:X?`${X}.${F}`:F,message:`Additional property '${F}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,X){let _=[],L=[];for(let j of Z)try{let Y=this.getValueByPath($,j.path),z=this.validateWithRule(Y,j,j.path);if(_.push(...z),X.stopOnFirstError&&_.length>0)break}catch(Y){_.push({path:j.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:_.length===0,errors:_,warnings:L}}validateWithRule($,Z,X){let _=[];if(Z.required&&($===void 0||$===null))return _.push({path:X,message:Z.message||`Property '${X}' is required`,expected:"required",rule:"required"}),_;if($===void 0||$===null)return _;if(Z.type){let L=Array.isArray($)?"array":typeof $;if(L!==Z.type)_.push({path:X,message:Z.message||`Expected type ${Z.type}, got ${L}`,expected:Z.type,actual:L,rule:"type"})}if(Z.min!==void 0){let L=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(L<Z.min)_.push({path:X,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:L,rule:"min"})}if(Z.max!==void 0){let L=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(L>Z.max)_.push({path:X,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:L,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))_.push({path:X,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))_.push({path:X,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let L=Z.validator($);if(L)_.push({path:X,message:Z.message||L,rule:"custom"})}return _}getValueByPath($,Z){if(!Z)return $;let X=Z.split("."),_=$;for(let L of X)if(_&&typeof _==="object"&&L in _)_=_[L];else return;return _}generateRulesFromInterface($){let Z=[],X=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let _ of X){let[,L,j,Y]=_;Z.push({path:L,required:!j,type:this.mapTypeScriptType(Y)})}return Z}mapTypeScriptType($){switch($.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:J2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class s5{fileLoader=new u$;envProcessor=new m$;validator=new RZ;async loadConfig($){let Z=Date.now(),{cache:X,performance:_,schema:L,validate:j,...Y}=$;try{if(X?.enabled){let F=this.checkCache(Y.name||"",Y);if(F)return F}let z;try{z=await this.loadConfigurationStrategies(Y,!0,X)}catch(F){let E=Y.__strictErrorHandling;if(F instanceof Error&&F.name==="ConfigNotFoundError"){if(E)throw F;z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(F instanceof Error&&F.name==="ConfigLoadError"){let U=F.message.includes("EACCES")||F.message.includes("EPERM")||F.message.includes("permission denied"),V=!U&&(F.message.includes("syntax")||F.message.includes("Expected")||F.message.includes("Unexpected")||F.message.includes("BuildMessage")||F.message.includes("errors building")),Q=F.message.includes("Configuration must export a valid object")||F.message.includes("Configuration file is empty and exports nothing");if(E&&(Q||U))throw F;if(V&&(!E||!Q))z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${F.message}`]};else throw F}else z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${F instanceof Error?F.message:String(F)}`]}}if(L||j)await this.validateConfiguration(z.config,L,j,Y.name);if(X?.enabled&&z)this.cacheResult(Y.name||"",z,X,Y);if(_?.enabled){let F={operation:"loadConfig",duration:Date.now()-Z,configName:Y.name,timestamp:new Date};if(_.onMetrics)_.onMetrics(F);if(_.slowThreshold&&F.duration>_.slowThreshold)L9.warn(`Slow configuration loading detected: ${F.duration}ms for ${Y.name}`);z.metrics=F}return z}catch(z){let F=Date.now()-Z;throw L9.error(`Configuration loading failed after ${F}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,Z=!1,X){let{name:_="",alias:L,cwd:j,configDir:Y,defaultConfig:z,checkEnv:F=!0,arrayStrategy:E="replace",verbose:U=!1}=$,V=j||b9.cwd(),Q=[],O=await this.loadLocalConfiguration(_,L,V,Y,z,E,U,F,X);if(O)return Q.push(...this.getLocalSearchPaths(_,L,V,Y)),this.finalizeResult(O,Q,F,_,U);let K=await this.loadHomeConfiguration(_,L,z,E,U,F);if(K)return Q.push(...this.getHomeSearchPaths(_,L)),this.finalizeResult(K,Q,F,_,U);let I=await this.loadPackageJsonConfiguration(_,L,V,z,E,U,F);if(I)return Q.push(d0(V,"package.json")),this.finalizeResult(I,Q,F,_,U);if(Q.push(...this.getAllSearchPaths(_,L,V,Y)),Z)throw B9.configNotFound(_,Q,L);return{...await this.applyEnvironmentVariables(_,z,F,U),warnings:[`No configuration file found for "${_}"${L?` or alias "${L}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,X,_,L,j,Y,z,F){let E=z?w8($,L,Y):L,U=this.getLocalDirectories(X,_);for(let V of U){if(Y)L9.info(`Searching for configuration in: ${V}`);let Q=this.fileLoader.generateConfigPaths($,V,Z),O=await this.fileLoader.tryLoadFromPaths(Q,E,{arrayStrategy:j,verbose:Y,cacheTtl:F?.ttl,useCache:!F?.ttl||F.ttl>100});if(O){if(Y)L9.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,Z,X,_,L,j){if(!$)return null;let Y=j?w8($,X,L):X,z=[d0(m9(),".config",$),d0(m9(),".config"),m9()];for(let F of z){if(L)L9.info(`Checking home directory: ${F}`);let E=this.fileLoader.generateConfigPaths($,F,Z),U=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:_,verbose:L});if(U){if(L)L9.success(`Configuration loaded from home directory: ${U.source.path}`);return U}}return null}async loadPackageJsonConfiguration($,Z,X,_,L,j,Y){let z=Y?w8($,_,j):_;try{let F=d0(X,"package.json");if(!m5(F))return null;let E=await import(F),U=E[$],V=$;if(!U&&Z)U=E[Z],V=Z;if(U&&typeof U==="object"&&!Array.isArray(U)){if(j)L9.success(`Configuration loaded from package.json: ${V}`);return{config:MZ(z,U,L),source:{type:"package.json",path:F,priority:30,timestamp:new Date}}}}catch(F){if(j)L9.warn("Failed to load package.json:",[F instanceof Error?F:Error(String(F))])}return null}async applyEnvironmentVariables($,Z,X,_){if(!X||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:w8($,Z,_),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,X,_,L){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,X,_){let L=[];if(X){let j=X($);if(j)L.push(...j)}if(Z){let j=await this.validator.validateConfiguration($,Z);if(!j.isValid)L.push(...j.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(L.length>0)throw B9.configValidation(_||"unknown",L,_)}checkCache($,Z){let X=this.generateCacheKey($,Z);return Q8.get(X)||null}cacheResult($,Z,X,_){let L=this.generateCacheKey($,_);Q8.set(L,Z,void 0,X.ttl)}generateCacheKey($,Z){let X=[$];if(Z.alias)X.push(`alias:${Z.alias}`);if(Z.cwd)X.push(`cwd:${Z.cwd}`);if(Z.configDir)X.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)X.push(`checkEnv:${Z.checkEnv}`);return X.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,d0($,"config"),d0($,".config"),Z?d0($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,X,_){let L=[];return L.push(...this.getLocalSearchPaths($,Z,X,_)),L.push(...this.getHomeSearchPaths($,Z)),L.push(d0(X,"package.json")),L}getLocalSearchPaths($,Z,X,_){let L=this.getLocalDirectories(X,_),j=[];for(let Y of L)j.push(...this.fileLoader.generateConfigPaths($,Y,Z));return j}getHomeSearchPaths($,Z){if(!$)return[];let X=[d0(m9(),".config",$),d0(m9(),".config"),m9()],_=[];for(let L of X)_.push(...this.fileLoader.generateConfigPaths($,L,Z));return _}async loadConfigWithResult($){return this.loadConfig($)}}function I6($){let X=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),_=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return X||_}async function R4($){return M9.loadConfig({...$,__strictErrorHandling:!0})}async function E2($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},X="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let _;if(X)_=await M9.loadConfig($);else _=await M9.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return _?.config??Z}catch(_){let L=_ instanceof Error?_.name:"UnknownError",j=_ instanceof Error?_.message:String(_);if(!(L==="ConfigNotFoundError"||L==="ConfigLoadError"||L==="ConfigValidationError"||j.includes("config"))&&$.verbose)L9.warn("Unexpected error loading config, using defaults:",[_ instanceof Error?_:Error(String(_))]);let z=X?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await M9.applyEnvironmentVariables(z.name||"",Z,!0,z.verbose||!1))?.config??Z;return Z}}async function m0($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:Z}=await import("process");try{return(await M9.loadConfig({name:$,cwd:Z(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&I6(X)))return(await M9.applyEnvironmentVariables($,{},!0,!1)).config;throw X}}try{return(await M9.loadConfig({...$,cwd:$.cwd||b9.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&I6(Z)))return(await M9.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw Z}}async function J4($,Z,X="replace"){let _=new u$;try{let L=await _.loadFromPath($,Z,{arrayStrategy:X,useCache:!1,trackPerformance:!1});return L?L.config:null}catch{return null}}function w8($,Z,X=!1){let _=new m$,L=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function j(Y,z=[]){let F={...Y};for(let[E,U]of Object.entries(Y)){let V=[...z,E],Q=[`${L}_${V.join("_").toUpperCase()}`,`${L}_${V.map((I)=>I.toUpperCase()).join("")}`,`${L}_${V.map((I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,K;for(let I of Q)if(O=b9.env[I],O!==void 0){K=I;break}if(O!==void 0&&K)if(typeof U==="boolean")F[E]=["true","1","yes"].includes(O.toLowerCase());else if(typeof U==="number"){let I=Number(O);if(!Number.isNaN(I))F[E]=I}else if(Array.isArray(U))try{F[E]=JSON.parse(O)}catch{F[E]=O.split(",").map((I)=>I.trim())}else F[E]=O;else if(U&&typeof U==="object"&&!Array.isArray(U))F[E]=j(U,V)}return F}return j(Z)}function C4($){let Z=d0(b9.cwd(),$.configDir),X=d0(b9.cwd(),$.generatedDir),_=d0(X,"config-types.ts");if(!m5(lZ(_)))K_(lZ(_),{recursive:!0,mode:511});let L=m5(Z)?I_(Z).map((Y)=>Y.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],j=`// Generated by bunfig v${OL}
36
- export type ConfigNames = ${L.length?`'${L.join("' | '")}'`:"string"}
37
- `;W_(_,j,{mode:438})}function w4($){let Z=null,X=null,_=()=>{if(!X)X=E2($).then((j)=>{return Z=j,j},(j)=>{let Y="defaultConfig"in $?$.defaultConfig:{};if(Z=Y,"verbose"in $&&$.verbose)L9.warn("Config loading failed, using defaults:",[j instanceof Error?j:Error(String(j))]);return Y});return X},L="defaultConfig"in $?$.defaultConfig:{};return Z=L,_(),new Proxy({},{get(j,Y){if(Z)return Z[Y];let z=L[Y];return _(),z},has(j,Y){return Y in(Z||L)},ownKeys(){return Object.keys(Z||L)},getOwnPropertyDescriptor(j,Y){return Object.getOwnPropertyDescriptor(Z||L,Y)},set(j,Y,z){if(!Z)Z={...L};return Z[Y]=z,!0}})}function q4($){let Z=z6(d_.cwd(),$?.configDir||"./config");function X(){if(!g_(Z))return[];let L=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),j=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Y=p_(Z).filter((F)=>L.has(z5(F))).map((F)=>({base:F.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:F})),z=new Map;for(let{base:F,file:E}of Y){let U=z5(E).toLowerCase(),V=z.get(F);if(!V){z.set(F,E);continue}let Q=z5(V).toLowerCase();if(j.indexOf(U)<j.indexOf(Q))z.set(F,E)}return Array.from(z.entries()).map(([F,E])=>({base:F,file:E})).sort((F,E)=>F.base.localeCompare(E.base))}function _(){let L=X(),j=L.map((E)=>E.base),Y=j.length?j.map((E)=>`'${E}'`).join(" | "):"string",z=L.length?`{
38
- ${L.map((E)=>{let U=z6(Z,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${U}').default`}).join(`,
32
+ `;Z+=`| Variable | Type | Description | Example |
33
+ `,Z+=`|----------|------|-------------|----------|
34
+ `;for(let Y of X)Z+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
35
+ `;return Z}}function j4(X,$){let Z=r6("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function f6(X,$,Z={}){return g6(X,$,Z,new WeakMap)}function g6(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return d6(X,$,U,Y);if(!G9($)||!G9(X))return $;return O4(X,$,Z,Y)}function d6(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return E4(X,$);case"smart":return G4(X,$,Y);default:return $}return $}function E4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>W1(U,Y)))Z.push(Y);return Z}function G4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(G9($[0])&&G9(X[0]))return F4(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function F4(X,$,Z){let Y=[...$];for(let U of X){if(!G9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((j)=>G9(j)&&(L in j)&&j[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function O4(X,$,Z,Y){let U=$;if(G9(U)&&Y.has(U))return Y.get(U);let _={...X};if(G9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(G9(L)&&G9(z))_[Q]=g6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=d6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function o1(X,$,Z="replace"){return f6(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function W1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!W1(X[Z],$[Z]))return!1;return!0}if(G9(X)&&G9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!W1(X[U],$[U]))return!1}return!0}return!1}function G9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class ZZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=xX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!u$(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new $$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new $$(X,Error("Configuration must export a valid object"),"unknown");let K={config:o1($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)xX.setWithFileCheck("file",K,X,_);return K}catch(j){throw j instanceof Error?p9.configLoad(X,j):p9.configLoad(X,Error(String(j)))}};if(Q)return N$.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(RZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);if($){if(Z.push($,`.${$}.config`,`${$}.config`,`.${$}`),X)Z.push(`${X}.${$}.config`,`.${X}.${$}.config`)}return Z.filter(Boolean)}checkFileAccess(X){return v6(async()=>{return u$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!u$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=RZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=RZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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((Z)=>Z.test(X))}async validateConfigFile(X){let $=[];try{if(!u$(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class r1{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await N$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!k2($))throw new Z$($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new Z$($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:e6},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class V1{fileLoader=new ZZ;envProcessor=new $Z;validator=new r1;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)V9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw V9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||t9.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(i0(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw p9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?lX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)V9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)V9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?lX(X,Z,U):Z,L=[i0(LX(),".config",X),i0(LX(),".config"),LX()];for(let z of L){if(U)V9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)V9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?lX(X,Y,_):Y;try{let z=i0(Z,"package.json");if(!G1(z))return null;let j=await import(z),E=j[X],V=X;if(!E&&$)E=j[$],V=$;if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)V9.success(`Configuration loaded from package.json: ${V}`);return{config:o1(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)V9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:lX(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw p9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return xX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);xX.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias)Z.push(`alias:${$.alias}`);if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,i0(X,"config"),i0(X,".config"),$?i0(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(i0(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[i0(LX(),".config",X),i0(LX(),".config"),LX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function s5(X){let Z=!(X.message.includes("EACCES")||X.message.includes("EPERM")||X.message.includes("permission denied"))&&(X.message.includes("syntax")||X.message.includes("Expected")||X.message.includes("Unexpected")||X.message.includes("BuildMessage")),Y=X.message.includes("Configuration must export a valid object")||X.message.includes("Configuration file is empty and exports nothing");return Z||Y}async function J4(X){return A9.loadConfig({...X,__strictErrorHandling:!0})}async function p6(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await A9.loadConfig(X);else Y=await A9.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)V9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let L=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await A9.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}async function W4(X={defaultConfig:{}}){if(typeof X==="string"){let{cwd:$}=await import("process");try{return(await A9.loadConfig({name:X,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&s5(Z)))return(await A9.applyEnvironmentVariables(X,{},!0,!1)).config;throw Z}}try{return(await A9.loadConfig({...X,cwd:X.cwd||t9.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&s5($)))return(await A9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function V4(X,$,Z="replace"){let Y=new ZZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function lX(X,$,Z=!1){let Y=new $Z,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=t9.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}function I4(X){let $=i0(t9.cwd(),X.configDir),Z=i0(t9.cwd(),X.generatedDir),Y=i0(Z,"config-types.ts");if(!G1(q5(Y)))L2(q5(Y),{recursive:!0,mode:511});let U=G1($)?j2($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${__}
36
+ export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
37
+ `;E2(Y,_,{mode:438})}function K4(X){let $=null,Z=null,Y=()=>{if(!Z)Z=p6(X).then((_)=>{return $=_,_},(_)=>{let Q="defaultConfig"in X?X.defaultConfig:{};if($=Q,"verbose"in X&&X.verbose)V9.warn("Config loading failed, using defaults:",[_ instanceof Error?_:Error(String(_))]);return Q});return Z},U="defaultConfig"in X?X.defaultConfig:{};return $=U,Y(),new Proxy({},{get(_,Q){if($)return $[Q];let L=U[Q];return Y(),L},has(_,Q){return Q in($||U)},ownKeys(){return Object.keys($||U)},getOwnPropertyDescriptor(_,Q){return Object.getOwnPropertyDescriptor($||U,Q)},set(_,Q,L){if(!$)$={...U};return $[Q]=L,!0}})}function R4(X){let $=d5(y2.cwd(),X?.configDir||"./config");function Z(){if(!x2($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=B2($).filter((z)=>U.has(DZ(z))).map((z)=>({base:z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:z})),L=new Map;for(let{base:z,file:j}of Q){let E=DZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=DZ(V).toLowerCase();if(_.indexOf(E)<_.indexOf(G))L.set(z,j)}return Array.from(L.entries()).map(([z,j])=>({base:z,file:j})).sort((z,j)=>z.base.localeCompare(j.base))}function Y(){let U=Z(),_=U.map((j)=>j.base),Q=_.length?_.map((j)=>`'${j}'`).join(" | "):"string",L=U.length?`{
38
+ ${U.map((j)=>{let E=d5($,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${E}').default`}).join(`,
39
39
  `)}
40
- }`:"Record<string, any>";return`export type ConfigNames = ${Y}
41
- export type ConfigByName = ${z}
40
+ }`:"Record<string, any>";return`export type ConfigNames = ${Q}
41
+ export type ConfigByName = ${L}
42
42
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
43
43
  export type ConfigOf = Config
44
- `}return{name:"bunfig-plugin",setup(L){L.onResolve({filter:/^virtual:bunfig-types$/},(j)=>{return{path:j.path,namespace:"bunfig-virtual"}}),L.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:_(),loader:"ts"}})}}}function H4($,Z={}){let X=Q$.cwd();while(X.includes("storage"))X=U6(X,"..");let _=U6(X,$||"");if(Z?.relative)return m_(Q$.cwd(),_);return _}function C0(){if(I9.env.NODE_ENV==="test"||I9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function N4(){if(I9.env.NODE_ENV==="test"||I9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof I9<"u"){let $=I9.type;if($==="renderer"||$==="worker")return!1;return!!(I9.versions&&(I9.versions.node||I9.versions.bun))}return!1}class O2{async format($){let Z=await N4(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:a9.pid,hostname:Z(),environment:a9.env.NODE_ENV||"development",platform:a9.platform,version:a9.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:a9.env.NODE_ENV||a9.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class W${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=$,this.config={...x8},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new O2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??Z0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let L=this.generateKeyId(),j=this.generateKey();this.currentKeyId=L,this.keys.set(L,j),this.encryptionKeys.set(L,{key:j,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[X]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...r1,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...r1};return{...r1,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:x8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}shouldWriteToFile(){return!C0()&&this.config.writeToFile===!0}async writeToFile($){let X=(async()=>{let L,j=0,Y=3,z=1000;while(j<Y)try{try{try{await s_(this.config.logDirectory,V6.F_OK|V6.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await o_(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let F=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Q9.from($);try{if(!S1(this.currentLogFile))await O5(this.currentLogFile,"",{mode:420});if(L=Q6(this.currentLogFile,"a",420),l_(L,F,{flag:"a"}),O6(L),L!==void 0)E5(L),L=void 0;if((await r9(this.currentLogFile)).size===0){if(await O5(this.currentLogFile,F,{flag:"w",mode:420}),(await r9(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let U=E;if(U.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(U.code)){if(j<Y-1){let V=typeof U.message==="string"?U.message:"Unknown error";console.error(`Network error during write attempt ${j+1}/${Y}:`,V);let Q=z*2**j;await new Promise((O)=>setTimeout(O,Q)),j++;continue}}if(U?.code&&["ENOSPC","EDQUOT"].includes(U.code))throw Error(`Disk quota exceeded or no space left on device: ${U.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",U),U}finally{if(L!==void 0)try{E5(L)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(F){if(j===Y-1){let U=F,V=typeof U.message==="string"?U.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),F}j++;let E=z*2**(j-1);await new Promise((U)=>setTimeout(U,E))}})();this.pendingOperations.push(X);let _=this.pendingOperations.length-1;try{await X}catch(L){throw console.error("Debug: [writeToFile] Error in operation:",L),L}finally{this.pendingOperations.splice(_,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 t9(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 t9(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return t9(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(C0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Z=this.config.rotation.keyRotation;if(!Z?.enabled)return;let X=typeof Z.interval==="number"?Z.interval:60,_=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((L)=>{console.error("Error rotating keys:",L)})},_)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Z=this.config.rotation.keyRotation,X=this.generateKeyId(),_=this.generateKey();this.currentKeyId=X,this.keys.set(X,_),this.encryptionKeys.set(X,{key:_,createdAt:new Date});let L=Array.from(this.encryptionKeys.entries()).sort(([,z],[,F])=>F.createdAt.getTime()-z.createdAt.getTime()),j=typeof Z.maxKeys==="number"?Z.maxKeys:1,Y=Math.max(1,j);if(L.length>Y)for(let[z]of L.slice(Y))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return U5(16).toString("hex")}generateKey(){return U5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=U5(16),_=u_("aes-256-gcm",Z,X),L=Q9.isBuffer($)?$:Q9.from($,"utf8"),j=_.update(L),Y=_.final(),z=j.length+Y.length,F=_.getAuthTag(),E=Q9.allocUnsafe(16+z+16);return X.copy(E,0),j.copy(E,16),Y.copy(E,16+j.length),F.copy(E,16+z),{encrypted:E,iv:X}}async compressData($){return new Promise((Z,X)=>{let _=K6(),L=[];_.on("data",(j)=>L.push(j)),_.on("end",()=>Z(Q9.from(Q9.concat(L)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(C0())return;if(!this.shouldWriteToFile())return;let $=await r9(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let L=await M1(this.config.logDirectory),j=L.filter((F)=>F.startsWith(this.name)&&/\.log\.\d+$/.test(F)).sort((F,E)=>{let U=Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),Y=j.length>0?Number.parseInt(j[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${X}.${Y}`;if(await r9(X).catch(()=>null))try{if(await G6(X,z),Z.compress)try{let F=`${z}.gz`;await this.compressLogFile(z,F),await R1(z)}catch(F){console.error("Error compressing rotated file:",F)}if(j.length===0&&!L.some((F)=>F.endsWith(".log.1")))try{let F=`${X}.1`;await O5(F,"")}catch(F){console.error("Error creating backup file:",F)}}catch(F){console.error(`Error during rotation: ${F instanceof Error?F.message:String(F)}`)}}else{let L=new Date().toISOString().replace(/[:.]/g,"-"),j=X.replace(/\.log$/,`-${L}.log`);if(await r9(X).catch(()=>null))await G6(X,j)}if(this.currentLogFile=_,Z.maxFiles){let j=(await M1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,z)=>z.localeCompare(Y));for(let Y of j.slice(Z.maxFiles))await R1(t9(this.config.logDirectory,Y))}}}async compressLogFile($,Z){let X=E6($),_=i_(Z),L=K6();await a_(X,L,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(_);console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),S1(this.currentLogFile))try{let $=Q6(this.currentLogFile,"r+");O6($),E5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!C0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Z=(await M1(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of Z)try{await R1(t9(this.config.logDirectory,X))}catch(_){console.error(`Failed to delete temp file ${X}:`,_)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?_0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||C0())return!1;let $=typeof Z0.env.NO_COLOR<"u",Z=Z0.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof Z0.stderr<"u"&&Z0.stderr.isTTY||typeof Z0.stdout<"u"&&Z0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:L,level:j,showTimestamp:Y=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(Y)O.push(Z);if(j==="warning")O.push("WARN");else if(j==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(L),O.join(" ")}let F=Z0.stdout.columns||120,E="";if(j==="warning"||j==="error")E=`${X} ${L}`;else if(j==="info"||j==="success")E=`${X} ${_} ${L}`;else E=`${X} ${_} ${_0.cyan(L)}`;if(!Y)return E.trim();let U=z(E).trim().length,V=z(Z).length,Q=Math.max(1,F-2-U-V);return`${E.trim()}${" ".repeat(Q)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(j,Y)=>{let z=Number.parseInt(Y,10);return z<Z[0].length?String(Z[0][z]):j});let X=/%([sdijfo%])/g,_=0,L=$.replace(X,(j,Y)=>{if(Y==="%")return"%";if(_>=Z.length)return j;let z=Z[_++];switch(Y){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return j}});if(_<Z.length)L+=` ${Z.slice(_).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`;return L}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,_,L)=>{let j=_0.underline(_0.blue(_)),Y=this.toAbsoluteFilePath(L);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(Y)}`,F="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${z}\x1B\\${j}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${L}\x1B\\${j}\x1B]8;;\x1B\\`;return j}),Z=Z.replace(/`([^`]+)`/g,(X,_)=>_0.bgGray(_)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(X,_)=>_0.bold(_)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,_)=>_0.italic(_)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,_)=>_0.italic(_)),Z=Z.replace(/~([^~]+)~/g,(X,_)=>_0.strikethrough(_)),Z}supportsHyperlinks(){if(C0())return!1;let $=Z0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let X=Z0.env.HOME||"";if(X)Z=Z.replace(/^~(?=$|\/)/,X)}if(r_(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=t_(Z);else return null;return S1(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,X=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:X}}async log($,Z,...X){if(!this.shouldLog($))return;let _=new Date,L=this.formatConsoleTimestamp(_),j=this.formatFileTimestamp(_),Y,z;if(Z instanceof Error)Y=Z.message,z=Z.stack;else Y=this.formatMessage(Z,X);let{consoleText:F,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":C2[$],Q=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:_0.gray(F),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:_0.green(F),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.error(O),z){let K=z.split(`
45
- `);for(let I of K)if(I.trim()&&!I.includes(Y))console.error(this.formatConsoleMessage({timestamp:L,message:_0.gray(` ${I}`),level:$,showTimestamp:!1}))}break}}else if(!C0()){if(console.error(`${j} ${this.environment}.${$.toUpperCase()}: ${Y}`),z)console.error(z)}let U=`${j} ${this.environment}.${$.toUpperCase()}: ${E}
46
- `;if(z)U+=`${z}
47
- `;if(U=U.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(U)}progress($,Z=""){let X={update:(z,F)=>{},finish:(z)=>{},interrupt:(z,F)=>{}};if(!this.enabled)return X;let _=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:_,lastRenderedLine:""},this.shouldStyleConsole()&&!C0()&&Z0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(z,F)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,z),this.activeProgressBar.total),F!==void 0)this.activeProgressBar.message=F;if(this.shouldStyleConsole()&&!C0()&&Z0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,F="info")=>{if(!C0()&&Z0.stdout.isTTY)Z0.stdout.write(`
48
- `);if(this[F==="warning"?"warn":F](z),this.activeProgressBar&&this.shouldStyleConsole()&&!C0()&&Z0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":_0.blue("\u25D0"),tag:X,message:`${_0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),L=Math.round(_-Z),j=`${$} completed in ${L}ms`,Y=new Date,z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${j}`;if(X)E+=` ${JSON.stringify(X)}`;if(E+=`
49
- `,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:this.options.showIcons===!1?"":_0.green("\u2713"),tag:U,message:`${j}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!C0())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}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 $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new W$(Z,{...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(X),X}createReadStream(){if(C0())throw Error("createReadStream is not supported in browser environments");if(!S1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return E6(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=Q9.isBuffer($)?$:Q9.from($,"base64"),L=_.subarray(0,16),j=_.subarray(_.length-16),Y=_.subarray(16,_.length-16),z=n_("aes-256-gcm",X,L);z.setAuthTag(j);let F=z.update(Y),E=z.final(),U=F.length+E.length,V=Q9.allocUnsafe(U);return F.copy(V,0),E.copy(V,F.length),V.toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return C0()}isServerMode(){return!C0()}setTestEncryptionKey($,Z){this.currentKeyId=$,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($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),{consoleText:L,fileText:j}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let z=L.split(`
50
- `),F=Math.max(...z.map((Q)=>Q.length))+2,E=`\u250C${"\u2500".repeat(F)}\u2510`,U=`\u2514${"\u2500".repeat(F)}\u2518`,V=z.map((Q)=>{return this.formatConsoleMessage({timestamp:X,message:_0.cyan(Q),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:_0.cyan(E),showTimestamp:!1})),V.forEach((Q)=>console.error(Q)),console.error(this.formatConsoleMessage({timestamp:X,message:_0.cyan(U),showTimestamp:!1}))}else if(!C0())console.error(`${_} ${this.environment}.INFO: [BOX] ${j}`);let Y=`${_} ${this.environment}.INFO: [BOX] ${j}
51
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(C0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${_0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let L=_.toString().trim().toLowerCase();Z0.stdin.removeListener("data",X);try{if(typeof Z0.stdin.setRawMode==="function")Z0.stdin.setRawMode(!1)}catch{}Z0.stdin.pause(),console.error(""),Z(L==="y"||L==="yes")};try{if(typeof Z0.stdin.setRawMode==="function")Z0.stdin.setRawMode(!0)}catch{}Z0.stdin.resume(),Z0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let F=/%([sdijfo%])/g,E=0;if(X=$.replace(F,(U,V)=>{if(V==="%")return"%";if(E>=Z.length)return U;let Q=Z[E++];switch(V){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return U}}),E<Z.length)X+=` ${Z.slice(E).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}let{consoleText:_,fileText:L}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let F=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${_0.blue("\u25D0")} `;console.error(`${E}${F} ${_0.cyan(_)}`)}let z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${L}
52
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(z)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),L=$.barLength-_,j=_0.green("\u2501".repeat(_)),Y=_0.gray("\u2501".repeat(L)),z=`[${j}${Y}]`,F=`${X}%`.padStart(4),E=$.message?` ${$.message}`:"",U=this.options.showIcons===!1?"":Z||X===100?_0.green("\u2713"):_0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${_0.gray(this.formatTag(this.name))}`:"",Q=`\r${U}${V} ${z} ${F}${E}`,O=Z0.stdout.columns||80,K=" ".repeat(Math.max(0,O-Q.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${Q}${K}`,Z0.stdout.write($.lastRenderedLine),Z)Z0.stdout.write(`
53
- `)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||C0()||!Z0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(C0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await M1(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let j=t9(this.config.logDirectory,_);if($.before)try{if((await r9(j)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${j}:`,Y);continue}X.push(j)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await R1(_),console.warn(`Deleted log file: ${_}`)}catch(L){console.error(`Failed to delete log file ${_}:`,L)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function P4($,Z={}){let{maxRetries:X=3,retryDelay:_=1000,isRetryable:L=()=>!0,fallback:j}=Z,Y=Error("Unknown error occurred");for(let z=0;z<=X;z++)try{return await $()}catch(F){if(Y=F instanceof Error?F:Error(String(F)),z===X||!L(Y))break;if(_>0)await new Promise((E)=>setTimeout(E,_))}if(j!==void 0)return j;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}class JZ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,X={}){let{prefix:_,useCamelCase:L=!0,useBackwardCompatibility:j=!0,customParsers:Y={},verbose:z=!1,trackPerformance:F=!0}=X,E=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let U=_||this.generateEnvPrefix($),V={...Z};return this.processObject(V,[],U,{useCamelCase:L,useBackwardCompatibility:j,customParsers:Y,verbose:z,configName:$}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(F)return n$.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,X,_){for(let[L,j]of Object.entries($)){let Y=[...Z,L],z=Y.map((U)=>this.formatEnvKey(U,_.useCamelCase)),F=`${X}_${z.join("_")}`,E=_.useBackwardCompatibility?`${X}_${Y.map((U)=>U.toUpperCase()).join("_")}`:null;if(_.verbose);if(typeof j==="object"&&j!==null&&!Array.isArray(j))this.processObject(j,Y,X,_);else{let U=J1.env[F]||(E?J1.env[E]:void 0);if(U!==void 0){if(_.verbose){let V=J1.env[F]?F:E}try{$[L]=this.parseEnvironmentValue(U,typeof j,F,_.customParsers,_.configName)}catch(V){if(V instanceof a5)throw V;throw f9.envVar(F,U,typeof j,_.configName)}}}}}parseEnvironmentValue($,Z,X,_,L){for(let[j,Y]of Object.entries(_))try{return Y($)}catch{continue}for(let j of this.defaultParsers)if(j.canParse($,Z))try{return j.parse($)}catch{throw f9.envVar(X,$,`${Z} (via ${j.name} parser)`,L)}return $}getEnvironmentVariables($){let Z={},X=$.toUpperCase();for(let[_,L]of Object.entries(J1.env))if(_.startsWith(X)&&L!==void 0)Z[_]=L;return Z}validateEnvironmentVariable($,Z,X){let _=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))_.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue($,Z,X,{})}catch(L){_.push(`Cannot parse value "${Z}" as ${X}: ${L}`)}return{isValid:_.length===0,errors:_}}generateEnvVarDocs($,Z,X={}){let{prefix:_,format:L="text"}=X,j=_||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(Z,[],j,Y),L){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,Z,X,_){for(let[L,j]of Object.entries($)){let Y=[...Z,L],z=`${X}_${Y.map((F)=>this.formatEnvKey(F,!0)).join("_")}`;if(typeof j==="object"&&j!==null&&!Array.isArray(j))this.extractEnvVarInfo(j,Y,X,_);else _.push({key:z,type:Array.isArray(j)?"array":typeof j,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(j)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let X=`Environment Variables for ${Z}:
44
+ `}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(_)=>{return{path:_.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function D4(X,$={}){let Z=x8.cwd();while(Z.includes("storage"))Z=p5(Z,"..");let Y=p5(Z,X||"");if($?.relative)return v2(x8.cwd(),Y);return Y}function S0(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function M4(){if(N9.env.NODE_ENV==="test"||N9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof N9<"u"){let X=N9.type;if(X==="renderer"||X==="worker")return!1;return!!(N9.versions&&(N9.versions.node||N9.versions.bun))}return!1}class c6{async format(X){let $=await M4(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:IX.pid,hostname:$(),environment:IX.env.NODE_ENV||"development",platform:IX.platform,version:IX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:IX.env.NODE_ENV||IX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class b8{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(X,$={}){this.name=X,this.config={...Y$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new c6,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...D8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...D8};return{...D8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:Y$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!S0()&&this.config.writeToFile===!0}async writeToFile(X){let Z=(async()=>{let U,_=0,Q=3,L=1000;while(_<Q)try{try{try{await p2(this.config.logDirectory,n5.F_OK|n5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await c2(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let z=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:D9.from(X);try{if(!n$(this.currentLogFile))await CZ(this.currentLogFile,"",{mode:420});if(U=u5(this.currentLogFile,"a",420),d2(U,z,{flag:"a"}),m5(U),U!==void 0)HZ(U),U=void 0;if((await WX(this.currentLogFile)).size===0){if(await CZ(this.currentLogFile,z,{flag:"w",mode:420}),(await WX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let E=j;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(_<Q-1){let V=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${Q}:`,V);let G=L*2**_;await new Promise((J)=>setTimeout(J,G)),_++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{HZ(U)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(z){if(_===Q-1){let E=z,V=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",V),z}_++;let j=L*2**(_-1);await new Promise((E)=>setTimeout(E,j))}})();this.pendingOperations.push(Z);let Y=this.pendingOperations.length-1;try{await Z}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(Y,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 VX(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 VX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return VX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(S0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.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 Z=typeof $.interval==="number"?$.interval:60,Y=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,Y),this.encryptionKeys.set(Z,{key:Y,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,L],[,z])=>z.createdAt.getTime()-L.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,Q=Math.max(1,_);if(U.length>Q)for(let[L]of U.slice(Q))this.encryptionKeys.delete(L),this.keys.delete(L)}generateKeyId(){return MZ(16).toString("hex")}generateKey(){return MZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=MZ(16),Y=b2("aes-256-gcm",$,Z),U=D9.isBuffer(X)?X:D9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=D9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=l5(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(D9.from(D9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(S0())return;if(!this.shouldWriteToFile())return;let X=await WX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await i$(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await WX(Z).catch(()=>null))try{if(await i5(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await l$(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await CZ(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 U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await WX(Z).catch(()=>null))await i5(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let _=(await i$(this.config.logDirectory)).filter((Q)=>Q.startsWith(this.name)).sort((Q,L)=>L.localeCompare(Q));for(let Q of _.slice($.maxFiles))await l$(VX(this.config.logDirectory,Q))}}}async compressLogFile(X,$){let Z=c5(X),Y=g2($),U=l5();await n2(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),n$(this.currentLogFile))try{let X=u5(this.currentLogFile,"r+");m5(X),HZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!S0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await i$(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await l$(VX(this.config.logDirectory,Z))}catch(Y){console.error(`Failed to delete temp file ${Z}:`,Y)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?E0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S0())return!1;let X=typeof L0.env.NO_COLOR<"u",$=L0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof L0.stderr<"u"&&L0.stderr.isTTY||typeof L0.stdout<"u"&&L0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=L0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${E0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=E0.underline(E0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>E0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>E0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>E0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>E0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>E0.strikethrough(Y)),$}supportsHyperlinks(){if(S0())return!1;let X=L0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=L0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(m2($)||$.startsWith("./")||$.startsWith("../"))$=u2($);else return null;return n$($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){if(!this.shouldLog(X))return;let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":XU[X],G=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:E0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:E0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
45
+ `);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:E0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!S0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}let E=`${_} ${this.environment}.${X.toUpperCase()}: ${j}
46
+ `;if(L)E+=`${L}
47
+ `;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(L,z)=>{},finish:(L)=>{},interrupt:(L,z)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!S0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),z!==void 0)this.activeProgressBar.message=z;if(this.shouldStyleConsole()&&!S0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,z="info")=>{if(!S0()&&L0.stdout.isTTY)L0.stdout.write(`
48
+ `);if(this[z==="warning"?"warn":z](L),this.activeProgressBar&&this.shouldStyleConsole()&&!S0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":E0.blue("\u25D0"),tag:Z,message:`${E0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),j=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)j+=` ${JSON.stringify(Z)}`;if(j+=`
49
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":E0.green("\u2713"),tag:E,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!S0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new b8($,{...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(Z),Z}createReadStream(){if(S0())throw Error("createReadStream is not supported in browser environments");if(!n$(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return c5(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){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 Z=this.keys.get(this.currentKeyId);try{let Y=D9.isBuffer(X)?X:D9.from(X,"base64"),U=Y.subarray(0,16),_=Y.subarray(Y.length-16),Q=Y.subarray(16,Y.length-16),L=f2("aes-256-gcm",Z,U);L.setAuthTag(_);let z=L.update(Q),j=L.final(),E=z.length+j.length,V=D9.allocUnsafe(E);return z.copy(V,0),j.copy(V,z.length),V.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S0()}isServerMode(){return!S0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}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(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($),{consoleText:U,fileText:_}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let L=U.split(`
50
+ `),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:E0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:E0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:E0.cyan(E),showTimestamp:!1}))}else if(!S0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
51
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(S0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${E0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();L0.stdin.removeListener("data",Z);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let z=/%([sdijfo%])/g,j=0;if(Z=X.replace(z,(E,V)=>{if(V==="%")return"%";if(j>=$.length)return E;let G=$[j++];switch(V){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return E}}),j<$.length)Z+=` ${$.slice(j).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:U}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${E0.blue("\u25D0")} `;console.error(`${j}${z} ${E0.cyan(Y)}`)}let L=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
52
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(L)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!L0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=E0.green("\u2501".repeat(Y)),Q=E0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?E0.green("\u2713"):E0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${E0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=L0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,L0.stdout.write(X.lastRenderedLine),$)L0.stdout.write(`
53
+ `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||S0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(S0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await i$(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let _=VX(this.config.logDirectory,Y);if(X.before)try{if((await WX(_)).mtime>=X.before)continue}catch(Q){console.error(`Failed to get stats for file ${_}:`,Q);continue}Z.push(_)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await l$(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function H4(X,$={}){let{maxRetries:Z=3,retryDelay:Y=1000,isRetryable:U=()=>!0,fallback:_}=$,Q=Error("Unknown error occurred");for(let L=0;L<=Z;L++)try{return await X()}catch(z){if(Q=z instanceof Error?z:Error(String(z)),L===Z||!U(Q))break;if(Y>0)await new Promise((j)=>setTimeout(j,Y))}if(_!==void 0)return _;throw Q instanceof Error?Q:Error(`Unknown error: ${String(Q)}`)}class a1{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(X,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(X.toLowerCase()),parse:(X)=>{let $=X.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(X,$)=>$==="number"||!Number.isNaN(Number(X))&&!Number.isNaN(Number.parseFloat(X)),parse:(X)=>{let $=Number(X);if(Number.isNaN($))throw TypeError(`Cannot parse "${X}" as number`);return $}},{name:"array",canParse:(X,$)=>$==="array"||X.startsWith("[")||X.includes(","),parse:(X)=>{try{let $=JSON.parse(X);if(Array.isArray($))return $}catch{}return X.split(",").map(($)=>$.trim())}},{name:"json",canParse:(X,$)=>$==="object"||(X.startsWith("{")&&X.endsWith("}")||X.startsWith("[")&&X.endsWith("]")),parse:(X)=>{try{return JSON.parse(X)}catch($){throw Error(`Cannot parse "${X}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(X,$,Z={}){let{prefix:Y,useCamelCase:U=!0,useBackwardCompatibility:_=!0,customParsers:Q={},verbose:L=!1,trackPerformance:z=!0}=Z,j=async()=>{if(!X)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix(X),V={...$};return this.processObject(V,[],E,{useCamelCase:U,useBackwardCompatibility:_,customParsers:Q,verbose:L,configName:X}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return YZ.track("applyEnvironmentVariables",j,{configName:X});return j()}generateEnvPrefix(X){return X.toUpperCase().replace(/-/g,"_")}formatEnvKey(X,$){if(!$)return X.toUpperCase();return X.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=Q.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),z=`${Z}_${L.join("_")}`,j=Y.useBackwardCompatibility?`${Z}_${Q.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.processObject(_,Q,Z,Y);else{let E=s$.env[z]||(j?s$.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=s$.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof D1)throw V;throw e9.envVar(z,E,typeof _,Y.configName)}}}}}parseEnvironmentValue(X,$,Z,Y,U){for(let[_,Q]of Object.entries(Y))try{return Q(X)}catch{continue}for(let _ of this.defaultParsers)if(_.canParse(X,$))try{return _.parse(X)}catch{throw e9.envVar(Z,X,`${$} (via ${_.name} parser)`,U)}return X}getEnvironmentVariables(X){let $={},Z=X.toUpperCase();for(let[Y,U]of Object.entries(s$.env))if(Y.startsWith(Z)&&U!==void 0)$[Y]=U;return $}validateEnvironmentVariable(X,$,Z){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(X))Y.push(`Environment variable key "${X}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(X,$,Z,{})}catch(U){Y.push(`Cannot parse value "${$}" as ${Z}: ${U}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(X,$,Z={}){let{prefix:Y,format:U="text"}=Z,_=Y||this.generateEnvPrefix(X),Q=[];switch(this.extractEnvVarInfo($,[],_,Q),U){case"markdown":return this.formatAsMarkdown(Q,X);case"json":return JSON.stringify(Q,null,2);default:return this.formatAsText(Q,X)}}extractEnvVarInfo(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=`${Z}_${Q.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.extractEnvVarInfo(_,Q,Z,Y);else Y.push({key:L,type:Array.isArray(_)?"array":typeof _,description:`Configuration for ${Q.join(".")}`,example:this.generateExample(_)})}}generateExample(X){if(Array.isArray(X))return JSON.stringify(X);if(typeof X==="object"&&X!==null)return JSON.stringify(X);return String(X)}formatAsText(X,$){let Z=`Environment Variables for ${$}:
54
54
 
55
- `;for(let _ of $)X+=`${_.key}
56
- `,X+=` Type: ${_.type}
57
- `,X+=` Description: ${_.description}
58
- `,X+=` Example: ${_.example}
55
+ `;for(let Y of X)Z+=`${Y.key}
56
+ `,Z+=` Type: ${Y.type}
57
+ `,Z+=` Description: ${Y.description}
58
+ `,Z+=` Example: ${Y.example}
59
59
 
60
- `;return X}formatAsMarkdown($,Z){let X=`# Environment Variables for ${Z}
60
+ `;return Z}formatAsMarkdown(X,$){let Z=`# Environment Variables for ${$}
61
61
 
62
- `;X+=`| Variable | Type | Description | Example |
63
- `,X+=`|----------|------|-------------|----------|
64
- `;for(let _ of $)X+=`| \`${_.key}\` | ${_.type} | ${_.description} | \`${_.example}\` |
65
- `;return X}}function T4($,Z,X={}){return Q2($,Z,X,new WeakMap)}function Q2($,Z,X,_){let{arrayMergeMode:L="replace",skipNullish:j=!1,customMerger:Y}=X;if(Z===null||Z===void 0)return j?$:Z;if(Y){let z=Y($,Z);if(z!==void 0)return z}if(Array.isArray(Z)||Array.isArray($))return V2($,Z,L,_);if(!e0(Z)||!e0($))return Z;return h4($,Z,X,_)}function V2($,Z,X,_){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(X){case"replace":return Z;case"concat":return k4($,Z);case"smart":return x4($,Z,_);default:return Z}return Z}function k4($,Z){let X=[...Z];for(let _ of $)if(!X.some((L)=>o5(L,_)))X.push(_);return X}function x4($,Z,X){if(Z.length===0)return $;if($.length===0)return Z;if(e0(Z[0])&&e0($[0]))return B4($,Z,X);if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}function B4($,Z,X){let _=[...Z];for(let L of $){if(!e0(L)){_.push(L);continue}let j=["id","name","key","path","type"],Y=!1;for(let z of j)if(z in L){if(_.find((E)=>e0(E)&&(z in E)&&E[z]===L[z])){Y=!0;break}}if(!Y)_.push(L)}return _}function h4($,Z,X,_){let L=Z;if(e0(L)&&_.has(L))return _.get(L);let j={...$};if(e0(L))_.set(L,j);for(let Y in L){if(!Object.prototype.hasOwnProperty.call(L,Y))continue;let z=L[Y],F=j[Y];if(X.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){j[Y]=z;continue}if(e0(z)&&e0(F))j[Y]=Q2(F,z,X,_);else if(Array.isArray(z)||Array.isArray(F))j[Y]=V2(F,z,X.arrayMergeMode||"smart",_);else j[Y]=z}return j}function G2($,Z,X="replace"){return T4($,Z,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function o5($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!o5($[X],Z[X]))return!1;return!0}if(e0($)&&e0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!o5($[L],Z[L]))return!1}return!0}return!1}function e0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class K2{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,X={}){let{arrayStrategy:_="replace",useCache:L=!0,cacheTtl:j,trackPerformance:Y=!0,verbose:z=!1}=X;if(L){let E=e8.getWithFileCheck("file",$);if(E){if(z)console.log(`Configuration loaded from cache: ${$}`);return E}}let F=async()=>{if(!C1($))return null;try{let E=`?t=${Date.now()}`,U=await import($+E),V=U.default||U,Q="default"in U,O=Object.keys(U).length>0;if(!Q&&!O)throw new D$($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new D$($,Error("Configuration must export a valid object"),"unknown");let C={config:G2(Z,V,_),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(L)e8.setWithFileCheck("file",C,$,j);return C}catch(E){throw E instanceof Error?f9.configLoad($,E):f9.configLoad($,Error(String(E)))}};if(Y)return n$.track("loadFromPath",F,{path:$});return F()}async tryLoadFromPaths($,Z,X={}){for(let _ of $)try{let L=await this.loadFromPath(_,Z,X);if(L)return L}catch(L){if(L instanceof Error&&L.name==="ConfigLoadError")throw L;if(X.verbose)console.warn(`Failed to load config from ${_}:`,L)}return null}generateConfigPaths($,Z,X){let _=this.generateNamePatterns($,X),L=[];for(let j of _)for(let Y of this.extensions)L.push(Q5(Z,`${j}${Y}`));return L}generateNamePatterns($,Z){let X=[];if(X.push("config",".config"),$)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);let _=Z===void 0?[]:Array.isArray(Z)?Z:[Z];for(let j of _){if(!j)continue;if(X.push(j,`.${j}.config`,`${j}.config`,`.${j}`),$)X.push(`${$}.${j}.config`,`.${$}.${j}.config`)}let L=new Set;return X.filter((j)=>{if(!j||L.has(j))return!1;return L.add(j),!0})}checkFileAccess($){return P4(async()=>{return C1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,X){let _=[];if(!C1($))return _;if(Z||X){let L=this.generateNamePatterns(Z||"",X);for(let j of L)for(let Y of this.extensions){let z=Q5($,`${j}${Y}`);if(await this.checkFileAccess(z))_.push(z)}}else try{let{readdirSync:L}=await import("fs"),j=L($);for(let Y of j)if(this.looksLikeConfigFile(Y)){let z=Q5($,Y);if(await this.checkFileAccess(z))_.push(z)}}catch{return[]}return _}looksLikeConfigFile($){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((X)=>X.test($))}async validateConfigFile($){let Z=[];try{if(!C1($))return Z.push("Configuration file does not exist"),Z;let X=await import($),_=X.default||X;if(_===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof _!=="object"||_===null)Z.push("Configuration must be an object");else if(Array.isArray(_))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:L}=await import("fs"),j=L($,"utf8");JSON.parse(j)}catch(L){Z.push(`Invalid JSON syntax: ${L}`)}}catch(X){Z.push(`Failed to load configuration file: ${X}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let X=new Map;return await Promise.allSettled($.map(async(_)=>{try{let L=await this.loadFromPath(_,{},Z);if(L)X.set(_,L.config)}catch(L){if(Z.verbose)console.warn(`Failed to preload ${_}:`,L)}})),X}}class I2{async validateConfiguration($,Z,X={}){let{stopOnFirstError:_=!1,validateRequired:L=!0,validateTypes:j=!0,customRules:Y=[],trackPerformance:z=!0,verbose:F=!1}=X,E=async()=>{let U=[],V=[],Q={stopOnFirstError:_,validateRequired:L,validateTypes:j,customRules:Y,trackPerformance:z,verbose:F};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,Q);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...Y],Q);else return this.validateWithJSONSchema($,Z,Q)}catch(O){return U.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:U,warnings:V}}};if(z)return await n$.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,Z,X){try{if(!e_(Z))throw new S$(Z,[{path:"",message:"Schema file does not exist"}]);let _=await import(Z),L=_.default||_;if(Array.isArray(L))return this.validateWithRules($,L,X);else return this.validateWithJSONSchema($,L,X)}catch(_){throw new S$(Z,[{path:"",message:`Failed to load schema: ${_}`}])}}validateWithJSONSchema($,Z,X){let _=[],L=[];return this.validateObjectAgainstSchema($,Z,"",_,L,X),{isValid:_.length===0,errors:_,warnings:L}}validateObjectAgainstSchema($,Z,X,_,L,j){if(j.validateTypes&&Z.type){let Y=Array.isArray($)?"array":typeof $,z=Array.isArray(Z.type)?Z.type:[Z.type];if(!z.includes(Y)){if(_.push({path:X,message:`Expected type ${z.join(" or ")}, got ${Y}`,expected:z.join(" or "),actual:Y,rule:"type"}),j.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(_.push({path:X,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),j.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)_.push({path:X,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)_.push({path:X,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))_.push({path:X,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)_.push({path:X,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)_.push({path:X,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let Y=0;Y<$.length;Y++){let z=X?`${X}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],Z.items,z,_,L,j),j.stopOnFirstError&&_.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(j.validateRequired&&Z.required){for(let z of Z.required)if(!(z in Y)){if(_.push({path:X?`${X}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),j.stopOnFirstError)return}}if(Z.properties){for(let[z,F]of Object.entries(Z.properties))if(z in Y){let E=X?`${X}.${z}`:z;if(this.validateObjectAgainstSchema(Y[z],F,E,_,L,j),j.stopOnFirstError&&_.length>0)return}}if(Z.additionalProperties===!1){let z=new Set(Object.keys(Z.properties||{}));for(let F of Object.keys(Y))if(!z.has(F))L.push({path:X?`${X}.${F}`:F,message:`Additional property '${F}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,X){let _=[],L=[];for(let j of Z)try{let Y=this.getValueByPath($,j.path),z=this.validateWithRule(Y,j,j.path);if(_.push(...z),X.stopOnFirstError&&_.length>0)break}catch(Y){_.push({path:j.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:_.length===0,errors:_,warnings:L}}validateWithRule($,Z,X){let _=[];if(Z.required&&($===void 0||$===null))return _.push({path:X,message:Z.message||`Property '${X}' is required`,expected:"required",rule:"required"}),_;if($===void 0||$===null)return _;if(Z.type){let L=Array.isArray($)?"array":typeof $;if(L!==Z.type)_.push({path:X,message:Z.message||`Expected type ${Z.type}, got ${L}`,expected:Z.type,actual:L,rule:"type"})}if(Z.min!==void 0){let L=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(L<Z.min)_.push({path:X,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:L,rule:"min"})}if(Z.max!==void 0){let L=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(L>Z.max)_.push({path:X,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:L,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))_.push({path:X,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))_.push({path:X,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let L=Z.validator($);if(L)_.push({path:X,message:Z.message||L,rule:"custom"})}return _}getValueByPath($,Z){if(!Z)return $;let X=Z.split("."),_=$;for(let L of X)if(_&&typeof _==="object"&&L in _)_=_[L];else return;return _}generateRulesFromInterface($){let Z=[],X=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let _ of X){let[,L,j,Y]=_;Z.push({path:L,required:!j,type:this.mapTypeScriptType(Y)})}return Z}mapTypeScriptType($){switch($.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:w2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function y4($){if(!$)return"";let Z=Array.isArray($)?$.filter(Boolean):[$];if(Z.length===0)return"";if(Z.length===1)return` or alias "${Z[0]}"`;return` or aliases ${Z.map((X)=>`"${X}"`).join(", ")}`}class W2{fileLoader=new K2;envProcessor=new JZ;validator=new I2;async loadConfig($){let Z=Date.now(),{cache:X,performance:_,schema:L,validate:j,...Y}=$;try{if(X?.enabled){let F=this.checkCache(Y.name||"",Y);if(F)return F}let z;try{z=await this.loadConfigurationStrategies(Y,!0,X)}catch(F){let E=Y.__strictErrorHandling;if(F instanceof Error&&F.name==="ConfigNotFoundError"){if(E)throw F;z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(F instanceof Error&&F.name==="ConfigLoadError"){let U=F.message.includes("EACCES")||F.message.includes("EPERM")||F.message.includes("permission denied"),V=!U&&(F.message.includes("syntax")||F.message.includes("Expected")||F.message.includes("Unexpected")||F.message.includes("BuildMessage")||F.message.includes("errors building")),Q=F.message.includes("Configuration must export a valid object")||F.message.includes("Configuration file is empty and exports nothing");if(E&&(Q||U))throw F;if(V&&(!E||!Q))z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${F.message}`]};else throw F}else z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${F instanceof Error?F.message:String(F)}`]}}if(L||j)await this.validateConfiguration(z.config,L,j,Y.name);if(X?.enabled&&z)this.cacheResult(Y.name||"",z,X,Y);if(_?.enabled){let F={operation:"loadConfig",duration:Date.now()-Z,configName:Y.name,timestamp:new Date};if(_.onMetrics)_.onMetrics(F);if(_.slowThreshold&&F.duration>_.slowThreshold)_9.warn(`Slow configuration loading detected: ${F.duration}ms for ${Y.name}`);z.metrics=F}return z}catch(z){if(z instanceof Error&&z.name==="ConfigNotFoundError")throw z;let F=Date.now()-Z;throw _9.error(`Configuration loading failed after ${F}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,Z=!1,X){let{name:_="",alias:L,cwd:j,configDir:Y,defaultConfig:z,checkEnv:F=!0,arrayStrategy:E="replace",verbose:U=!1}=$,V=j||z$.cwd(),Q=[],O=await this.loadLocalConfiguration(_,L,V,Y,z,E,U,F,X);if(O)return Q.push(...this.getLocalSearchPaths(_,L,V,Y)),this.finalizeResult(O,Q,F,_,U);let K=await this.loadHomeConfiguration(_,L,z,E,U,F);if(K)return Q.push(...this.getHomeSearchPaths(_,L)),this.finalizeResult(K,Q,F,_,U);let I=await this.loadPackageJsonConfiguration(_,L,V,z,E,U,F);if(I)return Q.push(o0(V,"package.json")),this.finalizeResult(I,Q,F,_,U);if(Q.push(...this.getAllSearchPaths(_,L,V,Y)),Z)throw f9.configNotFound(_,Q,L);return{...await this.applyEnvironmentVariables(_,z,F,U),warnings:[`No configuration file found for "${_}"${y4(L)}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,X,_,L,j,Y,z,F){let E=z?q1($,L,Y):L,U=this.getLocalDirectories(X,_);for(let V of U){if(Y)_9.info(`Searching for configuration in: ${V}`);let Q=this.fileLoader.generateConfigPaths($,V,Z),O=await this.fileLoader.tryLoadFromPaths(Q,E,{arrayStrategy:j,verbose:Y,cacheTtl:F?.ttl,useCache:!F?.ttl||F.ttl>100});if(O){if(Y)_9.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,Z,X,_,L,j){if(!$)return null;let Y=j?q1($,X,L):X,z=[o0(c9(),".config",$),o0(c9(),".config"),c9()];for(let F of z){if(L)_9.info(`Checking home directory: ${F}`);let E=this.fileLoader.generateConfigPaths($,F,Z),U=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:_,verbose:L});if(U){if(L)_9.success(`Configuration loaded from home directory: ${U.source.path}`);return U}}return null}async loadPackageJsonConfiguration($,Z,X,_,L,j,Y){let z=Y?q1($,_,j):_;try{let F=o0(X,"package.json");if(!V_(F))return null;let E={};try{E=JSON.parse(G_(F,"utf8"))}catch(Q){if(j)_9.warn("Failed to parse package.json:",[Q instanceof Error?Q:Error(String(Q))]);return null}let U=E[$],V=$;if(!U&&Z){let Q=Array.isArray(Z)?Z:[Z];for(let O of Q){if(!O)continue;if(E[O]){U=E[O],V=O;break}}}if(U&&typeof U==="object"&&!Array.isArray(U)){if(j)_9.success(`Configuration loaded from package.json: ${V}`);return{config:G2(z,U,L),source:{type:"package.json",path:F,priority:30,timestamp:new Date}}}}catch(F){if(j)_9.warn("Failed to load package.json:",[F instanceof Error?F:Error(String(F))])}return null}async applyEnvironmentVariables($,Z,X,_){if(!X||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:q1($,Z,_),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,X,_,L){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,X,_){let L=[];if(X){let j=X($);if(j)L.push(...j)}if(Z){let j=await this.validator.validateConfiguration($,Z);if(!j.isValid)L.push(...j.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(L.length>0)throw f9.configValidation(_||"unknown",L,_)}checkCache($,Z){let X=this.generateCacheKey($,Z);return e8.get(X)||null}cacheResult($,Z,X,_){let L=this.generateCacheKey($,_);e8.set(L,Z,void 0,X.ttl)}generateCacheKey($,Z){let X=[$];if(Z.alias){let _=Array.isArray(Z.alias)?Z.alias.join(","):Z.alias;X.push(`alias:${_}`)}if(Z.cwd)X.push(`cwd:${Z.cwd}`);if(Z.configDir)X.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)X.push(`checkEnv:${Z.checkEnv}`);return X.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,o0($,"config"),o0($,".config"),Z?o0($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,X,_){let L=[];return L.push(...this.getLocalSearchPaths($,Z,X,_)),L.push(...this.getHomeSearchPaths($,Z)),L.push(o0(X,"package.json")),L}getLocalSearchPaths($,Z,X,_){let L=this.getLocalDirectories(X,_),j=[];for(let Y of L)j.push(...this.fileLoader.generateConfigPaths($,Y,Z));return j}getHomeSearchPaths($,Z){if(!$)return[];let X=[o0(c9(),".config",$),o0(c9(),".config"),c9()],_=[];for(let L of X)_.push(...this.fileLoader.generateConfigPaths($,L,Z));return _}async loadConfigWithResult($){return this.loadConfig($)}}async function A4($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},X="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let _;if(X)_=await t1.loadConfig($);else _=await t1.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return _?.config??Z}catch(_){let L=_ instanceof Error?_.name:"UnknownError",j=_ instanceof Error?_.message:String(_);if(!(L==="ConfigNotFoundError"||L==="ConfigLoadError"||L==="ConfigValidationError"||j.includes("config"))&&$.verbose)_9.warn("Unexpected error loading config, using defaults:",[_ instanceof Error?_:Error(String(_))]);let z=X?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await t1.applyEnvironmentVariables(z.name||"",Z,!0,z.verbose||!1))?.config??Z;return Z}}function q1($,Z,X=!1){let _=new JZ,L=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function j(Y,z=[]){let F={...Y};for(let[E,U]of Object.entries(Y)){let V=[...z,E],Q=[`${L}_${V.join("_").toUpperCase()}`,`${L}_${V.map((I)=>I.toUpperCase()).join("")}`,`${L}_${V.map((I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,K;for(let I of Q)if(O=z$.env[I],O!==void 0){K=I;break}if(O!==void 0&&K)if(typeof U==="boolean")F[E]=["true","1","yes"].includes(O.toLowerCase());else if(typeof U==="number"){let I=Number(O);if(!Number.isNaN(I))F[E]=I}else if(Array.isArray(U))try{F[E]=JSON.parse(O)}catch{F[E]=O.split(",").map((I)=>I.trim())}else F[E]=O;else if(U&&typeof U==="object"&&!Array.isArray(U))F[E]=j(U,V)}return F}return j(Z)}var e8,n$,D2,v4=($)=>$,b4=($,Z)=>{for(var X in Z)D2($,X,{get:Z[X],enumerable:!0,configurable:!0,set:$4.bind(Z,X)})},f4=($,Z)=>()=>($&&(Z=$($=0)),Z),V5,S2,Q8,$1,W6,g4,p4,D6,u1,r5,k0,O0,d4,S6,c4,M6,m4,u4,G5,n4,R6,J6,K5,i4,l4,s4,o4,n1,M2,r4,h0,t4,a4,C6,i1,t5,w0,X0,e4,w6,$L,q6,ZL,XL,I5,_L,H6,N6,LL,W5,jL,YL,FL,zL,UL,l1,R2,EL,OL="0.15.6",u0,s1,P8,D5,S5,o1,M5,R5,T8,J5,C5,B9,P6,J2,L9,M9,T6,k6,x6,B6,k8,x8,QL,q0,_0,VL,h6,GL,y6,KL,IL,w5,WL,A6,v6,DL,q5,SL,ML,RL,JL,CL,r1,C2,wL,Z9,b6,D$,f6,g6,a5,p6,d6,S$,c6,m6,f9,w2,_9,t1,qL,HL,NL=n(()=>{e8=new Z2,n$=new X2,D2=Object.defineProperty,V5={},b4(V5,{withErrorRecovery:()=>j2,tryLoadConfig:()=>J4,loadConfigWithResult:()=>R4,loadConfig:()=>E2,isRetryableError:()=>K4,isConfigNotFoundError:()=>G4,isBunfigError:()=>Y2,globalPerformanceMonitor:()=>$1,globalCache:()=>Q8,getEnvOrDefault:()=>I4,generateConfigTypes:()=>C4,defaultGeneratedDir:()=>k6,defaultConfigDir:()=>T6,deepMergeWithArrayStrategy:()=>MZ,deepMerge:()=>F2,createLibraryConfig:()=>w4,config:()=>m0,bunfigPlugin:()=>q4,applyEnvVarsToConfig:()=>w8,TypeGenerationError:()=>R5,SchemaValidationError:()=>T8,PluginError:()=>C5,PerformanceMonitor:()=>i5,FileSystemError:()=>M5,ErrorFactory:()=>B9,EnvVarError:()=>o1,EnvProcessor:()=>m$,ConfigValidator:()=>RZ,ConfigValidationError:()=>D5,ConfigNotFoundError:()=>s1,ConfigMergeError:()=>S5,ConfigLoader:()=>s5,ConfigLoadError:()=>P8,ConfigFileLoader:()=>u$,ConfigCache:()=>n5,CacheUtils:()=>W6,BunfigError:()=>u0,BrowserConfigError:()=>J5,ArrayMergeStrategies:()=>P6}),x6=f4(async()=>{S2=import.meta.require,Q8=new n5,$1=new i5,W6={createKey:Z4,isEquivalent:X4,estimateMemoryUsage:_4},g4=O$(u5.cwd(),"config"),p4=O$(u5.cwd(),"src/generated"),D6=E$.env.CLARITY_LOG_DIR||M_(Y4(),"logs"),u1={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:D6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},r5=await F4(),k0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},O0=k0,d4=k0.red,S6=k0.green,c4=k0.yellow,M6=k0.blue,m4=k0.magenta,u4=k0.cyan,G5=k0.white,n4=k0.gray,R6=k0.bgRed,J6=k0.bgYellow,K5=k0.bold,i4=k0.dim,l4=k0.italic,s4=k0.underline,o4=k0.reset,n1={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},M2={debug:"\uD83D\uDD0D",info:M6("\u2139"),success:S6("\u2713"),warning:J6(G5(K5(" WARN "))),error:R6(G5(K5(" ERROR ")))},r4=new G$("stacks"),h0=new G$("bunfig",{showTags:!0}),t4=g0(a8.cwd(),"config"),a4=g0(a8.cwd(),"src/generated"),C6=U$.env.CLARITY_LOG_DIR||D_(O4(),"logs"),i1={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:C6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},t5=await Q4(),w0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},X0=w0,e4=w0.red,w6=w0.green,$L=w0.yellow,q6=w0.blue,ZL=w0.magenta,XL=w0.cyan,I5=w0.white,_L=w0.gray,H6=w0.bgRed,N6=w0.bgYellow,LL=w0.bgGray,W5=w0.bold,jL=w0.dim,YL=w0.italic,FL=w0.underline,zL=w0.strikethrough,UL=w0.reset,l1={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},R2={debug:"\uD83D\uDD0D",info:q6("\u2139"),success:w6("\u2713"),warning:N6(I5(W5(" WARN "))),error:H6(I5(W5(" ERROR ")))},EL=new I$("stacks"),u0=class extends Error{timestamp;context;constructor(Z,X={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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(([X,_])=>`${X}: ${_}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},s1=class extends u0{code="CONFIG_NOT_FOUND";constructor(Z,X,_){let L=_?` or alias "${_}"`:"";super(`Configuration "${Z}"${L} not found`,{configName:Z,alias:_,searchPaths:X,searchPathCount:X.length})}},P8=class extends u0{code="CONFIG_LOAD_ERROR";constructor(Z,X,_){super(`Failed to load configuration from "${Z}": ${X.message}`,{configPath:Z,configName:_,originalError:X.name,originalMessage:X.message});this.cause=X}},D5=class extends u0{code="CONFIG_VALIDATION_ERROR";constructor(Z,X,_){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},S5=class extends u0{code="CONFIG_MERGE_ERROR";constructor(Z,X,_,L){super(`Failed to merge configuration from "${Z}" with "${X}": ${_.message}`,{sourcePath:Z,targetPath:X,configName:L,originalError:_.name,originalMessage:_.message});this.cause=_}},o1=class extends u0{code="ENV_VAR_ERROR";constructor(Z,X,_,L){super(`Failed to parse environment variable "${Z}" with value "${X}" as ${_}`,{envKey:Z,envValue:X,expectedType:_,configName:L})}},M5=class extends u0{code="FILE_SYSTEM_ERROR";constructor(Z,X,_){super(`File system ${Z} failed for "${X}": ${_.message}`,{operation:Z,path:X,originalError:_.name,originalMessage:_.message});this.cause=_}},R5=class extends u0{code="TYPE_GENERATION_ERROR";constructor(Z,X,_){super(`Failed to generate types from "${Z}" to "${X}": ${_.message}`,{configDir:Z,outputPath:X,originalError:_.name,originalMessage:_.message});this.cause=_}},T8=class extends u0{code="SCHEMA_VALIDATION_ERROR";constructor(Z,X,_){super(`Schema validation failed${_?` for config "${_}"`:""}`,{schemaPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},J5=class extends u0{code="BROWSER_CONFIG_ERROR";constructor(Z,X,_,L){super(`Failed to fetch configuration from "${Z}": ${X} ${_}`,{endpoint:Z,status:X,statusText:_,configName:L})}},C5=class extends u0{code="PLUGIN_ERROR";constructor(Z,X,_){super(`Plugin "${Z}" failed during ${X}: ${_.message}`,{pluginName:Z,operation:X,originalError:_.name,originalMessage:_.message});this.cause=_}},B9={configNotFound($,Z,X){return new s1($,Z,X)},configLoad($,Z,X){return new P8($,Z,X)},configValidation($,Z,X){return new D5($,Z,X)},configMerge($,Z,X,_){return new S5($,Z,X,_)},envVar($,Z,X,_){return new o1($,Z,X,_)},fileSystem($,Z,X){return new M5($,Z,X)},typeGeneration($,Z,X){return new R5($,Z,X)},schemaValidation($,Z,X){return new T8($,Z,X)},browserConfig($,Z,X,_){return new J5($,Z,X,_)},plugin($,Z,X){return new C5($,Z,X)}},P6={replace:"replace",concat:"concat",smart:"smart"},J2=/^https?:\/\//,L9=new I$("bunfig",{showTags:!0}),M9=new s5,T6=d0(b9.cwd(),"config"),k6=d0(b9.cwd(),"src/generated")}),B6=Q$.env.CLARITY_LOG_DIR||c_(H4(),"logs"),k8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:B6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},x8={...k8},QL=(async()=>{try{let{loadConfig:$}=await x6().then(()=>V5),Z=await $({name:"clarity",alias:"logging",defaultConfig:k8,cwd:Q$.cwd()});if(Z)Object.assign(x8,Z)}catch{}return x8})(),q0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},_0=q0,VL=q0.red,h6=q0.green,GL=q0.yellow,y6=q0.blue,KL=q0.magenta,IL=q0.cyan,w5=q0.white,WL=q0.gray,A6=q0.bgRed,v6=q0.bgYellow,DL=q0.bgGray,q5=q0.bold,SL=q0.dim,ML=q0.italic,RL=q0.underline,JL=q0.strikethrough,CL=q0.reset,r1={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},C2={debug:"\uD83D\uDD0D",info:y6("\u2139"),success:h6("\u2713"),warning:v6(w5(q5(" WARN "))),error:A6(w5(q5(" ERROR ")))},wL=new W$("stacks"),Z9=class extends Error{timestamp;context;constructor(Z,X={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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(([X,_])=>`${X}: ${_}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},b6=class extends Z9{code="CONFIG_NOT_FOUND";constructor(Z,X,_){let L=_===void 0?[]:Array.isArray(_)?_.filter(Boolean):[_],j="";if(L.length===1)j=` or alias "${L[0]}"`;else if(L.length>1)j=` or aliases ${L.map((Y)=>`"${Y}"`).join(", ")}`;super(`Configuration "${Z}"${j} not found`,{configName:Z,alias:_,searchPaths:X,searchPathCount:X.length})}},D$=class extends Z9{code="CONFIG_LOAD_ERROR";constructor(Z,X,_){super(`Failed to load configuration from "${Z}": ${X.message}`,{configPath:Z,configName:_,originalError:X.name,originalMessage:X.message});this.cause=X}},f6=class extends Z9{code="CONFIG_VALIDATION_ERROR";constructor(Z,X,_){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},g6=class extends Z9{code="CONFIG_MERGE_ERROR";constructor(Z,X,_,L){super(`Failed to merge configuration from "${Z}" with "${X}": ${_.message}`,{sourcePath:Z,targetPath:X,configName:L,originalError:_.name,originalMessage:_.message});this.cause=_}},a5=class extends Z9{code="ENV_VAR_ERROR";constructor(Z,X,_,L){super(`Failed to parse environment variable "${Z}" with value "${X}" as ${_}`,{envKey:Z,envValue:X,expectedType:_,configName:L})}},p6=class extends Z9{code="FILE_SYSTEM_ERROR";constructor(Z,X,_){super(`File system ${Z} failed for "${X}": ${_.message}`,{operation:Z,path:X,originalError:_.name,originalMessage:_.message});this.cause=_}},d6=class extends Z9{code="TYPE_GENERATION_ERROR";constructor(Z,X,_){super(`Failed to generate types from "${Z}" to "${X}": ${_.message}`,{configDir:Z,outputPath:X,originalError:_.name,originalMessage:_.message});this.cause=_}},S$=class extends Z9{code="SCHEMA_VALIDATION_ERROR";constructor(Z,X,_){super(`Schema validation failed${_?` for config "${_}"`:""}`,{schemaPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},c6=class extends Z9{code="BROWSER_CONFIG_ERROR";constructor(Z,X,_,L){super(`Failed to fetch configuration from "${Z}": ${X} ${_}`,{endpoint:Z,status:X,statusText:_,configName:L})}},m6=class extends Z9{code="PLUGIN_ERROR";constructor(Z,X,_){super(`Plugin "${Z}" failed during ${X}: ${_.message}`,{pluginName:Z,operation:X,originalError:_.name,originalMessage:_.message});this.cause=_}},f9={configNotFound($,Z,X){return new b6($,Z,X)},configLoad($,Z,X){return new D$($,Z,X)},configValidation($,Z,X){return new f6($,Z,X)},configMerge($,Z,X,_){return new g6($,Z,X,_)},envVar($,Z,X,_){return new a5($,Z,X,_)},fileSystem($,Z,X){return new p6($,Z,X)},typeGeneration($,Z,X){return new d6($,Z,X)},schemaValidation($,Z,X){return new S$($,Z,X)},browserConfig($,Z,X,_){return new c6($,Z,X,_)},plugin($,Z,X){return new m6($,Z,X)}},w2=/^https?:\/\//,_9=new W$("bunfig",{showTags:!0}),t1=new W2,qL=o0(z$.cwd(),"config"),HL=o0(z$.cwd(),"src/generated")});function m($){if(y.dialect==="postgres")return`$${$}`;return"?"}function f0($,Z=1){if(y.dialect==="postgres")return Array.from({length:$},(X,_)=>`$${Z+_}`).join(", ");return Array.from({length:$},()=>"?").join(", ")}async function iU(){if(!B8)B8=await A4({name:"query-builder",alias:"qb",defaultConfig:e5});return B8}function lU($){if(m0==null||m0.dialect===void 0)m0=k8?{...k8}:{};if(Object.assign(m0,$),$.database)m0.database={...m0.database,...$.database};if($.timestamps)m0.timestamps={...m0.timestamps,...$.timestamps};if($.pagination)m0.pagination={...m0.pagination,...$.pagination};if($.softDeletes)m0.softDeletes={...m0.softDeletes,...$.softDeletes};if(B8)Object.assign(B8,m0)}var e5,y,B8=null,F9=n(()=>{NL(),e5={verbose:!0,dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},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}},y={...e5}}),{SQL:PL}=globalThis.Bun;class q2{db;constructor($){this.db=new TL($),this.db.run("PRAGMA journal_mode = WAL")}query($,Z=[]){return this.db.prepare($).all(...Z)}run($,Z=[]){return this.db.prepare($).run(...Z)}close(){this.db.close()}get database(){return this.db}}function u6($){return{__raw:!0,value:$,toString:()=>$}}function kL($){let Z=[],X="",_=!1,L=!1,j=!1,Y=!1;for(let F=0;F<$.length;F++){let E=$[F],U=$[F+1];if(!_&&!L&&!Y&&E==="-"&&U==="-"){j=!0,X+=E;continue}if(j&&(E===`
66
- `||E==="\r")){j=!1,X+=E;continue}if(!_&&!L&&!j&&E==="/"&&U==="*"){Y=!0,X+=E;continue}if(Y&&E==="*"&&U==="/"){Y=!1,X+=E+U,F++;continue}if(j||Y){X+=E;continue}if(E==="'"&&!L){if(_&&U==="'"){X+=E+U,F++;continue}_=!_,X+=E;continue}if(E==='"'&&!_){L=!L,X+=E;continue}if(E===";"&&!_&&!L){let V=X.trim();if(V&&!V.startsWith("--"))Z.push(V);X="";continue}X+=E}let z=X.trim();if(z&&!z.startsWith("--"))Z.push(z);return Z}function n6($){let Z=new q2($);function X(L,...j){let Y=L[0],z=[];for(let F=0;F<j.length;F++){let E=j[F];if(E&&typeof E==="object"&&(E.__raw||E.raw)){let U=E.__raw?E.value:typeof E.raw==="string"?E.raw:E.raw();Y+=U+(L[F+1]||"")}else if(E&&typeof E==="object"&&"sql"in E&&"values"in E)Y+=E.sql+(L[F+1]||""),z.push(...E.values);else if(Array.isArray(E)){let U=E.map(()=>"?").join(", ");Y+=U+(L[F+1]||""),z.push(...E)}else Y+=`?${L[F+1]||""}`,z.push(E)}return{sql:Y,values:z,execute:()=>{try{let F=Y.trim().toUpperCase();if(F.startsWith("SELECT")||F.startsWith("PRAGMA")){let E=Z.query(Y,z);return Promise.resolve(E)}else{let E=Z.run(Y,z);return Promise.resolve(E)}}catch(F){return Promise.reject(F)}},raw:()=>Y,toString:()=>Y,cancel:()=>{}}}function _(L,...j){if(Array.isArray(L)&&"raw"in L)return X(L,...j);if(typeof L==="string")return u6(L);return X([""])}return _.raw=(L)=>u6(L),_.unsafe=(L,j=[])=>{return{sql:L,values:j,execute:()=>{try{let Y=L.trim().toUpperCase();if(Y.startsWith("SELECT")||Y.startsWith("PRAGMA")){let z=Z.query(L,j);return Promise.resolve(z)}else{let z=Z.run(L,j);return Promise.resolve(z)}}catch(Y){return Promise.reject(Y)}},raw:()=>L,toString:()=>L,cancel:()=>{}}},_.close=()=>{return Z.close(),Promise.resolve()},_.query=(L,j)=>{try{let Y=Z.query(L,j||[]);return Promise.resolve(Y)}catch(Y){return Promise.reject(Y)}},_.file=async(L,j)=>{try{let{readFileSync:Y}=await import("fs"),z=Y(L,"utf-8"),F=kL(z);for(let E of F){let U=E.trim();if(!U||U.startsWith("--"))continue;let V=U.toUpperCase();if(V.startsWith("SELECT")||V.startsWith("PRAGMA"))Z.query(E);else Z.run(E)}return Promise.resolve([])}catch(Y){return Promise.reject(Y)}},_._wrapper=Z,_}function xL($,Z){if(Z.url)return Z.url;let{database:X,username:_,password:L,host:j="localhost",port:Y}=Z;switch($){case"postgres":return`postgres://${_}:${L}@${j}${Y?`:${Y}`:""}/${X}`;case"mysql":return`mysql://${_}:${L}@${j}${Y?`:${Y}`:""}/${X}`;case"sqlite":if(X===":memory:")return":memory:";return X||":memory:";default:throw Error(`Unsupported dialect: ${$}`)}}function BL(){let $=y.dialect,Z=xL($,y.database);try{if($==="sqlite")return n6(Z);let X=new PL(Z);if(X&&typeof X.catch==="function")X.catch((_)=>{if(y.verbose&&!_.message.includes("database")&&!_.message.includes("does not exist"))console.warn(`[query-builder] Database connection error: ${_.message}`)});return X}catch(X){if(y.verbose)console.warn(`[query-builder] Failed to create connection: ${X.message}`);try{return n6(":memory:")}catch{return{query:()=>Promise.resolve([]),execute:()=>Promise.resolve([]),close:()=>Promise.resolve()}}}}function Z1($=!1){let Z=q8!==null&&($Z!==y.dialect||ZZ!==y.database.database);if($||Z||!q8)q8=BL(),$Z=y.dialect,ZZ=y.database.database;return q8}function rU(){q8=null,$Z=null,ZZ=null}async function H5($){try{return await $(Z1())}catch(Z){if(Z?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||Z?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let X=Z1(!0);return await $(X)}throw Z}}function hL(){return new Proxy({},{get($,Z){let X=Z1(),_=X[Z];if(typeof _==="function")return _.bind(X);return _},apply($,Z,X){return Z1()(...X)}})}var q8=null,$Z=null,ZZ=null,x,G8=n(()=>{if(F9(),x=hL(),typeof H1<"u"&&H1.on){if(!H1.listeners("unhandledRejection").find((Z)=>Z.name==="sqlConnectionErrorHandler")){let Z=function(X){if(X&&(X.message?.includes("database")||X.message?.includes("does not exist")||X.code==="ERR_POSTGRES_SERVER_ERROR"||X.code==="3D000"));};Object.defineProperty(Z,"name",{value:"sqlConnectionErrorHandler"}),H1.on("unhandledRejection",Z)}}});async function tU($={}){let Z=$.iterations||1000,X=$.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${Z}`),console.log(`-- Operations: ${X.join(", ")}`),console.log();let _=W0();console.log("-- Setting up test table...");try{await x.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await x.unsafe(`
62
+ `;Z+=`| Variable | Type | Description | Example |
63
+ `,Z+=`|----------|------|-------------|----------|
64
+ `;for(let Y of X)Z+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
65
+ `;return Z}}function C4(X,$,Z={}){return m6(X,$,Z,new WeakMap)}function m6(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return u6(X,$,U,Y);if(!F9($)||!F9(X))return $;return T4(X,$,Z,Y)}function u6(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return w4(X,$);case"smart":return q4(X,$,Y);default:return $}return $}function w4(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>I1(U,Y)))Z.push(Y);return Z}function q4(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(F9($[0])&&F9(X[0]))return P4(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function P4(X,$,Z){let Y=[...$];for(let U of X){if(!F9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((j)=>F9(j)&&(L in j)&&j[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function T4(X,$,Z,Y){let U=$;if(F9(U)&&Y.has(U))return Y.get(U);let _={...X};if(F9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(F9(L)&&F9(z))_[Q]=m6(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=u6(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function n6(X,$,Z="replace"){return C4(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function I1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!I1(X[Z],$[Z]))return!1;return!0}if(F9(X)&&F9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!I1(X[U],$[U]))return!1}return!0}return!1}function F9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class i6{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=T$.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!o$(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new f8(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new f8(X,Error("Configuration must export a valid object"),"unknown");let K={config:n6($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)T$.setWithFileCheck("file",K,X,_);return K}catch(j){throw j instanceof Error?e9.configLoad(X,j):e9.configLoad(X,Error(String(j)))}};if(Q)return YZ.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(wZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let Y=$===void 0?[]:Array.isArray($)?$:[$];for(let _ of Y){if(!_)continue;if(Z.push(_,`.${_}.config`,`${_}.config`,`.${_}`),X)Z.push(`${X}.${_}.config`,`.${X}.${_}.config`)}let U=new Set;return Z.filter((_)=>{if(!_||U.has(_))return!1;return U.add(_),!0})}checkFileAccess(X){return H4(async()=>{return o$(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!o$(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=wZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=wZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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((Z)=>Z.test(X))}async validateConfigFile(X){let $=[];try{if(!o$(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class l6{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await YZ.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!i2($))throw new g8($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new g8($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:$U},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function N4(X){if(!X)return"";let $=Array.isArray(X)?X.filter(Boolean):[X];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Z)=>`"${Z}"`).join(", ")}`}class s6{fileLoader=new i6;envProcessor=new a1;validator=new l6;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)W9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){if(L instanceof Error&&L.name==="ConfigNotFoundError")throw L;let z=Date.now()-$;throw W9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||N8.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(L9(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw e9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${N4(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?a$(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)W9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)W9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?a$(X,Z,U):Z,L=[L9(zX(),".config",X),L9(zX(),".config"),zX()];for(let z of L){if(U)W9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)W9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?a$(X,Y,_):Y;try{let z=L9(Z,"package.json");if(!Q2(z))return null;let j={};try{j=JSON.parse(z2(z,"utf8"))}catch(G){if(_)W9.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let E=j[X],V=X;if(!E&&$){let G=Array.isArray($)?$:[$];for(let J of G){if(!J)continue;if(j[J]){E=j[J],V=J;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)W9.success(`Configuration loaded from package.json: ${V}`);return{config:n6(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)W9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:a$(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw e9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return T$.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);T$.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias){let Y=Array.isArray($.alias)?$.alias.join(","):$.alias;Z.push(`alias:${Y}`)}if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,L9(X,"config"),L9(X,".config"),$?L9(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(L9(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[L9(zX(),".config",X),L9(zX(),".config"),zX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}async function S4(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await M8.loadConfig(X);else Y=await M8.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)W9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let L=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await M8.applyEnvironmentVariables(L.name||"",$,!0,L.verbose||!1))?.config??$;return $}}function a$(X,$,Z=!1){let Y=new a1,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=N8.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}var T$,YZ,o6,A4=(X)=>X,k4=(X,$)=>{for(var Z in $)o6(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:l2.bind($,Z)})},x4=(X,$)=>()=>(X&&($=X(X=0)),$),qZ,r6,xX,N$,o5,B4,y4,r5,J8,K1,f0,R0,h4,a5,v4,t5,b4,f4,PZ,g4,e5,XY,TZ,d4,p4,c4,m4,W8,a6,u4,g0,n4,i4,$Y,V8,R1,A0,j0,l4,ZY,s4,YY,o4,r4,NZ,a4,UY,_Y,t4,SZ,e4,X_,$_,Z_,Y_,I8,t6,U_,__="0.15.6",$9,K8,$$,AZ,kZ,R8,xZ,BZ,Z$,yZ,hZ,p9,QY,e6,V9,A9,zY,LY,jY,EY,vZ,Y$,Q_,k0,E0,z_,GY,L_,FY,j_,E_,bZ,G_,OY,JY,F_,fZ,O_,J_,W_,V_,I_,D8,XU,K_,J9,WY,f8,VY,IY,D1,KY,RY,g8,DY,MY,e9,$U,W9,M8,R_,D_,M_=e(()=>{T$=new x6,YZ=new B6,o6=Object.defineProperty,qZ={},k4(qZ,{withErrorRecovery:()=>v6,tryLoadConfig:()=>V4,loadConfigWithResult:()=>J4,loadConfig:()=>p6,isRetryableError:()=>L4,isConfigNotFoundError:()=>z4,isBunfigError:()=>b6,globalPerformanceMonitor:()=>N$,globalCache:()=>xX,getEnvOrDefault:()=>j4,generateConfigTypes:()=>I4,defaultGeneratedDir:()=>LY,defaultConfigDir:()=>zY,deepMergeWithArrayStrategy:()=>o1,deepMerge:()=>f6,createLibraryConfig:()=>K4,config:()=>W4,bunfigPlugin:()=>R4,applyEnvVarsToConfig:()=>lX,TypeGenerationError:()=>BZ,SchemaValidationError:()=>Z$,PluginError:()=>hZ,PerformanceMonitor:()=>J1,FileSystemError:()=>xZ,ErrorFactory:()=>p9,EnvVarError:()=>R8,EnvProcessor:()=>$Z,ConfigValidator:()=>r1,ConfigValidationError:()=>AZ,ConfigNotFoundError:()=>K8,ConfigMergeError:()=>kZ,ConfigLoader:()=>V1,ConfigLoadError:()=>$$,ConfigFileLoader:()=>ZZ,ConfigCache:()=>O1,CacheUtils:()=>o5,BunfigError:()=>$9,BrowserConfigError:()=>yZ,ArrayMergeStrategies:()=>QY}),jY=x4(async()=>{r6=import.meta.require,xX=new O1,N$=new J1,o5={createKey:s2,isEquivalent:o2,estimateMemoryUsage:r2},B4=k8(F1.cwd(),"config"),y4=k8(F1.cwd(),"src/generated"),r5=A8.env.CLARITY_LOG_DIR||O2(e2(),"logs"),J8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:r5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},K1=await X4(),f0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,reset:"\x1B[0m"},R0=f0,h4=f0.red,a5=f0.green,v4=f0.yellow,t5=f0.blue,b4=f0.magenta,f4=f0.cyan,PZ=f0.white,g4=f0.gray,e5=f0.bgRed,XY=f0.bgYellow,TZ=f0.bold,d4=f0.dim,p4=f0.italic,c4=f0.underline,m4=f0.reset,W8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a6={debug:"\uD83D\uDD0D",info:t5("\u2139"),success:a5("\u2713"),warning:XY(PZ(TZ(" WARN "))),error:e5(PZ(TZ(" ERROR ")))},u4=new y8("stacks"),g0=new y8("bunfig",{showTags:!0}),n4=u0(P$.cwd(),"config"),i4=u0(P$.cwd(),"src/generated"),$Y=S8.env.CLARITY_LOG_DIR||G2(U4(),"logs"),V8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$Y,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},R1=await _4(),A0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},j0=A0,l4=A0.red,ZY=A0.green,s4=A0.yellow,YY=A0.blue,o4=A0.magenta,r4=A0.cyan,NZ=A0.white,a4=A0.gray,UY=A0.bgRed,_Y=A0.bgYellow,t4=A0.bgGray,SZ=A0.bold,e4=A0.dim,X_=A0.italic,$_=A0.underline,Z_=A0.strikethrough,Y_=A0.reset,I8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t6={debug:"\uD83D\uDD0D",info:YY("\u2139"),success:ZY("\u2713"),warning:_Y(NZ(SZ(" WARN "))),error:UY(NZ(SZ(" ERROR ")))},U_=new v8("stacks"),$9=class extends Error{timestamp;context;constructor($,Z={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,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(([Z,Y])=>`${Z}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},K8=class extends $9{code="CONFIG_NOT_FOUND";constructor($,Z,Y){let U=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:Z,searchPathCount:Z.length})}},$$=class extends $9{code="CONFIG_LOAD_ERROR";constructor($,Z,Y){super(`Failed to load configuration from "${$}": ${Z.message}`,{configPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},AZ=class extends $9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},kZ=class extends $9{code="CONFIG_MERGE_ERROR";constructor($,Z,Y,U){super(`Failed to merge configuration from "${$}" with "${Z}": ${Y.message}`,{sourcePath:$,targetPath:Z,configName:U,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},R8=class extends $9{code="ENV_VAR_ERROR";constructor($,Z,Y,U){super(`Failed to parse environment variable "${$}" with value "${Z}" as ${Y}`,{envKey:$,envValue:Z,expectedType:Y,configName:U})}},xZ=class extends $9{code="FILE_SYSTEM_ERROR";constructor($,Z,Y){super(`File system ${$} failed for "${Z}": ${Y.message}`,{operation:$,path:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},BZ=class extends $9{code="TYPE_GENERATION_ERROR";constructor($,Z,Y){super(`Failed to generate types from "${$}" to "${Z}": ${Y.message}`,{configDir:$,outputPath:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Z$=class extends $9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},yZ=class extends $9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},hZ=class extends $9{code="PLUGIN_ERROR";constructor($,Z,Y){super(`Plugin "${$}" failed during ${Z}: ${Y.message}`,{pluginName:$,operation:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},p9={configNotFound(X,$,Z){return new K8(X,$,Z)},configLoad(X,$,Z){return new $$(X,$,Z)},configValidation(X,$,Z){return new AZ(X,$,Z)},configMerge(X,$,Z,Y){return new kZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new R8(X,$,Z,Y)},fileSystem(X,$,Z){return new xZ(X,$,Z)},typeGeneration(X,$,Z){return new BZ(X,$,Z)},schemaValidation(X,$,Z){return new Z$(X,$,Z)},browserConfig(X,$,Z,Y){return new yZ(X,$,Z,Y)},plugin(X,$,Z){return new hZ(X,$,Z)}},QY={replace:"replace",concat:"concat",smart:"smart"},e6=/^https?:\/\//,V9=new v8("bunfig",{showTags:!0}),A9=new V1,zY=i0(t9.cwd(),"config"),LY=i0(t9.cwd(),"src/generated")}),EY=x8.env.CLARITY_LOG_DIR||h2(D4(),"logs"),vZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Y$={...vZ},Q_=(async()=>{try{let{loadConfig:X}=await jY().then(()=>qZ),$=await X({name:"clarity",alias:"logging",defaultConfig:vZ,cwd:x8.cwd()});if($)Object.assign(Y$,$)}catch{}return Y$})(),k0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},E0=k0,z_=k0.red,GY=k0.green,L_=k0.yellow,FY=k0.blue,j_=k0.magenta,E_=k0.cyan,bZ=k0.white,G_=k0.gray,OY=k0.bgRed,JY=k0.bgYellow,F_=k0.bgGray,fZ=k0.bold,O_=k0.dim,J_=k0.italic,W_=k0.underline,V_=k0.strikethrough,I_=k0.reset,D8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XU={debug:"\uD83D\uDD0D",info:FY("\u2139"),success:GY("\u2713"),warning:JY(bZ(fZ(" WARN "))),error:OY(bZ(fZ(" ERROR ")))},K_=new b8("stacks"),J9=class extends Error{timestamp;context;constructor($,Z={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,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(([Z,Y])=>`${Z}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},WY=class extends J9{code="CONFIG_NOT_FOUND";constructor($,Z,Y){let U=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],_="";if(U.length===1)_=` or alias "${U[0]}"`;else if(U.length>1)_=` or aliases ${U.map((Q)=>`"${Q}"`).join(", ")}`;super(`Configuration "${$}"${_} not found`,{configName:$,alias:Y,searchPaths:Z,searchPathCount:Z.length})}},f8=class extends J9{code="CONFIG_LOAD_ERROR";constructor($,Z,Y){super(`Failed to load configuration from "${$}": ${Z.message}`,{configPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},VY=class extends J9{code="CONFIG_VALIDATION_ERROR";constructor($,Z,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},IY=class extends J9{code="CONFIG_MERGE_ERROR";constructor($,Z,Y,U){super(`Failed to merge configuration from "${$}" with "${Z}": ${Y.message}`,{sourcePath:$,targetPath:Z,configName:U,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},D1=class extends J9{code="ENV_VAR_ERROR";constructor($,Z,Y,U){super(`Failed to parse environment variable "${$}" with value "${Z}" as ${Y}`,{envKey:$,envValue:Z,expectedType:Y,configName:U})}},KY=class extends J9{code="FILE_SYSTEM_ERROR";constructor($,Z,Y){super(`File system ${$} failed for "${Z}": ${Y.message}`,{operation:$,path:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},RY=class extends J9{code="TYPE_GENERATION_ERROR";constructor($,Z,Y){super(`Failed to generate types from "${$}" to "${Z}": ${Y.message}`,{configDir:$,outputPath:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},g8=class extends J9{code="SCHEMA_VALIDATION_ERROR";constructor($,Z,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:Z,errorCount:Z.length})}},DY=class extends J9{code="BROWSER_CONFIG_ERROR";constructor($,Z,Y,U){super(`Failed to fetch configuration from "${$}": ${Z} ${Y}`,{endpoint:$,status:Z,statusText:Y,configName:U})}},MY=class extends J9{code="PLUGIN_ERROR";constructor($,Z,Y){super(`Plugin "${$}" failed during ${Z}: ${Y.message}`,{pluginName:$,operation:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},e9={configNotFound(X,$,Z){return new WY(X,$,Z)},configLoad(X,$,Z){return new f8(X,$,Z)},configValidation(X,$,Z){return new VY(X,$,Z)},configMerge(X,$,Z,Y){return new IY(X,$,Z,Y)},envVar(X,$,Z,Y){return new D1(X,$,Z,Y)},fileSystem(X,$,Z){return new KY(X,$,Z)},typeGeneration(X,$,Z){return new RY(X,$,Z)},schemaValidation(X,$,Z){return new g8(X,$,Z)},browserConfig(X,$,Z,Y){return new DY(X,$,Z,Y)},plugin(X,$,Z){return new MY(X,$,Z)}},$U=/^https?:\/\//,W9=new b8("bunfig",{showTags:!0}),M8=new s6,R_=L9(N8.cwd(),"config"),D_=L9(N8.cwd(),"src/generated")});function J0(X=f.dialect){return X==="mysql"||X==="singlestore"}function i(X){if(f.dialect==="postgres")return`$${X}`;return"?"}function h0(X,$=1){if(X<=0)return"";if(f.dialect==="postgres"){let Z=`$${$}`;for(let Y=1;Y<X;Y++)Z+=`, $${$+Y}`;return Z}return X===1?"?":`?${", ?".repeat(X-1)}`}async function EG(){if(!U$)U$=await S4({name:"query-builder",alias:"qb",defaultConfig:M1}),H_(U$);return f}function H_(X){if(X.dialect&&mX&&X.dialect!==mX){let $=`${mX}->${X.dialect}`;if(!H1.has($))H1.add($),console.warn(`[query-builder] setConfig({ dialect: '${X.dialect}' }) overrides a previous setConfig({ dialect: '${mX}' }). Config is process-wide; in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(X.dialect)mX=X.dialect;if(Object.assign(f,X),X.database)f.database={...f.database,...X.database};if(X.timestamps)f.timestamps={...f.timestamps,...X.timestamps};if(X.pagination)f.pagination={...f.pagination,...X.pagination};if(X.softDeletes)f.softDeletes={...f.softDeletes,...X.softDeletes};if(U$)Object.assign(U$,f)}var M1,HY,f,U$=null,mX=null,H1,d0=e(()=>{M_(),M1={verbose:!0,dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},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}},HY=Symbol.for("bun-query-builder.config"),f=globalThis[HY]??={...M1},H1=new Set});function C_(){let X=f.sqlite?.pragmas;return Array.isArray(X)?X:ZU}function t1(X){for(let $ of C_())try{X.run($)}catch{}}var ZU,e1=e(()=>{d0(),ZU=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]}),{SQL:CY}=globalThis.Bun;class YU{db;constructor(X){if(X!==":memory:"&&!X.startsWith(":")){let $=P_(X);if($&&$!==".")q_($,{recursive:!0})}this.db=new w_(X),t1(this.db)}query(X,$=[]){return this.db.prepare(X).all(...$)}run(X,$=[]){return this.db.prepare(X).run(...$)}close(){this.db.close()}get database(){return this.db}}function wY(X){return{__raw:!0,value:X,toString:()=>X}}function qY(X){let $=X.trimStart();for(;;)if($.startsWith("--")){let Z=$.indexOf(`
66
+ `);$=Z===-1?"":$.slice(Z+1).trimStart()}else if($.startsWith("/*")){let Z=$.indexOf("*/");$=Z===-1?"":$.slice(Z+2).trimStart()}else return $}function T_(X){let $=[],Z="",Y=!1,U=!1,_=!1,Q=!1;for(let z=0;z<X.length;z++){let j=X[z],E=X[z+1];if(!Y&&!U&&!Q&&j==="-"&&E==="-"){_=!0,Z+=j;continue}if(_&&(j===`
67
+ `||j==="\r")){_=!1,Z+=j;continue}if(!Y&&!U&&!_&&j==="/"&&E==="*"){Q=!0,Z+=j;continue}if(Q&&j==="*"&&E==="/"){Q=!1,Z+=j+E,z++;continue}if(_||Q){Z+=j;continue}if(j==="'"&&!U){if(Y&&E==="'"){Z+=j+E,z++;continue}Y=!Y,Z+=j;continue}if(j==='"'&&!Y){U=!U,Z+=j;continue}if(j===";"&&!Y&&!U){let V=qY(Z.trim());if(V)$.push(V);Z="";continue}Z+=j}let L=qY(Z.trim());if(L)$.push(L);return $}function PY(X){let $=new YU(X);function Z(_,...Q){let L=_[0],z=[];for(let j=0;j<Q.length;j++){let E=Q[j];if(E&&typeof E==="object"&&(E.__raw||E.raw)){let V=E.__raw?E.value:typeof E.raw==="string"?E.raw:E.raw();L+=V+(_[j+1]||"")}else if(E&&typeof E==="object"&&"sql"in E&&"values"in E)L+=E.sql+(_[j+1]||""),z.push(...E.values);else if(Array.isArray(E)){let V=E.map(()=>"?").join(", ");L+=V+(_[j+1]||""),z.push(...E)}else L+=`?${_[j+1]||""}`,z.push(E)}return{sql:L,values:z,execute:()=>{try{let j=L.trim().toUpperCase();if(j.startsWith("SELECT")||j.startsWith("PRAGMA")){let E=$.query(L,z);return Promise.resolve(E)}else{let E=$.run(L,z);return Promise.resolve(E)}}catch(j){return Promise.reject(j)}},raw:()=>L,toString:()=>L,cancel:()=>{}}}function Y(_,...Q){if(Array.isArray(_)&&"raw"in _)return Z(_,...Q);if(typeof _==="string")return wY(_);return Z([""])}Y.raw=(_)=>wY(_),Y.unsafe=(_,Q=[])=>{let L=()=>{try{let z=_.trim().toUpperCase();if(z.startsWith("SELECT")||z.startsWith("PRAGMA")){let j=$.query(_,Q);return Promise.resolve(j)}else{let j=$.run(_,Q);return Promise.resolve(j)}}catch(z){return Promise.reject(z)}};return{sql:_,values:Q,execute:L,then:(z,j)=>L().then(z,j),raw:()=>_,toString:()=>_,cancel:()=>{}}},Y.close=()=>{return $.close(),Promise.resolve()},Y.query=(_,Q)=>{try{let L=$.query(_,Q||[]);return Promise.resolve(L)}catch(L){return Promise.reject(L)}},Y.file=async(_,Q)=>{try{let{readFileSync:L}=await import("fs"),z=L(_,"utf-8"),j=T_(z);for(let E of j){let V=E.trim();if(!V||V.startsWith("--"))continue;let G=V.toUpperCase();if(G.startsWith("SELECT")||G.startsWith("PRAGMA"))$.query(E);else $.run(E)}return Promise.resolve([])}catch(L){return Promise.reject(L)}};let U=0;return Y.begin=async(_,Q)=>{let L=typeof _==="function"?_:Q;if(typeof L!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let z=U>0,j=`qb_sp_${U}`;if(z)$.run(`SAVEPOINT ${j}`);else $.run("BEGIN");U++;try{let E=await L(Y);if(U--,z)$.run(`RELEASE SAVEPOINT ${j}`);else $.run("COMMIT");return E}catch(E){U--;try{if(z)$.run(`ROLLBACK TO SAVEPOINT ${j}`),$.run(`RELEASE SAVEPOINT ${j}`);else $.run("ROLLBACK")}catch{}throw E}},Y.savepoint=Y.begin,Y.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},Y._wrapper=$,Y}function N_(X,$){if((X==="postgres"||X==="mysql"||X==="singlestore")&&t$.env.DB_CONNECTION===X){let j=t$.env,E=(j.DB_DATABASE||$.database||"").replace(/^['"]|['"]$/g,""),V=j.DB_USERNAME||$.username,G=j.DB_PASSWORD??$.password??"",J=j.DB_HOST||$.host||"localhost",W=j.DB_PORT||$.port,F=X==="postgres"?"postgres":"mysql",K=j.DB_SSL==="true"||j.DB_SSL==="1"||$.ssl?"?ssl=true":"";return`${F}://${V}:${G}@${J}${W?`:${W}`:""}/${E}${K}`}if($.url)return $.url;let{database:Z,username:Y,password:U,host:_="localhost",port:Q,ssl:L}=$,z=L||t$.env.DB_SSL==="true"||t$.env.DB_SSL==="1"?"?ssl=true":"";switch(X){case"postgres":return`postgres://${Y}:${U}@${_}${Q?`:${Q}`:""}/${Z}${z}`;case"mysql":case"singlestore":return`mysql://${Y}:${U}@${_}${Q?`:${Q}`:""}/${Z}${z}`;case"sqlite":if(Z===":memory:")return":memory:";return Z||":memory:";default:throw Error(`Unsupported dialect: ${X}`)}}function UU(X){if(!X)return{};let $={},Z=(Y)=>Math.max(0,Math.round(Y/1000));if(typeof X.max==="number"&&Number.isFinite(X.max))$.max=X.max;if(typeof X.idleTimeoutMs==="number"&&Number.isFinite(X.idleTimeoutMs))$.idleTimeout=Z(X.idleTimeoutMs);if(typeof X.acquireTimeoutMs==="number"&&Number.isFinite(X.acquireTimeoutMs))$.connectionTimeout=Z(X.acquireTimeoutMs);if(typeof X.maxLifetimeMs==="number"&&Number.isFinite(X.maxLifetimeMs))$.maxLifetime=Z(X.maxLifetimeMs);return $}function S_(){let X=f.dialect,$=N_(X,f.database);try{if(X==="sqlite")return PY($);let Z=UU(f.database.pool);return Object.keys(Z).length>0?new CY($,Z):new CY($)}catch(Z){if(console.error(`[query-builder] Failed to create database connection for dialect '${X}': ${Z.message}`),X==="sqlite")return PY(":memory:");throw Z}}function A_(){let X=f.database;return JSON.stringify({dialect:f.dialect,database:X.database,username:X.username,password:X.password,host:X.host,port:X.port,url:X.url,pool:UU(X.pool)})}function BX(X=!1){let $=A_();if(X||sX!==null&&C1!==$||!sX)sX=S_(),C1=$;return sX}function WG(){sX=null,C1=null}async function gZ(X){try{return await X(BX())}catch($){if($?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||$?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let Z=BX(!0);return await X(Z)}throw $}}function k_(){return new Proxy(function(){},{get(X,$){let Z=BX(),Y=Z[$];if(typeof Y==="function")return Y.bind(Z);return Y},apply(X,$,Z){return BX()(...Z)}})}var sX=null,C1=null,m,$X=e(()=>{d0(),e1(),m=k_()});async function VG(X={}){let $=X.iterations||1000,Z=X.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${$}`),console.log(`-- Operations: ${Z.join(", ")}`),console.log();let Y=K0();console.log("-- Setting up test table...");try{await m.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await m.unsafe(`
67
68
  CREATE TABLE bench_users (
68
69
  id INTEGER PRIMARY KEY AUTOINCREMENT,
69
70
  name TEXT NOT NULL,
@@ -71,10 +72,10 @@ export type ConfigOf = Config
71
72
  active INTEGER DEFAULT 1,
72
73
  created_at TEXT
73
74
  )
74
- `).execute();for(let Y=0;Y<100;Y++)await x.unsafe(`
75
+ `).execute();for(let Q=0;Q<100;Q++)await m.unsafe(`
75
76
  INSERT INTO bench_users (name, email, created_at)
76
77
  VALUES (?, ?, ?)
77
- `,[`User ${Y}`,`user${Y}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(Y){throw console.error("-- Failed to setup test table:",Y),Y}let L=[];if(X.includes("select")){let Y=[];for(let z=0;z<Z;z++){let F=performance.now();await _.selectFrom("bench_users").where({active:1}).limit(10).execute(),Y.push(performance.now()-F)}L.push({operation:"SELECT with WHERE + LIMIT",avgTime:Y.reduce((z,F)=>z+F,0)/Y.length,minTime:Math.min(...Y),maxTime:Math.max(...Y),iterations:Z})}if(X.includes("select")){let Y=[];for(let z=0;z<Z;z++){let F=performance.now();await _.selectFrom("bench_users").where({id:1}).first(),Y.push(performance.now()-F)}L.push({operation:"SELECT by ID (first)",avgTime:Y.reduce((z,F)=>z+F,0)/Y.length,minTime:Math.min(...Y),maxTime:Math.max(...Y),iterations:Z})}if(X.includes("count")){let Y=[];for(let z=0;z<Z;z++){let F=performance.now();await _.selectFrom("bench_users").count(),Y.push(performance.now()-F)}L.push({operation:"COUNT",avgTime:Y.reduce((z,F)=>z+F,0)/Y.length,minTime:Math.min(...Y),maxTime:Math.max(...Y),iterations:Z})}if(X.includes("insert")){let Y=[];for(let z=0;z<Z;z++){let F=performance.now();await _.insertInto("bench_users").values({name:`Bench User ${z}`,email:`bench${z}@example.com`,created_at:new Date().toISOString()}).execute(),Y.push(performance.now()-F)}L.push({operation:"INSERT",avgTime:Y.reduce((z,F)=>z+F,0)/Y.length,minTime:Math.min(...Y),maxTime:Math.max(...Y),iterations:Z})}if(X.includes("update")){let Y=[];for(let z=0;z<Z;z++){let F=performance.now();await _.updateTable("bench_users").set({active:0}).where({id:1}).execute(),Y.push(performance.now()-F)}L.push({operation:"UPDATE by ID",avgTime:Y.reduce((z,F)=>z+F,0)/Y.length,minTime:Math.min(...Y),maxTime:Math.max(...Y),iterations:Z})}if(X.includes("delete")){let Y=[],z=[];for(let F=0;F<Z;F++){let E=await _.insertInto("bench_users").values({name:"To Delete",email:`delete${F}@example.com`,created_at:new Date().toISOString()}).execute();z.push(E)}for(let F=0;F<Z;F++){let E=performance.now();await _.deleteFrom("bench_users").where({id:z[F]}).execute(),Y.push(performance.now()-E)}L.push({operation:"DELETE by ID",avgTime:Y.reduce((F,E)=>F+E,0)/Y.length,minTime:Math.min(...Y),maxTime:Math.max(...Y),iterations:Z})}console.log("-- Benchmark Results"),console.log();let j=Math.max(...L.map((Y)=>Y.operation.length));console.log("Operation".padEnd(j+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(j+2+12+12+12+12));for(let Y of L){let z=Y.operation.padEnd(j+2),F=Y.avgTime.toFixed(3).padStart(12),E=Y.minTime.toFixed(3).padStart(12),U=Y.maxTime.toFixed(3).padStart(12),V=(1000/Y.avgTime).toFixed(0).padStart(12);console.log(`${z}${F}${E}${U}${V}`)}console.log();try{await x.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(Y){console.error("-- Warning: Failed to cleanup test table:",Y)}}var yL=n(()=>{G8(),P0()});function AL($){return $.endsWith("s")?$.slice(0,-1):$}function H8($,Z,X,_={}){let L=_.singularize??AL,Y=$.relations?.[Z]?.belongsToMany?.[X];if(Y==null)return null;let z=typeof Y==="object",F=z?Y:null,E=z?F.model:Y,U=$.modelToTable[E]||E,V,Q;if(F?.table)V=F.table;else if(F?.through){if(Q=F.through,V=$.modelToTable[F.through],!V)throw Error(`[query-builder] belongsToMany relation '${X}' on '${Z}' references unknown through model '${F.through}'. Make sure '${F.through}' is registered via defineModels({...}).`)}else{let M=L(Z),J=L(U);V=[M,J].sort().join("_")}let O=F?.foreignKey??`${L(Z)}_id`,K=F?.relatedKey??`${L(U)}_id`,I={};if(F?.pivot?.columns)Object.assign(I,F.pivot.columns);if(Q&&_.models){let M=_.models[Q],J=M?.definition??M?.getDefinition?.()??M,N=J?.attributes??{};for(let[T,v]of Object.entries(N)){if(T===O||T===K||T===(J?.primaryKey??"id"))continue;I[T]={default:v?.default,nullable:v?.nullable,validation:v?.validation}}}let C=Boolean(F?.pivot?.timestamps),D=Object.keys(I);return{pivotTable:V,fkParent:O,fkRelated:K,pivotColumns:D,pivotColumnDefs:I,pivotModelName:Q,timestamps:C,relatedModelName:E,relatedTable:U,hasConfig:z}}function*aU($,Z={}){let X=$.relations;if(!X)return;for(let[_,L]of Object.entries(X)){let j=L?.belongsToMany;if(!j)continue;for(let Y of Object.keys(j)){let z=H8($,_,Y,Z);if(z)yield{parentTable:_,relationKey:Y,resolved:z}}}}function i6($){return typeof $==="object"&&$!==null&&"raw"in $&&typeof $.raw==="string"}class H2{cache=new Map;maxSize=100;get($){let Z=this.cache.get($);if(!Z)return null;if(Date.now()>Z.expiresAt)return this.cache.delete($),null;return Z.data}set($,Z,X){if(this.cache.size>=this.maxSize){let _=this.cache.keys().next().value;if(_)this.cache.delete(_)}this.cache.set($,{data:Z,expiresAt:Date.now()+X})}clear(){this.cache.clear()}setMaxSize($){this.maxSize=$}}function vL($){let Z=String($?.message||"").toLowerCase();return Z.includes("deadlock")||Z.includes("serialization failure")||Z.includes("could not serialize access")||Z.includes("deadlock found when trying to get lock")||Z.includes("lock wait timeout exceeded")||Z.includes("database is locked")||Z.includes("busy")}function bL($,Z){if(!Z||Z.length===0)return!1;let X=$&&($.code||$.sqlState||$.sqlstate);if(!X)return!1;return Z.includes(X)}function fL($){return new Promise((Z)=>setTimeout(Z,$))}function gL($,Z){let X=Math.max(1,Z?.baseMs??50),_=Math.max(1,Z?.factor??2),L=Math.max(X,Z?.maxMs??2000),j=Math.min(L,X*_**Math.max(0,$-1));if(Z?.jitter){let Y=Math.random()*j*0.2;j=j-Y/2}return Math.floor(j)}function W0($){let Z=$?.sql??Z1(),X=$?.meta,_=$?.schema;function L(U){if(Array.isArray(U)){let[I,C,D]=U,M=String(I);switch(C){case"in":if(Array.isArray(D)){let J=f0(D.length);return Z.unsafe(`${M} IN (${J})`,D)}return Z.unsafe(`${M} IN (${m(1)})`,[D]);case"not in":if(Array.isArray(D)){let J=f0(D.length);return Z.unsafe(`${M} NOT IN (${J})`,D)}return Z.unsafe(`${M} NOT IN (${m(1)})`,[D]);case"like":return Z.unsafe(`${M} LIKE ${m(1)}`,[D]);case"is":return Z.unsafe(`${M} IS ${D}`);case"is not":return Z.unsafe(`${M} IS NOT ${D}`);case"!=":return Z.unsafe(`${M} <> ${m(1)}`,[D]);case"<":case">":case"<=":case">=":case"=":default:return Z.unsafe(`${M} ${C} ${m(1)}`,[D])}}if("raw"in U)return U.raw;let V=Object.keys(U);if(V.length===0)return Z.unsafe("");let Q=[],O=[],K=1;for(let I of V){let C=U[I];if(Array.isArray(C)){let D=f0(C.length,K);Q.push(`${I} IN (${D})`),O.push(...C),K+=C.length}else Q.push(`${I} = ${m(K++)}`),O.push(C)}return Z.unsafe(Q.join(" AND "),O)}function j(U,V,Q){if(!Q)return V;let O=L(Q);return Z`${V} WHERE ${O}`}function Y(U){let V=y.debug?.captureText;if(y.debug)y.debug.captureText=!0;let Q=String(U);if(y.debug)y.debug.captureText=V;return Q}function z(U,V,Q){let O=y.hooks,K=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan),I=Q?.timeoutMs&&Q.timeoutMs>0||Q?.signal;if(!K&&!I)return U.execute();let C=Y(U),D=Date.now(),M;try{if(O?.onQueryStart?.({sql:C,kind:V}),O?.startSpan)M=O.startSpan({sql:C,kind:V})}catch{}let J=!1,N=(f,p)=>{if(J)return;J=!0;let g=Date.now()-D;try{if(f)O?.onQueryError?.({sql:C,error:f,durationMs:g,kind:V});else O?.onQueryEnd?.({sql:C,durationMs:g,rowCount:p,kind:V})}catch{}try{M?.end(f)}catch{}},T=U.execute(),v=[T],b;if(Q?.timeoutMs&&Q.timeoutMs>0){let f=new Promise((p,g)=>{b=setTimeout(()=>{try{U.cancel?.()}catch{}let t=Error(`Query timed out after ${Q.timeoutMs}ms`);t.code="EBQBTIMEOUT",g(t)},Q.timeoutMs)});v.push(f)}if(Q?.signal){if(Q.signal.aborted){try{U.cancel?.()}catch{}let p=Error("Query aborted");return p.code="EBQBABORT",N(p),Promise.reject(p)}let f=()=>{try{U.cancel?.()}catch{}};Q.signal.addEventListener("abort",f,{once:!0}),T.finally(()=>{Q.signal?.removeEventListener("abort",f)})}return Promise.race(v).then((f)=>{clearTimeout(b);let p=Array.isArray(f)?f.length:typeof f==="number"?f:void 0;return N(void 0,p),f}).catch((f)=>{throw clearTimeout(b),N(f),f})}function F(U,V){let Q=V??Y(U);return{sql:Q,toString:()=>Q,execute:()=>U.execute(),values:()=>U.values(),raw:()=>U.raw()}}function E(U,V){let Q=Z,O=V&&V.length>0?`SELECT ${V.join(", ")} FROM ${String(U)}`:`SELECT * FROM ${String(U)}`,K=null,I=()=>{if(K===null)K=h.length>0?Z.unsafe(O,h):Z.unsafe(O);return K},C=(G,W)=>{let R=c.WHERE.test(O)?G:"WHERE";O=`${O} ${R} ${W}`},D=new Set,M,J,N=!1,T=!1,v=!1,b=new Map,f=new Set,p=60000,g=(G)=>{if(y.relations.singularizeStrategy==="none")return G;return G.endsWith("s")?G.slice(0,-1):G},t=(G)=>{if(!X)return null;return H8(X,String(U),G,{singularize:g,models:X.models})},c0=(G)=>{if(!G||typeof G!=="object"||f.size===0)return G;let W;for(let S of Object.keys(G))if(S.startsWith("pivot_")){if(!W)W={};W[S.slice(6)]=G[S],delete G[S]}if(W)G.pivot=W;return G},z9=(G)=>{if(f.size===0||!G)return G;if(Array.isArray(G))for(let W=0;W<G.length;W++)c0(G[W]);else c0(G);return G},w9=(G)=>{if(!X)return;if(D.has(G.pivotTable))return;let W=String(U),S=X.primaryKeys[W]??"id";u(G.pivotTable,"wherePivot auto-join (pivot table)"),u(G.fkParent,"wherePivot auto-join (parent FK)"),u(W,"wherePivot auto-join (parent table)"),u(S,"wherePivot auto-join (parent PK)"),K=Q`${I()} LEFT JOIN ${Q(G.pivotTable)} ON ${Q(`${G.pivotTable}.${G.fkParent}`)} = ${Q(`${W}.${S}`)}`,O=`${O} LEFT JOIN ${G.pivotTable} ON ${G.pivotTable}.${G.fkParent} = ${W}.${S}`,D.add(G.pivotTable)},G0=[],h=[],u=(G,W)=>{if(!c.IDENTIFIER.test(G)){let S=W?` in ${W}`:"";throw Error(`[query-builder] Invalid identifier${S}: '${G}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}},t$=(G)=>{if(c.SELECT_STAR.test(O))O=O.replace(c.SELECT_STAR,`SELECT *, ${G}`);else if(c.SELECT.test(O))O=O.replace(c.SELECT_FROM,`SELECT $1, ${G} FROM`);let W=String(I());if(c.SELECT_STAR.test(W)){let S=W.replace(c.SELECT_STAR,`SELECT *, ${G}`);K=Z.unsafe(S)}else if(c.SELECT.test(W)){if(c.SELECT_FROM.exec(W)){let R=W.replace(c.SELECT_FROM,`SELECT $1, ${G} FROM`);K=Z.unsafe(R)}}},U1=(G,W,S,R)=>{u(G,"relationship subquery (parent table)"),u(W,"relationship subquery (target table)"),u(S,"relationship subquery (primary key)");let w=`${G.endsWith("s")?G.slice(0,-1):G}_id`;u(w,"relationship subquery (foreign key)");let q=`SELECT 1 FROM ${W} WHERE ${W}.${w} = ${G}.${S}`;if(R){let P=R({where:(A,H,B)=>{return u(A,"relationship subquery condition"),`${W}.${A} ${H} ${typeof B==="string"?`'${B}'`:B}`}});if(P)q+=` AND ${P}`}return q},E1=(G,W,S,R)=>{u(G,"relationship subquery (parent table)"),u(W,"relationship subquery (target table)"),u(S,"relationship subquery (primary key)");let w=`${W.endsWith("s")?W.slice(0,-1):W}_id`;u(w,"relationship subquery (foreign key)");let q=`SELECT 1 FROM ${W} WHERE ${W}.${S} = ${G}.${w}`;if(R){let P=R({where:(A,H,B)=>{return u(A,"relationship subquery condition"),`${W}.${A} ${H} ${typeof B==="string"?`'${B}'`:B}`}});if(P)q+=` AND ${P}`}return q},O1=(G,W,S,R,w,q)=>{u(G,"relationship subquery (parent table)"),u(W,"relationship subquery (target table)"),u(S,"relationship subquery (primary key)"),u(R,"relationship subquery (target primary key)");let k=q&&X?H8(X,G,q,{singularize:g,models:X.models}):null,P=g(G),A=g(W),H=k?.pivotTable??[P,A].sort().join("_"),B=k?.fkParent??`${P}_id`,d=k?.fkRelated??`${A}_id`;u(H,"relationship subquery (pivot table)"),u(B,"relationship subquery (foreign key A)"),u(d,"relationship subquery (foreign key B)");let l=`SELECT 1 FROM ${H} JOIN ${W} ON ${W}.${R} = ${H}.${d} WHERE ${H}.${B} = ${G}.${S}`;if(w){let s=w({where:(q9,D8,y9)=>{return u(q9,"relationship subquery condition"),`${W}.${q9} ${D8} ${typeof y9==="string"?`'${y9}'`:y9}`}});if(s)l+=` AND ${s}`}return l},gX=(G,W,S)=>{u(G,"withCount (parent table)"),u(W,"withCount (target table)"),u(S,"withCount (primary key)");let R=`${G.endsWith("s")?G.slice(0,-1):G}_id`;return u(R,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${W} WHERE ${W}.${R} = ${G}.${S})`},pX=(G,W,S,R)=>{u(G,"withCount (parent table)"),u(W,"withCount (target table)"),u(S,"withCount (primary key)");let w=R&&X?H8(X,G,R,{singularize:g,models:X.models}):null,q=g(G),k=g(W),P=w?.pivotTable??[q,k].sort().join("_"),A=w?.fkParent??`${q}_id`;return u(P,"withCount (pivot table)"),u(A,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${P} WHERE ${P}.${A} = ${G}.${S})`},AZ=()=>{if(b.size===0)return;let G=[];for(let[W,S]of b.entries()){let R=t(W);if(!R)continue;for(let q of S)u(q,"withPivot");let w=S.map((q)=>`${R.pivotTable}.${q} AS pivot_${q}`);G.push(...w)}if(G.length>0){let W=G.join(", ");t$(W)}};return new Proxy({distinct(){return O=O.replace(/^SELECT\s+/i,"SELECT DISTINCT "),K=null,this},distinctOn(...G){let W=G.map(String).join(", ");return O=O.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${W}) `),K=null,this},selectRaw(G){let W=O.indexOf(" FROM ");if(W!==-1)O=`${O.substring(0,W)}, ${String(G)}${O.substring(W)}`;else O+=`, ${String(G)}`;return K=null,this},rowNumber(G="row_number",W,S){let R=[];if(W){let P=Array.isArray(W)?W:[W];R.push(`PARTITION BY ${P.join(", ")}`)}if(S&&S.length)R.push(`ORDER BY ${S.map(([P,A])=>`${P} ${A==="desc"?"DESC":"ASC"}`).join(", ")}`);let q=`ROW_NUMBER() ${R.length?`OVER (${R.join(" ")})`:"OVER ()"} AS ${G}`,k=O.indexOf(" FROM ");if(k!==-1)O=`${O.substring(0,k)}, ${q}${O.substring(k)}`;else O+=`, ${q}`;return K=null,this},denseRank(G="dense_rank",W,S){let R=Array.isArray(W)?W:W?[W]:[],w=[];if(R.length)w.push(`PARTITION BY ${R.join(", ")}`);if(S&&S.length)w.push(`ORDER BY ${S.map(([A,H])=>`${A} ${H==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`DENSE_RANK() ${w.length?`OVER (${w.join(" ")})`:"OVER ()"} AS ${G}`,P=O.indexOf(" FROM ");if(P!==-1)O=`${O.substring(0,P)}, ${k}${O.substring(P)}`;else O+=`, ${k}`;return K=null,this},rank(G="rank",W,S){let R=Array.isArray(W)?W:W?[W]:[],w=[];if(R.length)w.push(`PARTITION BY ${R.join(", ")}`);if(S&&S.length)w.push(`ORDER BY ${S.map(([A,H])=>`${A} ${H==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`RANK() ${w.length?`OVER (${w.join(" ")})`:"OVER ()"} AS ${G}`,P=O.indexOf(" FROM ");if(P!==-1)O=`${O.substring(0,P)}, ${k}${O.substring(P)}`;else O+=`, ${k}`;return K=null,this},selectAll(){return this},select(G){if(!G||G.length===0)return this;let W=O.indexOf(" FROM ");if(W!==-1)O=`SELECT ${G.join(", ")}${O.substring(W)}`;else O=`SELECT ${G.join(", ")} FROM ${U}`;return this},addSelect(...G){if(!G.length)return this;let W=O.indexOf(" FROM ");if(W!==-1)O=`${O.substring(0,W)}, ${G.join(", ")}${O.substring(W)}`;else O+=`, ${G.join(", ")}`;return K=null,this},with(...G){if(!X||!G||G.length===0)return this;let W=[];for(let H of G){if(!H)continue;if(typeof H==="string")W.push({name:H});else if(typeof H==="object"&&!Array.isArray(H))for(let[B,d]of Object.entries(H))if(typeof d==="function")W.push({name:B,callback:d});else W.push({name:B})}if(W.length===0)return this;let S=y.relations.maxEagerLoad??50;if(W.length>S)throw Error(`[query-builder] Too many relationships to eager load (${W.length}). Maximum allowed: ${S}`);let R=String(U),w=new Set,q=new Set,k=new Map,P=(H)=>{let B=X.relations?.[H];if(!B)return[];return[...Object.keys(B.hasOne||{}),...Object.keys(B.hasMany||{}),...Object.keys(B.belongsTo||{}),...Object.keys(B.belongsToMany||{}),...Object.keys(B.hasOneThrough||{}),...Object.keys(B.hasManyThrough||{}),...Object.keys(B.morphOne||{}),...Object.keys(B.morphMany||{}),...Object.keys(B.morphToMany||{}),...Object.keys(B.morphedByMany||{})]},A=(H,B,d=0,l)=>{let D0=y.relations.maxDepth??10;if(d>=D0)throw Error(`[query-builder] Maximum relationship depth (${D0}) exceeded at '${B}'. Consider using separate queries or increasing maxDepth.`);let s=X.relations?.[H];if(!s)return H;let q9=(i,o)=>{let U0=i;if(y.softDeletes?.enabled&&y.softDeletes?.defaultFilter){let E0=y.softDeletes.column||"deleted_at";U0=`${U0} AND ${o}.${E0} IS NULL`}if(!l)return U0;let S0={where:(E0,l0,U9)=>{let S8=typeof U9==="string"?`'${U9}'`:String(U9);return`${o}.${E0} ${l0} ${S8}`}};try{let E0=l(S0);if(E0&&typeof E0==="string")return`${U0} AND ${E0}`}catch{}return U0},D8=(i)=>{if(y.softDeletes?.enabled&&y.softDeletes?.defaultFilter){let o=y.softDeletes.column||"deleted_at";return` AND ${i}.${o} IS NULL`}return""},y9=()=>{let i=(S0)=>{let E0=S0?.[B];return E0?X.modelToTable[E0]:void 0},o=(S0)=>{let E0=S0?.[B],l0=typeof E0==="string"?E0:E0?.model;return l0?X.modelToTable[l0]:void 0},U0=(S0)=>{let E0=S0?.[B];return E0?.target?X.modelToTable[E0.target]:void 0};return i(s?.hasOne)||i(s?.hasMany)||i(s?.belongsTo)||o(s?.belongsToMany)||U0(s?.hasOneThrough)||U0(s?.hasManyThrough)||i(s?.morphOne)||i(s?.morphMany)||i(s?.morphToMany)||i(s?.morphedByMany)},vZ=y9()??(X.modelToTable[B]||X.tableToModel[B]?X.modelToTable[B]??B:B),e=String(vZ);if(!vZ||!y9()&&!X.modelToTable[B]&&!X.tableToModel[B]){let i=P(H);if(i.length>0&&!i.includes(B)){let o=` Available relationships: ${i.join(", ")}`;throw Error(`[query-builder] Relationship '${B}' not found on table '${H}'.${o}`)}}if(y.relations.detectCycles!==!1){let i=`${H}->${e}`;if(w.has(i))throw Error(`[query-builder] Circular relationship detected: ${i}. This would cause an infinite loop.`);w.add(i)}if(!e||e===H)return H;let a$=s?.hasOneThrough?.[B]||s?.hasManyThrough?.[B];if(a$){let{through:i,target:o}=a$,U0=X.modelToTable[i]||i,S0=X.modelToTable[o]||o,E0=X.primaryKeys[H]??"id",l0=X.primaryKeys[U0]??"id",U9=`${g(H)}_id`,S8=`${g(U0)}_id`;return K=Q`${I()} LEFT JOIN ${Q(U0)} ON ${Q(`${U0}.${U9}`)} = ${Q(`${H}.${E0}`)} LEFT JOIN ${Q(S0)} ON ${Q(`${S0}.${S8}`)} = ${Q(`${U0}.${l0}`)}`,D.add(U0),D.add(S0),S0}if(Boolean(s?.belongsToMany?.[B])){let i=H8(X,H,B,{singularize:g,models:X.models}),o=i?.pivotTable??[g(H),g(e)].sort().join("_"),U0=X.primaryKeys[H]??"id",S0=X.primaryKeys[e]??"id",E0=i?.fkParent??`${g(H)}_id`,l0=i?.fkRelated??`${g(e)}_id`;return K=Q`${I()} LEFT JOIN ${Q(o)} ON ${Q(`${o}.${E0}`)} = ${Q(`${H}.${U0}`)} LEFT JOIN ${Q(e)} ON ${Q(`${e}.${S0}`)} = ${Q(`${o}.${l0}`)}`,D.add(o),D.add(e),e}if(Boolean(s?.morphToMany?.[B])){let i=B,o=`${g(e)}_${i}`,U0=X.primaryKeys[H]??"id",S0=X.primaryKeys[e]??"id",E0=`${i}_type`,l0=`${i}_id`,U9=`${g(e)}_id`;return K=Q`${I()} LEFT JOIN ${Q(o)} ON ${Q(`${o}.${l0}`)} = ${Q(`${H}.${U0}`)} AND ${Q(`${o}.${E0}`)} = ${Q(X.tableToModel[H]||H)} LEFT JOIN ${Q(e)} ON ${Q(`${e}.${S0}`)} = ${Q(`${o}.${U9}`)}`,D.add(o),D.add(e),e}if(Boolean(s?.morphedByMany?.[B])){let i=s.morphedByMany?.[B]||B,o=X.modelToTable[i]||i,U0=g(H),S0=`${g(o)}_${U0}`,E0=X.primaryKeys[H]??"id",l0=X.primaryKeys[o]??"id",U9=`${U0}_type`,S8=`${U0}_id`,mX=`${g(o)}_id`;return K=Q`${I()} LEFT JOIN ${Q(S0)} ON ${Q(`${S0}.${mX}`)} = ${Q(`${H}.${E0}`)} LEFT JOIN ${Q(o)} ON ${Q(`${o}.${l0}`)} = ${Q(`${S0}.${S8}`)} AND ${Q(`${S0}.${U9}`)} = ${Q(X.tableToModel[o]||o)}`,D.add(S0),D.add(o),o}if(Boolean(s?.belongsTo?.[B])){let i=`${g(e)}_id`,o=X.primaryKeys[e]??"id";return K=Q`${I()} LEFT JOIN ${Q(e)} ON ${Q(`${H}.${i}`)} = ${Q(`${e}.${o}`)}`,D.add(e),e}let dX=Boolean(s?.morphOne?.[B]),cX=Boolean(s?.morphMany?.[B]);if(dX||cX){let i=`${B}_type`,o=`${B}_id`,U0=X.primaryKeys[H]??"id";return K=Q`${I()} LEFT JOIN ${Q(e)} ON ${Q(`${e}.${o}`)} = ${Q(`${H}.${U0}`)} AND ${Q(`${e}.${i}`)} = ${Q(X.tableToModel[H]||H)}`,D.add(e),e}let bZ=`${g(H)}_id`,fZ=X.primaryKeys[H]??"id",gZ=D8(e);if(gZ){let i=String(I()),o=`${e}.${bZ} = ${H}.${fZ}${gZ}`;K=Q`${Q(i)} LEFT JOIN ${Q(e)} ON ${Q(o)}`}else K=Q`${I()} LEFT JOIN ${Q(e)} ON ${Q(`${e}.${bZ}`)} = ${Q(`${H}.${fZ}`)}`;return D.add(e),e};for(let H of W){let B=H.name.trim();if(H.callback)k.set(B,H.callback);let d=B.split("."),l=R,D0=0;for(let s of d){if(!s||s.trim().length===0)continue;let q9=s.trim(),D8=k.get(q9);l=A(l,q9,D0,D8)||l,D0++}q.add(B)}if(b.size>0){let H=[];for(let[B,d]of b.entries()){let l=t(B);if(!l)continue;let D0=d.map((s)=>`${l.pivotTable}.${s} AS pivot_${s}`);H.push(...D0)}if(H.length>0){let B=H.join(", ");t$(B)}}return O=Y(I()),this},whereHas(G,W){if(!X)return this;let S=String(U),R=X.relations?.[S];if(!R)throw Error(`[query-builder] No relationships defined for table '${S}'`);let w=Object.entries(R).find(([d,l])=>l&&typeof l==="object"&&(G in l));if(!w)throw Error(`[query-builder] Relationship '${G}' not found on table '${S}'`);let[q,k]=w,P=k[G],A=typeof P==="string"?P:P?.model||P?.target||P,H=X.modelToTable[A]||A,B;if(q==="hasMany"||q==="hasOne"){let d=X.primaryKeys[S]??"id";B=U1(S,H,d,W)}else if(q==="belongsTo"){let d=X.primaryKeys[H]??"id";B=E1(S,H,d,W)}else if(q==="belongsToMany"){let d=X.primaryKeys[S]??"id",l=X.primaryKeys[H]??"id";B=O1(S,H,d,l,W,G)}else throw Error(`[query-builder] Unsupported relationship type '${q}' for whereHas`);K=Q`${I()} WHERE EXISTS (${Q([B])})`;try{C("WHERE",`EXISTS (${B})`)}catch{}return this},whereDoesntHave(G,W){if(!X)return this;let S=String(U),R=X.relations?.[S];if(!R)throw Error(`[query-builder] No relationships defined for table '${S}'`);let w=Object.entries(R).find(([d,l])=>l&&typeof l==="object"&&(G in l));if(!w)throw Error(`[query-builder] Relationship '${G}' not found on table '${S}'`);let[q,k]=w,P=k[G],A=typeof P==="string"?P:P?.model||P?.target||P,H=X.modelToTable[A]||A,B;if(q==="hasMany"||q==="hasOne"){let d=X.primaryKeys[S]??"id";B=U1(S,H,d,W)}else if(q==="belongsTo"){let d=X.primaryKeys[H]??"id";B=E1(S,H,d,W)}else if(q==="belongsToMany"){let d=X.primaryKeys[S]??"id",l=X.primaryKeys[H]??"id";B=O1(S,H,d,l,W,G)}else throw Error(`[query-builder] Unsupported relationship type '${q}' for whereDoesntHave`);K=Q`${I()} WHERE NOT EXISTS (${Q([B])})`;try{C("WHERE",`NOT EXISTS (${B})`)}catch{}return this},has(G){if(!X)return this;let W=String(U),S=X.relations?.[W];if(!S)throw Error(`[query-builder] No relationships defined for table '${W}'`);let R=Object.entries(S).find(([B,d])=>d&&typeof d==="object"&&(G in d));if(!R)throw Error(`[query-builder] Relationship '${G}' not found on table '${W}'`);let[w,q]=R,k=q[G],P=typeof k==="string"?k:k?.model||k?.target||k,A=X.modelToTable[P]||P,H;if(w==="hasMany"||w==="hasOne"){let B=X.primaryKeys[W]??"id";H=U1(W,A,B)}else if(w==="belongsTo"){let B=X.primaryKeys[A]??"id";H=E1(W,A,B)}else if(w==="belongsToMany"){let B=X.primaryKeys[W]??"id",d=X.primaryKeys[A]??"id";H=O1(W,A,B,d,void 0,G)}else throw Error(`[query-builder] Unsupported relationship type '${w}' for has`);K=Q`${I()} WHERE EXISTS (${Q([H])})`;try{C("WHERE",`EXISTS (${H})`)}catch{}return this},doesntHave(G){if(!X)return this;let W=String(U),S=X.relations?.[W];if(!S)throw Error(`[query-builder] No relationships defined for table '${W}'`);let R=Object.entries(S).find(([B,d])=>d&&typeof d==="object"&&(G in d));if(!R)throw Error(`[query-builder] Relationship '${G}' not found on table '${W}'`);let[w,q]=R,k=q[G],P=typeof k==="string"?k:k?.model||k?.target||k,A=X.modelToTable[P]||P,H;if(w==="hasMany"||w==="hasOne"){let B=X.primaryKeys[W]??"id";H=U1(W,A,B)}else if(w==="belongsTo"){let B=X.primaryKeys[A]??"id";H=E1(W,A,B)}else if(w==="belongsToMany"){let B=X.primaryKeys[W]??"id",d=X.primaryKeys[A]??"id";H=O1(W,A,B,d,void 0,G)}else throw Error(`[query-builder] Unsupported relationship type '${w}' for doesntHave`);K=Q`${I()} WHERE NOT EXISTS (${Q([H])})`;try{C("WHERE",`NOT EXISTS (${H})`)}catch{}return this},withCount(...G){if(!X||!G||G.length===0)return this;let W=String(U);for(let S of G){let R=X.relations?.[W];if(!R)continue;let w=Object.entries(R).find(([D0,s])=>s&&typeof s==="object"&&(S in s));if(!w)continue;let[q,k]=w,P=k[S],A=typeof P==="string"?P:P?.model||P?.target||P,H=X.modelToTable[A]||A,B=X.primaryKeys[W]??"id",d;if(q==="hasMany"||q==="hasOne")d=gX(W,H,B);else if(q==="belongsToMany")d=pX(W,H,B,S);else continue;let l=`${S}_count`;t$(`${d} AS ${l}`)}return this},applyPivotColumns(){return AZ(),this},withPivot(G,...W){if(!X)return this;let S=String(U),R=t(G);if(!R)throw Error(`[query-builder] Relationship '${G}' is not a belongsToMany relationship on table '${S}'`);let w=W&&W.length>0?W:R.hasConfig?R.pivotColumns:[];if(w.length===0)return this;if(b.set(G,w),R.hasConfig)f.add(G);return AZ(),this},wherePivot(G,W,S,R){if(!X)return this;let w=t(G);if(!w)throw Error(`[query-builder] Relationship '${G}' is not a belongsToMany relationship on table '${String(U)}'`);u(w.pivotTable,"wherePivot (pivot table)"),u(W,"wherePivot (column)"),w9(w);let q=R===void 0?"=":String(S),k=R===void 0?S:R,P=h.length+1,A=`${w.pivotTable}.${W} ${q} ${m(P)}`;G0.push(A),h.push(k);let H=c.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${H} ${A}`,K=null,w.hasConfig)f.add(G);return this},wherePivotIn(G,W,S){if(!X||!Array.isArray(S)||S.length===0)return this;let R=t(G);if(!R)throw Error(`[query-builder] Relationship '${G}' is not a belongsToMany relationship on table '${String(U)}'`);u(R.pivotTable,"wherePivotIn (pivot table)"),u(W,"wherePivotIn (column)"),w9(R);let w=f0(S.length,h.length+1),q=`${R.pivotTable}.${W} IN (${w})`;G0.push(q),h.push(...S);let k=c.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${k} ${q}`,K=null,R.hasConfig)f.add(G);return this},wherePivotNotIn(G,W,S){if(!X||!Array.isArray(S)||S.length===0)return this;let R=t(G);if(!R)throw Error(`[query-builder] Relationship '${G}' is not a belongsToMany relationship on table '${String(U)}'`);u(R.pivotTable,"wherePivotNotIn (pivot table)"),u(W,"wherePivotNotIn (column)"),w9(R);let w=f0(S.length,h.length+1),q=`${R.pivotTable}.${W} NOT IN (${w})`;G0.push(q),h.push(...S);let k=c.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${k} ${q}`,K=null,R.hasConfig)f.add(G);return this},wherePivotNull(G,W){if(!X)return this;let S=t(G);if(!S)throw Error(`[query-builder] Relationship '${G}' is not a belongsToMany relationship on table '${String(U)}'`);u(S.pivotTable,"wherePivotNull (pivot table)"),u(W,"wherePivotNull (column)"),w9(S);let R=`${S.pivotTable}.${W} IS NULL`;G0.push(R);let w=c.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${w} ${R}`,K=null,S.hasConfig)f.add(G);return this},wherePivotNotNull(G,W){if(!X)return this;let S=t(G);if(!S)throw Error(`[query-builder] Relationship '${G}' is not a belongsToMany relationship on table '${String(U)}'`);u(S.pivotTable,"wherePivotNotNull (pivot table)"),u(W,"wherePivotNotNull (column)"),w9(S);let R=`${S.pivotTable}.${W} IS NOT NULL`;G0.push(R);let w=c.WHERE.test(O)?"AND":"WHERE";if(O=`${O} ${w} ${R}`,K=null,S.hasConfig)f.add(G);return this},where(G,W,S){let R=()=>O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";if(typeof G==="string"&&W!==void 0){let w=h.length+1;return G0.push(`${String(G)} ${String(W)} ${m(w)}`),h.push(S),O=`${O} ${R()} ${String(G)} ${String(W)} ${m(w)}`,K=null,this}if(Array.isArray(G)){let[w,q,k]=G,P=String(w),A=String(q);if(A==="in"||A==="not in"){let H=Array.isArray(k)?k:[k],B=f0(H.length,h.length+1);G0.push(`${P} ${A.toUpperCase()} (${B})`),h.push(...H),O=`${O} ${R()} ${P} ${A.toUpperCase()} (${B})`,K=null}else{let H=h.length+1;G0.push(`${P} ${A} ${m(H)}`),h.push(k),O=`${O} ${R()} ${P} ${A} ${m(H)}`,K=null}return this}if(G&&typeof G==="object"&&!i6(G)){let w=G,q=Object.keys(w),k=[];for(let P of q){let A=w[P];if(Array.isArray(A)){let H=f0(A.length,h.length+1);k.push(`${P} IN (${H})`),G0.push(`${P} IN (${H})`),h.push(...A)}else{let H=h.length+1;k.push(`${P} = ${m(H)}`),G0.push(`${P} = ${m(H)}`),h.push(A)}}if(k.length>0)O=`${O} ${R()} ${k.join(" AND ")}`,K=null;return this}if(i6(G))return G0.push(G.raw),O=`${O} ${R()} ${G.raw}`,K=null,this;return this},whereNull(G){let W=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return O=`${O} ${W} ${String(G)} IS NULL`,K=null,this},whereNotNull(G){let W=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return O=`${O} ${W} ${String(G)} IS NOT NULL`,K=null,this},whereBetween(G,W,S){let R=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return h.push(W,S),O=`${O} ${R} ${String(G)} BETWEEN ? AND ?`,K=null,this},whereExists(G){let W=O.toUpperCase().includes(" WHERE ")?"AND":"WHERE";return O=`${O} ${W} EXISTS (${G.toSQL()})`,K=null,this},whereJsonContains(G,W){let S=c.WHERE.test(O)?"AND":"WHERE",R=h.length+1;return O+=` ${S} ${G} @> ${m(R)}`,h.push(JSON.stringify(W)),K=null,this},whereJsonPath(G,W,S){let R=y.dialect,w=c.WHERE.test(O)?"AND":"WHERE",q=h.length+1;if(R==="postgres")O+=` ${w} ${G} ${W} ${m(q)}`;else if(R==="mysql")O+=` ${w} JSON_EXTRACT(${G}) ${W} ${m(q)}`;else O+=` ${w} json_extract(${G}) ${W} ${m(q)}`;return h.push(S),K=null,this},whereLike(G,W,S=!1){let R=S?Q`${Q(String(G))} LIKE ${W}`:Q`LOWER(${Q(String(G))}) LIKE LOWER(${W})`;return K=Q`${I()} WHERE ${R}`,C("WHERE",`${S?String(G):`LOWER(${String(G)})`} LIKE ${S?"?":"LOWER(?)"}`),this},whereILike(G,W){if(y.dialect==="postgres")K=Q`${I()} WHERE ${Q(String(G))} ILIKE ${W}`,C("WHERE",`${String(G)} ILIKE ?`);else{let S=Q`LOWER(${Q(String(G))}) LIKE LOWER(${W})`;K=Q`${I()} WHERE ${S}`,C("WHERE",`LOWER(${String(G)}) LIKE LOWER(?)`)}return this},orWhereLike(G,W,S=!1){let R=S?Q`${Q(String(G))} LIKE ${W}`:Q`LOWER(${Q(String(G))}) LIKE LOWER(${W})`;return K=Q`${I()} OR ${R}`,C("OR",`${S?String(G):`LOWER(${String(G)})`} LIKE ${S?"?":"LOWER(?)"}`),this},orWhereILike(G,W){if(y.dialect==="postgres")K=Q`${I()} OR ${Q(String(G))} ILIKE ${W}`,C("OR",`${String(G)} ILIKE ?`);else{let S=Q`LOWER(${Q(String(G))}) LIKE LOWER(${W})`;K=Q`${I()} OR ${S}`,C("OR",`LOWER(${String(G)}) LIKE LOWER(?)`)}return this},whereNotLike(G,W,S=!1){let R=S?Q`${Q(String(G))} NOT LIKE ${W}`:Q`LOWER(${Q(String(G))}) NOT LIKE LOWER(${W})`;return K=Q`${I()} WHERE ${R}`,C("WHERE",`${S?String(G):`LOWER(${String(G)})`} NOT LIKE ${S?"?":"LOWER(?)"}`),this},whereNotILike(G,W){if(y.dialect==="postgres")K=Q`${I()} WHERE ${Q(String(G))} NOT ILIKE ${W}`,C("WHERE",`${String(G)} NOT ILIKE ?`);else{let S=Q`LOWER(${Q(String(G))}) NOT LIKE LOWER(${W})`;K=Q`${I()} WHERE ${S}`,C("WHERE",`LOWER(${String(G)}) NOT LIKE LOWER(?)`)}return this},orWhereNotLike(G,W,S=!1){let R=S?Q`${Q(String(G))} NOT LIKE ${W}`:Q`LOWER(${Q(String(G))}) NOT LIKE LOWER(${W})`;return K=Q`${I()} OR ${R}`,C("OR",`${S?String(G):`LOWER(${String(G)})`} NOT LIKE ${S?"?":"LOWER(?)"}`),this},orWhereNotILike(G,W){if(y.dialect==="postgres")K=Q`${I()} OR ${Q(String(G))} NOT ILIKE ${W}`,C("OR",`${String(G)} NOT ILIKE ?`);else{let S=Q`LOWER(${Q(String(G))}) NOT LIKE LOWER(${W})`;K=Q`${I()} OR ${S}`,C("OR",`LOWER(${String(G)}) NOT LIKE LOWER(?)`)}return this},whereAny(G,W,S){if(G.length===0)return this;let R=c.WHERE.test(O)?"AND":"WHERE",w=h.length+1,q=G.map((k,P)=>`${k} ${W} ${m(w+P)}`);O+=` ${R} (${q.join(" OR ")})`;for(let k=0;k<G.length;k++)h.push(S);return K=null,this},whereAll(G,W,S){if(G.length===0)return this;let R=c.WHERE.test(O)?"AND":"WHERE",w=h.length+1,q=G.map((k,P)=>`${k} ${W} ${m(w+P)}`);O+=` ${R} (${q.join(" AND ")})`;for(let k=0;k<G.length;k++)h.push(S);return K=null,this},whereNone(G,W,S){if(G.length===0)return this;let R=c.WHERE.test(O)?"AND":"WHERE",w=h.length+1,q=G.map((k,P)=>`${k} ${W} ${m(w+P)}`);O+=` ${R} NOT (${q.join(" OR ")})`;for(let k=0;k<G.length;k++)h.push(S);return K=null,this},whereNotBetween(G,W,S){let R=c.WHERE.test(O)?"AND":"WHERE";return O+=` ${R} ${G} NOT BETWEEN ? AND ?`,h.push(W,S),K=null,this},whereDate(G,W,S){let R=c.WHERE.test(O)?"AND":"WHERE",w=h.length+1;return O+=` ${R} ${G} ${W} ${m(w)}`,h.push(String(S)),K=null,this},whereRaw(G){let W=c.WHERE.test(O)?"AND":"WHERE";return O+=` ${W} ${String(G)}`,K=null,this},whereColumn(G,W,S){let R=c.WHERE.test(O)?"AND":"WHERE";return O+=` ${R} ${G} ${W} ${S}`,K=null,this},orWhereColumn(G,W,S){return O+=` OR ${G} ${W} ${S}`,K=null,this},whereIn(G,W){let S=c.WHERE.test(O)?"AND":"WHERE";if(Array.isArray(W)){let R=f0(W.length,h.length+1);O+=` ${S} ${G} IN (${R})`,h.push(...W)}else O+=` ${S} ${G} IN (${String(W.toSQL())})`;return K=null,this},orWhereIn(G,W){if(Array.isArray(W)){let S=f0(W.length,h.length+1);O+=` OR ${G} IN (${S})`,h.push(...W)}else O+=` OR ${G} IN (${String(W.toSQL())})`;return K=null,this},whereNotIn(G,W){let S=c.WHERE.test(O)?"AND":"WHERE";if(Array.isArray(W)){let R=f0(W.length,h.length+1);O+=` ${S} ${G} NOT IN (${R})`,h.push(...W)}else O+=` ${S} ${G} NOT IN (${String(W.toSQL())})`;return K=null,this},orWhereNotIn(G,W){if(Array.isArray(W)){let S=f0(W.length,h.length+1);O+=` OR ${G} NOT IN (${S})`,h.push(...W)}else O+=` OR ${G} NOT IN (${String(W.toSQL())})`;return K=null,this},whereNested(G){let W=c.WHERE.test(O)?"AND":"WHERE",S=G.toSQL?String(G.toSQL()):String(G);return O+=` ${W} (${S})`,K=null,this},orWhereNested(G){let W=G.toSQL?String(G.toSQL()):String(G);return O+=` OR (${W})`,K=null,this},andWhere(G,W,S){if(typeof G==="string"&&W!==void 0){let R=h.length+1;return G0.push(`${String(G)} ${String(W)} ${m(R)}`),h.push(S),O=`${O} AND ${String(G)} ${String(W)} ${m(R)}`,K=null,this}if(Array.isArray(G)){let[R,w,q]=G,k=String(R),P=String(w);if(P==="in"||P==="not in"){let A=Array.isArray(q)?q:[q],H=f0(A.length,h.length+1);G0.push(`${k} ${P.toUpperCase()} (${H})`),h.push(...A),O=`${O} AND ${k} ${P.toUpperCase()} (${H})`,K=null}else{let A=h.length+1;G0.push(`${k} ${P} ${m(A)}`),h.push(q),O=`${O} AND ${k} ${P} ${m(A)}`,K=null}return this}if(G&&typeof G==="object"&&!("raw"in G)){let R=Object.keys(G),w=[];for(let q of R){let k=G[q];if(Array.isArray(k)){let P=f0(k.length,h.length+1);w.push(`${q} IN (${P})`),G0.push(`${q} IN (${P})`),h.push(...k)}else{let P=h.length+1;w.push(`${q} = ${m(P)}`),G0.push(`${q} = ${m(P)}`),h.push(k)}}if(w.length>0)O=`${O} AND ${w.join(" AND ")}`,K=null;return this}if(G&&typeof G.raw<"u")return G0.push(G.raw),O=`${O} AND ${G.raw}`,K=null,this;return this},orWhere(G,W,S){if(typeof G==="string"&&W!==void 0){let R=h.length+1;return G0.push(`OR ${String(G)} ${String(W)} ${m(R)}`),h.push(S),O=`${O} OR ${String(G)} ${String(W)} ${m(R)}`,K=null,this}if(Array.isArray(G)){let[R,w,q]=G,k=String(R),P=String(w);if(P==="in"||P==="not in"){let A=Array.isArray(q)?q:[q],H=f0(A.length,h.length+1);G0.push(`OR ${k} ${P.toUpperCase()} (${H})`),h.push(...A),O=`${O} OR ${k} ${P.toUpperCase()} (${H})`,K=null}else{let A=h.length+1;G0.push(`OR ${k} ${P} ${m(A)}`),h.push(q),O=`${O} OR ${k} ${P} ${m(A)}`,K=null}return this}if(G&&typeof G==="object"&&!("raw"in G)){let R=Object.keys(G),w=[];for(let q of R){let k=G[q];if(Array.isArray(k)){let P=f0(k.length,h.length+1);w.push(`${q} IN (${P})`),G0.push(`OR ${q} IN (${P})`),h.push(...k)}else{let P=h.length+1;w.push(`${q} = ${m(P)}`),G0.push(`OR ${q} = ${m(P)}`),h.push(k)}}if(w.length>0)O=`${O} OR ${w.join(" AND ")}`,K=null;return this}if(G&&typeof G.raw<"u")return G0.push(`OR ${G.raw}`),O=`${O} OR ${G.raw}`,K=null,this;return this},orderBy(G,W="asc"){let S=W==="asc"?"ASC":"DESC";return O=c.ORDER_BY.test(O)?`${O}, ${G} ${S}`:`${O} ORDER BY ${G} ${S}`,K=null,this},orderByDesc(G){return O=c.ORDER_BY.test(O)?`${O}, ${G} DESC`:`${O} ORDER BY ${G} DESC`,K=null,this},inRandomOrder(){let G=y.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return O=c.ORDER_BY.test(O)?`${O}, ${G}`:`${O} ORDER BY ${G}`,K=null,this},reorder(G,W="asc"){return O=O.replace(/ORDER BY[\s\S]*$/i,""),O+=` ORDER BY ${G} ${W==="asc"?"ASC":"DESC"}`,K=null,this},latest(G){let W=G??y.timestamps.defaultOrderColumn;return O=c.ORDER_BY.test(O)?`${O}, ${W} DESC`:`${O} ORDER BY ${W} DESC`,K=null,this},oldest(G){let W=G??y.timestamps.defaultOrderColumn;return O=c.ORDER_BY.test(O)?`${O}, ${W} ASC`:`${O} ORDER BY ${W} ASC`,K=null,this},limit(G){return O=c.LIMIT.test(O)?O.replace(c.LIMIT,` LIMIT ${G}`):`${O} LIMIT ${G}`,K=null,this},offset(G){return O=c.OFFSET.test(O)?O.replace(c.OFFSET,` OFFSET ${G}`):`${O} OFFSET ${G}`,K=null,this},join(G,W,S,R){return O=`${O} JOIN ${G} ON ${W} ${S} ${R}`,D.add(G),this},joinSub(G,W,S,R,w){return O+=` JOIN (${String(G.toSQL())}) AS ${W} ON ${S} ${R} ${w}`,K=null,D.add(W),this},innerJoin(G,W,S,R){return O=`${O} INNER JOIN ${G} ON ${W} ${S} ${R}`,K=null,D.add(G),this},leftJoin(G,W,S,R){return O=`${O} LEFT JOIN ${G} ON ${W} ${S} ${R}`,K=null,D.add(G),this},leftJoinSub(G,W,S,R,w){return O+=` LEFT JOIN (${String(G.toSQL())}) AS ${W} ON ${S} ${R} ${w}`,K=null,D.add(W),this},rightJoin(G,W,S,R){return O=`${O} RIGHT JOIN ${G} ON ${W} ${S} ${R}`,K=null,D.add(G),this},crossJoin(G){return O=`${O} CROSS JOIN ${G}`,K=null,D.add(G),this},crossJoinSub(G,W){return O+=` CROSS JOIN (${String(G.toSQL())}) AS ${W}`,K=null,D.add(W),this},selectAllRelations(){if(!_)return this;let G=String(U),W=Object.keys(_[G]?.columns??{}),S=[];if(W.length>0)S.push(Q`${Q(G)}.*`);for(let R of D){let w=Object.keys(_[R]?.columns??{});for(let q of w){let k=y.aliasing.relationColumnAliasFormat==="camelCase"?`${R}_${q}`.replace(/_([a-z])/g,(P,A)=>A.toUpperCase()):y.aliasing.relationColumnAliasFormat==="table.dot.column"?`${R}.${q}`:`${R}_${q}`;S.push(Q`${Q(`${R}.${q}`)} AS ${Q(k)}`)}}if(S.length>0){let R=W.length>0?`${G}.*`:"",w=[];for(let P of D){let A=Object.keys(_[P]?.columns??{});for(let H of A){let B=y.aliasing.relationColumnAliasFormat==="camelCase"?`${P}_${H}`.replace(/_([a-z])/g,(d,l)=>l.toUpperCase()):y.aliasing.relationColumnAliasFormat==="table.dot.column"?`${P}.${H}`:`${P}_${H}`;w.push(`${P}.${H} AS ${B}`)}}let q=[R,...w].filter(Boolean).join(", "),k=O.indexOf(" FROM ");if(k!==-1)O=`SELECT ${q}${O.substring(k)}`;else O=`SELECT ${q} FROM ${G}`;K=null}return this},groupBy(...G){if(G.length)O=c.GROUP_BY.test(O)?`${O}, ${G.join(", ")}`:`${O} GROUP BY ${G.join(", ")}`,K=null;return this},groupByRaw(G){return O=c.GROUP_BY.test(O)?`${O}, ${String(G)}`:`${O} GROUP BY ${String(G)}`,K=null,this},having(G){if(Array.isArray(G)){let W=h.length+1;O=`${O} HAVING ${G[0]} ${G[1]} ${m(W)}`,h.push(G[2]),K=null}else if(G&&typeof G==="object"&&!("raw"in G)){let W=Object.keys(G),S=W.length;if(S){let R=h.length,w=Array.from({length:S});for(let q=0;q<S;q++){let k=W[q];w[q]=`${k} = ${m(R+q+1)}`,h.push(G[k])}O=`${O} HAVING ${w.join(" AND ")}`,K=null}}else if(G&&typeof G.raw<"u")O+=` HAVING ${G.raw}`,K=null;return this},havingRaw(G){return O+=` HAVING ${String(G)}`,K=null,this},orderByRaw(G){return O=c.ORDER_BY.test(O)?`${O}, ${String(G)}`:`${O} ORDER BY ${String(G)}`,K=null,this},union(G){return O+=` UNION ${String(G.toSQL())}`,K=null,this},unionAll(G){return O+=` UNION ALL ${String(G.toSQL())}`,K=null,this},forPage(G,W){let S=Math.max(1,Math.floor(G)),R=Math.max(1,Math.floor(W));return O+=` LIMIT ${R} OFFSET ${(S-1)*R}`,K=null,this},toSQL(){return F(I(),O)},async value(G){let W=Q`${I()} LIMIT 1`,S=await z(W,"select",{signal:J,timeoutMs:M}),[R]=S;return R?.[G]},async pluck(G,W){let S=await z(I(),"select",{signal:J,timeoutMs:M});if(W){let R={};for(let w of S)R[String(w?.[W])]=w?.[G];return R}return S.map((R)=>R?.[G])},async exists(){let G=Q`SELECT EXISTS (${I()}) as e`,W=await z(G,"select",{signal:J,timeoutMs:M}),[S]=W;return Boolean(S?.e)},async doesntExist(){return!await this.exists()},async paginate(G,W=1){let S=Q`SELECT COUNT(*) as c FROM (${I()}) as sub`,R=await z(S,"select",{signal:J,timeoutMs:M}),[w]=R,q=Number(w?.c??0),k=Math.max(1,Math.ceil(q/G)),P=Math.max(1,Math.min(W,k)),A=(P-1)*G;return{data:await z(Q`${I()} LIMIT ${G} OFFSET ${A}`,"select",{signal:J,timeoutMs:M}),meta:{perPage:G,page:P,total:q,lastPage:k}}},async simplePaginate(G,W=1){let S=Math.max(1,W),R=(S-1)*G,w=await z(Q`${I()} LIMIT ${G+1} OFFSET ${R}`,"select",{signal:J,timeoutMs:M}),q=w.length>G;return{data:q?w.slice(0,G):w,meta:{perPage:G,page:S,hasMore:q}}},async cursorPaginate(G,W,S="id",R="asc"){let w=I();if(W!==void 0&&W!==null)if(Array.isArray(S)){let H=S.map((D0)=>Q(String(D0))),B=R==="asc"?Q`>`:Q`<`,d=Q`(${Q(H)})`,l=Q`(${Q(W)})`;w=Q`${w} WHERE ${d} ${B} ${l}`}else w=R==="asc"?Q`${w} WHERE ${Q(String(S))} > ${W}`:Q`${w} WHERE ${Q(String(S))} < ${W}`;if(Array.isArray(S)){let B=S.map((d)=>Q`${Q(String(d))} ${R==="asc"?Q`ASC`:Q`DESC`}`).reduce((d,l,D0)=>D0===0?l:Q`${d}, ${l}`);w=Q`${w} ORDER BY ${B} LIMIT ${G+1}`}else w=Q`${w} ORDER BY ${Q(String(S))} ${R==="asc"?Q`ASC`:Q`DESC`} LIMIT ${G+1}`;let q=await z(w,"select",{signal:J,timeoutMs:M}),k=q.length>G?Array.isArray(S)?S.map((H)=>q[G]?.[H]):q[G]?.[S]:null,P=q.slice(0,G),A=P.length?Array.isArray(S)?S.map((H)=>P[0]?.[H]):P[0]?.[S]:null;return{data:P,meta:{perPage:G,nextCursor:k??null,prevCursor:A}}},async chunk(G,W){let S=1;while(!0){let{data:R}=await this.paginate(G,S);if(R.length===0)break;if(await W(R),R.length<G)break;S+=1}},async chunkById(G,W="id",S){let R;while(!0){let{data:w,meta:q}=await this.cursorPaginate(G,R,W,"asc");if(w.length===0)break;if(S)await S(w);if(R=q.nextCursor,!R)break}},async eachById(G,W="id",S){await this.chunkById(G,W,async(R)=>{for(let w of R)await S?.(w)})},withTimeout(G){return M=Math.max(1,Math.floor(G)),this},abort(G){return J=G,this},withTrashed(){return N=!0,T=!1,this},onlyTrashed(){N=!0,T=!0;let G=y.softDeletes?.column||"deleted_at";if(O.includes("WHERE"))O=O.replace(/WHERE/,`WHERE ${U}.${G} IS NOT NULL AND`);else O=`${O} WHERE ${U}.${G} IS NOT NULL`;let W=String(I());if(W.includes("WHERE")){let S=W.replace(/WHERE/,`WHERE ${U}.${G} IS NOT NULL AND`);K=Q([S])}else{let S=`${W} WHERE ${U}.${G} IS NOT NULL`;K=Q([S])}return this},scope(G,W){let S=String(U),w=X?.scopes?.[S]?.[G];if(w)return w(this,W);return this},when(G,W,S){if(G)return W(this);if(S)return S(this);return this},tap(G){return G(this),this},dump(){return console.log(String(I())),this},dd(){throw console.log(String(I())),Error("Dump and Die")},cache(G=60000){return p=G,v=!0,this},async explain(){let G=Q`EXPLAIN ${I()}`;return await z(G,"select",{signal:J,timeoutMs:M})},simple(){return I().simple()},toText(){return O},async get(){let G=y.hooks,W=G&&(G.onQueryStart||G.onQueryEnd||G.onQueryError||G.startSpan);if(!y.softDeletes?.enabled&&!v&&!M&&!J&&!W){let w=Z._prepareStatement;if(w){let q=w(O);return z9(h.length>0?q.all(...h):q.all())}}if(K=h.length>0?Z.unsafe(O,h):Z.unsafe(O),!y.softDeletes?.enabled&&!v&&!M&&!J&&!W){let w=I()._stmt,q=I()._params;if(w)return z9(q&&q.length>0?w.all(...q):w.all());return z9(await I().execute())}if(!y.softDeletes?.enabled&&!v&&!M&&!J)return z9(await z(I(),"select"));let S=I();if(y.softDeletes?.enabled&&y.softDeletes.defaultFilter&&!N){let w=y.softDeletes.column,q=String(U);if((_?Boolean(_[q]?.columns?.[w]):!0)&&!c.DELETED_AT.test(O))S=Q`${I()} WHERE ${Q(String(w))} IS ${T?Q`NOT NULL`:Q`NULL`}`,C("WHERE",`${String(w)} IS ${T?"NOT ":""}NULL`)}if(v){let w=String(S),q=X1.get(w);if(q)return q}let R=await z(S,"select",{signal:J,timeoutMs:M});if(v){let w=String(S);X1.set(w,R,p)}return z9(R)},async executeTakeFirst(){let G=await z(I(),"select",{signal:J,timeoutMs:M});return c0(Array.isArray(G)?G[0]:G)},async executeTakeFirstOrThrow(){let G=await this.executeTakeFirst();if(!G)throw Error("Record not found");return G},async first(){let G=y.hooks,W=G&&(G.onQueryStart||G.onQueryEnd||G.onQueryError||G.startSpan);if(!y.softDeletes?.enabled&&!v&&!M&&!J&&!W){let w=Z._prepareStatement;if(w){let q=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,k=w(q),P=h.length>0?k.all(...h):k.all();return c0(P[0])}}let S=await z(Q`${I()} LIMIT 1`,"select",{signal:J,timeoutMs:M}),[R]=S;return c0(R)},async firstOrFail(){let G=await this.first();if(!G)throw Error("Record not found");return G},async find(G){let W=X?.primaryKeys[String(U)]??"id",S=await z(Q`${I()} WHERE ${Q(W)} = ${G} LIMIT 1`,"select",{signal:J,timeoutMs:M}),[R]=S;return R},async findOrFail(G){let W=await this.find(G);if(!W)throw Error("Record not found");return W},async findMany(G){let W=X?.primaryKeys[String(U)]??"id";return await z(Q`${I()} WHERE ${Q(String(W))} IN ${Q(G)}`,"select",{signal:J,timeoutMs:M})},async*lazy(){let G,W=X?.primaryKeys[String(U)]??"id";while(!0){let R=await(G==null?Q`${I()} ORDER BY ${Q(String(W))} ASC LIMIT 100`:Q`${I()} WHERE ${Q(String(W))} > ${G} ORDER BY ${Q(String(W))} ASC LIMIT 100`).execute();if(R.length===0)break;for(let w of R)yield w;if(G=R[R.length-1]?.[W],G==null)break}},async*lazyById(){let G=X?.primaryKeys[String(U)]??"id",W;while(!0){let R=await(W==null?Q`${I()} ORDER BY ${Q(String(G))} ASC LIMIT 100`:Q`${I()} WHERE ${Q(String(G))} > ${W} ORDER BY ${Q(String(G))} ASC LIMIT 100`).execute();if(R.length===0)break;for(let w of R)yield w;if(W=R[R.length-1]?.[G],W==null)break}},pipe(G){return G(this)},async count(){let G=O.indexOf(" FROM "),W=G!==-1?`SELECT COUNT(*) as c${O.substring(G)}`:`SELECT COUNT(*) as c FROM ${U}`,S=y.hooks,R=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan);if(!y.softDeletes?.enabled&&!v&&!M&&!J&&!R){let P=Z._prepareStatement;if(P){let A=P(W),H=h.length>0?A.all(...h):A.all();return Number(H[0]?.c??0)}}let w=h.length>0?Z.unsafe(W,h):Z.unsafe(W),q=await z(w,"select",{signal:J,timeoutMs:M}),[k]=q;return Number(k?.c??0)},async avg(G){let W=O.indexOf(" FROM "),S=W!==-1?`SELECT AVG(${G}) as a${O.substring(W)}`:`SELECT AVG(${G}) as a FROM ${U}`,R=y.hooks,w=R&&(R.onQueryStart||R.onQueryEnd||R.onQueryError||R.startSpan);if(!y.softDeletes?.enabled&&!v&&!M&&!J&&!w){let A=Z._prepareStatement;if(A){let H=A(S),B=h.length>0?H.all(...h):H.all();return Number(B[0]?.a??0)}}let q=h.length>0?Z.unsafe(S,h):Z.unsafe(S),k=await z(q,"select",{signal:J,timeoutMs:M}),[P]=k;return Number(P?.a??0)},async sum(G){let W=O.indexOf(" FROM "),S=W!==-1?`SELECT SUM(${G}) as s${O.substring(W)}`:`SELECT SUM(${G}) as s FROM ${U}`,R=h.length>0?Z.unsafe(S,h):Z.unsafe(S),w=await z(R,"select",{signal:J,timeoutMs:M}),[q]=w;return Number(q?.s??0)},async max(G){let W=O.indexOf(" FROM "),S=W!==-1?`SELECT MAX(${G}) as m${O.substring(W)}`:`SELECT MAX(${G}) as m FROM ${U}`,R=h.length>0?Z.unsafe(S,h):Z.unsafe(S),w=await z(R,"select",{signal:J,timeoutMs:M}),[q]=w;return q?.m},async min(G){let W=O.indexOf(" FROM "),S=W!==-1?`SELECT MIN(${G}) as m${O.substring(W)}`:`SELECT MIN(${G}) as m FROM ${U}`,R=h.length>0?Z.unsafe(S,h):Z.unsafe(S),w=await z(R,"select",{signal:J,timeoutMs:M}),[q]=w;return q?.m},lockForUpdate(){return O+=" FOR UPDATE",K=null,this},sharedLock(){let G=y.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return O+=` ${G}`,K=null,this},withCTE(G,W){return O=`WITH ${G} AS (${String(W.toSQL())}) ${O}`,K=null,this},withRecursive(G,W){return O=`WITH RECURSIVE ${G} AS (${String(W.toSQL())}) ${O}`,K=null,this},execute(){return z(I(),"select",{signal:J,timeoutMs:M})},values(){return I().values()},toParams(){return I().values?.()??[]},raw(){return I().raw()},get rows(){return},get row(){return},cancel(){try{I().cancel()}catch{}}},{get(G,W,S){let R=Reflect.get(G,W,S);if(R!==void 0)return R;if(typeof W==="string"&&(W.startsWith("where")||W.startsWith("orWhere")||W.startsWith("andWhere"))){let w=W.startsWith("orWhere"),q=W.startsWith("andWhere"),k=W.replace(/^or?where/i,"").replace(/^andwhere/i,"");if(!k)return()=>S;let P=k.charAt(0).toLowerCase()+k.slice(1),H=((D0)=>D0.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))(k),B=String(U),d=_?Object.keys(_[B]?.columns??{}):[],l=[H,P,P.toLowerCase()].find((D0)=>d.includes(D0))??H;return(D0)=>{let s=Array.isArray(D0)?Q`${Q(String(l))} IN ${Q(D0)}`:Q`${Q(String(l))} = ${D0}`;K=w?Q`${I()} OR ${s}`:q?Q`${I()} AND ${s}`:Q`${I()} WHERE ${s}`;let q9=Array.isArray(D0)?`${String(l)} IN (?)`:`${String(l)} = ?`;return C(w?"OR":q?"AND":"WHERE",q9),S}}return Reflect.get(G,W,S)}})}return{configure(U){return Object.assign(y,U),this},id(U){if(!c.IDENTIFIER.test(U))throw Error(`[query-builder] Invalid identifier: '${U}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return Z(String(U))},ids(...U){for(let V of U)if(!c.IDENTIFIER.test(V))throw Error(`[query-builder] Invalid identifier: '${V}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return Z(U)},select(U,...V){return E(U,V)},selectFrom(U){return E(U)},selectFromSub(U,V){let Q=Z,O=Z`SELECT * FROM (${U.toSQL()}) AS ${Z(V)}`,K={distinct(){let D=String(O).replace(/^SELECT\s+/i,""),M=Q`SELECT DISTINCT ${Q``}${Q(D)}`;return I(M)},distinctOn(...D){let M=/^SELECT\s+(\S+)\s+FROM/i.exec(String(O)),J=M?`${M[1]} FROM`:String(O),N=Q`SELECT DISTINCT ON (${Q(D)}) ${Q``}${Q(J)}`;return I(N)},selectRaw(D){let M=Q`${O} , ${D}`;return I(M)},where(D,M,J){let N=C(O,D,M,J,"WHERE");return I(N)},andWhere(D,M,J){let N=C(O,D,M,J,"AND");return I(N)},orWhere(D,M,J){let N=C(O,D,M,J,"OR");return I(N)},orderBy(D,M="asc"){let J=M==="asc"?"ASC":"DESC",N=String(O),T=c.ORDER_BY.test(N)?Q.unsafe(`${N}, ${D} ${J}`):Q`${O} ORDER BY ${Q(D)} ${M==="asc"?Q`ASC`:Q`DESC`}`;return I(T)},limit(D){let M=String(O),J=c.LIMIT.test(M)?Q.unsafe(M.replace(c.LIMIT,` LIMIT ${D}`)):Q`${O} LIMIT ${D}`;return I(J)},offset(D){let M=String(O),J=c.OFFSET.test(M)?Q.unsafe(M.replace(c.OFFSET,` OFFSET ${D}`)):Q`${O} OFFSET ${D}`;return I(J)},toSQL(){return F(O)},async execute(){return z(O,"select")},async executeTakeFirst(){let D=await z(O,"select");return Array.isArray(D)?D[0]:D},async executeTakeFirstOrThrow(){let D=await z(O,"select"),M=Array.isArray(D)?D[0]:D;if(!M)throw Error("Record not found");return M},async get(){return z(O,"select")},async first(){let D=await z(O,"select");return Array.isArray(D)?D[0]:D},async firstOrFail(){let D=await z(O,"select"),M=Array.isArray(D)?D[0]:D;if(!M)throw Error("No rows found");return M},async exists(){let D=Q`SELECT EXISTS(${O}) as exists`;return(await z(D,"select"))?.[0]?.exists===!0},async doesntExist(){return!await this.exists()},values(){return O.values()},raw(){return O.raw()},cancel(){try{O.cancel()}catch{}},whereRaw:()=>this,whereColumn:()=>this,orWhereColumn:()=>this,whereIn:()=>this,orWhereIn:()=>this,whereNotIn:()=>this,orWhereNotIn:()=>this,whereLike:()=>this,whereILike:()=>this,orWhereLike:()=>this,orWhereILike:()=>this,whereNotLike:()=>this,whereNotILike:()=>this,orWhereNotLike:()=>this,orWhereNotILike:()=>this,whereAny:()=>this,whereAll:()=>this,whereNone:()=>this,whereNested:()=>this,orWhereNested:()=>this,whereDate:()=>this,whereBetween:()=>this,whereNotBetween:()=>this,whereJsonContains:()=>this,whereJsonPath:()=>this,whereNull:()=>this,whereNotNull:()=>this,whereExists:()=>this,whereJsonDoesntContain:()=>this,whereJsonContainsKey:()=>this,whereJsonDoesntContainKey:()=>this,whereJsonLength:()=>this,join:()=>this,joinSub:()=>this,innerJoin:()=>this,leftJoin:()=>this,leftJoinSub:()=>this,rightJoin:()=>this,crossJoin:()=>this,crossJoinSub:()=>this,groupBy:()=>this,groupByRaw:()=>this,having:()=>this,havingRaw:()=>this,addSelect:()=>this,select:()=>this,selectAll:()=>this,orderByDesc:()=>this,inRandomOrder:()=>this,reorder:()=>this,orderByRaw:()=>this,union:()=>this,unionAll:()=>this,forPage:()=>this,selectAllRelations:()=>this,with:()=>this,value:()=>Promise.resolve(void 0),pluck:()=>Promise.resolve([]),cursorPaginate:()=>Promise.resolve({data:[],meta:{perPage:0,nextCursor:null}}),paginate:()=>Promise.resolve({data:[],meta:{perPage:0,page:1,total:0,lastPage:1}}),simplePaginate:()=>Promise.resolve({data:[],meta:{perPage:0,page:1,hasMore:!1}}),chunk:()=>Promise.resolve(),chunkById:()=>Promise.resolve(),eachById:()=>Promise.resolve(),count:()=>Promise.resolve(0),avg:()=>Promise.resolve(0),sum:()=>Promise.resolve(0),max:()=>Promise.resolve(null),min:()=>Promise.resolve(null),find:()=>Promise.resolve(void 0),findOrFail:()=>Promise.reject(Error("Not found")),findMany:()=>Promise.resolve([]),latest:()=>this,oldest:()=>this,lazy:()=>async function*(){}(),lazyById:()=>async function*(){}(),pipe:(D)=>D(this),when:()=>this,tap:()=>this,dump:()=>this,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>O.simple(),toText:()=>String(O),toParams:()=>O.values?.()??[],withTimeout:()=>this,abort:()=>this,lockForUpdate:()=>this,sharedLock:()=>this,withCTE:()=>this,withRecursive:()=>this,cache:()=>this,clone:()=>this,withTrashed:()=>this,onlyTrashed:()=>this,scope:()=>this,get rows(){return[]},get row(){return}};function I(D){return{...K,toSQL:()=>F(D),execute:()=>z(D,"select"),get:()=>z(D,"select"),first:async()=>{let M=await z(D,"select");return Array.isArray(M)?M[0]:M},firstOrFail:async()=>{let M=await z(D,"select"),J=Array.isArray(M)?M[0]:M;if(!J)throw Error("No rows found");return J},exists:async()=>{let M=Q`SELECT EXISTS(${D}) as exists`;return(await z(M,"select"))?.[0]?.exists===!0},doesntExist:async()=>{return!await K.exists()},values:()=>D.values(),raw:()=>D.raw(),cancel:()=>{try{D.cancel()}catch{}},simple:()=>D.simple(),toText:()=>String(D),toParams:()=>D.values?.()??[]}}function C(D,M,J,N,T="WHERE"){if(typeof M==="string"&&J!==void 0){let v=Array.isArray(N)?`${M} IN (?)`:`${M} ${J} ?`;return Q`${D} ${Q(T)} ${Q(v)}`}else if(Array.isArray(M)&&M.length===3){let[v,b,f]=M,p=Array.isArray(f)?`${v} IN (?)`:`${v} ${b} ?`;return Q`${D} ${Q(T)} ${Q(p)}`}else if(typeof M==="object"&&M!==null){let b=Object.entries(M).map(([f,p])=>{let g=Array.isArray(p)?`${f} IN (?)`:`${f} = ?`;return Q`${Q(g)}`}).reduce((f,p,g)=>g===0?p:Q`${f} AND ${p}`);return Q`${D} ${Q(T)} ${b}`}return D}return K},insertInto(U){let V,Q="",O=[],K=y.dialect==="postgres",I=K?(D)=>`"${D}"`:y.dialect==="mysql"?(D)=>`\`${D}\``:(D)=>D,C=K?(D)=>`$${D+1}`:(D)=>"?";return{values(D){let M=Array.isArray(D)?D:[D],J=M.length;if(J===0)return V=Z.unsafe("SELECT 1"),this;let N=M[0],T=Object.keys(N),v=T.length,b=J*v;if(O.length=b,J===1)if(!K){let f=T[0],p="?";O[0]=N[T[0]];for(let g=1;g<v;g++)f+=`,${T[g]}`,p+=",?",O[g]=N[T[g]];Q=`INSERT INTO ${U}(${f})VALUES(${p})`}else{let f=T.map((p)=>I(p)).join(",");Q=`INSERT INTO ${I(U)}(${f})VALUES(`;for(let p=0;p<v;p++){if(p>0)Q+=",";Q+=C(p),O[p]=N[T[p]]}Q+=")"}else{let f=T.map((g)=>I(g)).join(",");Q=`INSERT INTO ${I(U)}(${f})VALUES`;let p=0;for(let g=0;g<J;g++){let t=M[g];if(g===0)Q+="(";else Q+="),(";for(let c0=0;c0<v;c0++){if(c0>0)Q+=",";Q+=C(p),O[p++]=t[T[c0]]}}Q+=")"}if(!Z._prepareStatement)V=Z.unsafe(Q,O);return this},returning(...D){let M=`${Q} RETURNING ${D.join(", ")}`,J=Z.unsafe(M,O);return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>F(J,M),execute:()=>z(J,"insert")}},toSQL(){if(!V)V=Z.unsafe(Q,O);return F(V,Q)},execute(){let D=y.hooks;if(!(D&&(D.onQueryStart||D.onQueryEnd||D.onQueryError||D.startSpan||D.beforeCreate||D.afterCreate))){let J=Z._prepareStatement;if(J){let N=J(Q);return O.length>0?N.run(...O):N.run()}}if(!V)V=Z.unsafe(Q,O);return z(V,"insert")},async executeTakeFirst(){if(!V)V=Z.unsafe(Q,O);return await z(V,"insert")},async executeTakeFirstOrThrow(){if(!V)V=Z.unsafe(Q,O);let D=await z(V,"insert");if(!D)throw Error("Insert failed");return D},returningAll(){let D=`${Q} RETURNING *`,M=Z.unsafe(D,O);return{toSQL:()=>F(M,D),execute:()=>z(M,"insert"),async executeTakeFirst(){let J=await z(M,"insert");return Array.isArray(J)?J[0]:J},async executeTakeFirstOrThrow(){let J=await z(M,"insert"),N=Array.isArray(J)?J[0]:J;if(!N)throw Error("Insert with RETURNING failed");return N}}}}},updateTable(U){let V,Q=[],O=(I)=>{if(y.dialect==="mysql")return`\`${I}\``;return`"${I}"`},K=`UPDATE ${O(String(U))}`;return{set(I){let C=Object.keys(I),D=C.length,M=Array.from({length:D});for(let J=0;J<D;J++){let N=C[J];M[J]=`${O(N)} = ${m(J+1)}`,Q.push(I[N])}return K=`${K} SET ${M.join(", ")}`,V=Z.unsafe(K,Q),this},where(I,C,D){let M=()=>K.toUpperCase().includes(" WHERE ")?"AND":"WHERE";if(typeof I==="string"&&C!==void 0){let J=Q.length+1;return K=`${K} ${M()} ${O(I)} ${C} ${m(J)}`,Q.push(D),V=Z.unsafe(K,Q),this}if(Array.isArray(I)){let[J,N,T]=I,v=Q.length+1;return K=`${K} ${M()} ${O(String(J))} ${String(N)} ${m(v)}`,Q.push(T),V=Z.unsafe(K,Q),this}if(I&&typeof I==="object"&&!("raw"in I)){let J=Object.keys(I),N=J.length,T=Q.length,v=Array.from({length:N});for(let b=0;b<N;b++)v[b]=`${O(J[b])} = ${m(T+b+1)}`,Q.push(I[J[b]]);K=`${K} ${M()} ${v.join(" AND ")}`,V=Z.unsafe(K,Q)}return this},returning(...I){let C=`${K} RETURNING ${I.join(", ")}`,D=Q.length>0?Z.unsafe(C,Q):Z.unsafe(C),M={where:()=>M,andWhere:()=>M,orWhere:()=>M,orderBy:()=>M,limit:()=>M,offset:()=>M,toSQL:()=>F(D,C),execute:()=>z(D,"update")};return M},toSQL(){if(!V)V=Q.length>0?Z.unsafe(K,Q):Z.unsafe(K);return F(V,K)},execute(){return z(V,"update")},async executeTakeFirst(){return{numUpdatedRows:await z(V,"update")}},async executeTakeFirstOrThrow(){let I=await z(V,"update");if(I===0)throw Error("No rows updated");return{numUpdatedRows:I}},returningAll(){let I=`${K} RETURNING *`,C=Q.length>0?Z.unsafe(I,Q):Z.unsafe(I);return{toSQL:()=>F(C,I),execute:()=>z(C,"update"),async executeTakeFirst(){let D=await z(C,"update");return Array.isArray(D)?D[0]:D},async executeTakeFirstOrThrow(){let D=await z(C,"update"),M=Array.isArray(D)?D[0]:D;if(!M)throw Error("Update with RETURNING failed");return M}}}}},deleteFrom(U){let V=(M)=>{if(y.dialect==="mysql")return`\`${M}\``;return`"${M}"`},O=`DELETE FROM ${V(String(U))}`,K=null,I=[],C=null,D=()=>{if(K===null)K=I.length>0?Z.unsafe(O,I):Z.unsafe(O);return K};return{where(M,J,N){if(C=M,typeof M==="string"&&J!==void 0){let T=I.length+1;return O+=` WHERE ${V(M)} ${J} ${m(T)}`,I.push(N),K=null,this}if(Array.isArray(M)){let[T,v,b]=M,f=I.length+1;return O+=` WHERE ${V(String(T))} ${v} ${m(f)}`,I.push(b),K=null,this}if(M&&typeof M==="object"&&!("raw"in M)){let T=Object.keys(M),v=[];for(let b of T){let f=I.length+1;v.push(`${V(b)} = ${m(f)}`),I.push(M[b])}return O+=` WHERE ${v.join(" AND ")}`,K=null,this}return K=j({},D(),M),this},returning(...M){let J=`${O} RETURNING ${M.join(", ")}`,N=I.length>0?Z.unsafe(J,I):Z.unsafe(J),T={where:()=>T,andWhere:()=>T,orWhere:()=>T,orderBy:()=>T,limit:()=>T,offset:()=>T,toSQL:()=>F(N,J),execute:()=>z(N,"delete")};return T},toSQL(){return F(D(),O)},async execute(){try{await y.hooks?.beforeDelete?.({table:String(U),where:C})}catch(J){throw J}let M=await z(D(),"delete");try{await y.hooks?.afterDelete?.({table:String(U),where:C,result:M})}catch{}return M},async executeTakeFirst(){return{numDeletedRows:await z(D(),"delete")}},async executeTakeFirstOrThrow(){let M=await z(D(),"delete");if(M===0)throw Error("No rows deleted");return{numDeletedRows:M}},returningAll(){let M=`${O} RETURNING *`,J=I.length>0?Z.unsafe(M,I):Z.unsafe(M);return{toSQL:()=>F(J,M),execute:()=>z(J,"delete"),async executeTakeFirst(){let N=await z(J,"delete");return Array.isArray(N)?N[0]:N},async executeTakeFirstOrThrow(){let N=await z(J,"delete"),T=Array.isArray(N)?N[0]:N;if(!T)throw Error("Delete with RETURNING failed");return T}}}}},table(U){let V=this;return{insert(Q){return V.insertInto(U).values(Q)},update(Q){return V.updateTable(U).set(Q)},delete(){return V.deleteFrom(U)},select(...Q){if(Q.length===0)return V.selectFrom(U);return V.select(U,...Q)}}},sql:Z,raw(U,...V){return Z(U,...V)},simple(U,...V){return Z(U,...V).simple()},async advisoryLock(U){if(y.dialect!=="postgres")return;let V=String(U),Q=7;for(let I=0;I<V.length;I++)Q=Q*31+V.charCodeAt(I)|0;let O=typeof U==="number"?U:Math.abs(Q),K=x`SELECT pg_advisory_lock(${O})`;await z(K,"raw")},async tryAdvisoryLock(U){if(y.dialect!=="postgres")return!1;let V=String(U),Q=7;for(let C=0;C<V.length;C++)Q=Q*31+V.charCodeAt(C)|0;let O=typeof U==="number"?U:Math.abs(Q),K=x`SELECT pg_try_advisory_lock(${O}) as ok`,I=await z(K,"raw");return Boolean(I?.[0]?.ok)},unsafe(U,V){return x.unsafe(U,V)},file(U,V){return x.file(U,V)},async reserve(){let U=await x.reserve(),V=W0({sql:U,meta:X,schema:_});return V.release=()=>U.release(),V},async close(U){await x.close(U)},async listen(U,V){},async unlisten(U){},async notify(U,V){},async copyTo(U,V){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(U,V,Q){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let U=x`SELECT 1`;return await z(U,"select"),!0}catch{return!1}},async waitForReady(U){let V=Math.max(1,U?.attempts??10),Q=Math.max(10,U?.delayMs??100);for(let O=0;O<V;O++){if(await this.ping())return;await new Promise((K)=>setTimeout(K,Q))}throw Error("Database not ready after waiting")},async transaction(U,V){let O={...$?.txDefaults,...V},K=async(D)=>{O.logger?.({type:"start",attempt:D});let M=Date.now();return await x.begin(async(J)=>{let N=W0({sql:J,meta:X,schema:_});if(O?.isolation){let b=O.isolation,f=b==="read committed"?x`READ COMMITTED`:b==="repeatable read"?x`REPEATABLE READ`:x`SERIALIZABLE`;await J`${x`SET TRANSACTION ISOLATION LEVEL`} ${f}`.execute()}if(O?.readOnly)try{await J`${x`SET TRANSACTION READ ONLY`}`.execute()}catch{}let T=await U(N),v=Date.now()-M;return O.logger?.({type:"commit",attempt:D,durationMs:v}),T})},I=Math.max(0,O?.retries??0),C=0;for(;;)try{let D=await K(C+1);return O?.afterCommit?.(),D}catch(D){let M=vL(D)||bL(D,O.sqlStates);if(C<I&&M){C++,O?.onRetry?.(C,D);let J=gL(C,O.backoff);if(J>0)await fL(J);continue}try{O.onRollback?.(D)}catch{}try{O.afterRollback?.()}catch{}throw D}},async savepoint(U){let V=Z;if(!V||typeof V.savepoint!=="function")throw Error("savepoint() must be called inside a transaction");return await V.savepoint(async(Q)=>{let O=W0({sql:Q,meta:X,schema:_});return await U(O)})},async beginDistributed(U,V){return await x.beginDistributed(U,async(O)=>{let K=W0({sql:O,meta:X,schema:_});return await V(K)})},async commitDistributed(U){await x.commitDistributed(U)},async rollbackDistributed(U){await x.rollbackDistributed(U)},setTransactionDefaults(U){$={...$,txDefaults:{...$?.txDefaults,...U}}},transactional(U,V){return(...Q)=>{return this.transaction((O)=>U(O,...Q),V)}},async insertOrIgnore(U,V){return x`INSERT INTO ${x(String(U))} ${x(V)} ON CONFLICT DO NOTHING`.execute()},async insertGetId(U,V,Q="id"){if(y.dialect==="mysql"){let K=await x`INSERT INTO ${x(String(U))} ${x(V)}`.execute();if(K&&typeof K==="object"&&"insertId"in K)return K.insertId;let[I]=await x`SELECT LAST_INSERT_ID() as id`.execute();return I?.id}else{let O=x`INSERT INTO ${x(String(U))} ${x(V)} RETURNING ${x(String(Q))} as id`,[K]=await O.execute();return K?.id}},async updateOrInsert(U,V,Q){let O=Object.keys(V).map((C)=>x`${x(String(C))} = ${x(V[C])}`);if((await x`SELECT 1 FROM ${x(String(U))} WHERE ${x(O)} LIMIT 1`.execute()).length)return await x`UPDATE ${x(String(U))} SET ${x(Q)} WHERE ${x(O)}`.execute(),!0;else return await x`INSERT INTO ${x(String(U))} ${x({...V,...Q})}`.execute(),!0},async upsert(U,V,Q,O){let K=Q.map((D)=>String(D)),I=(O??[]).map((D)=>String(D));return x`INSERT INTO ${x(String(U))} ${x(V)} ON CONFLICT (${x(K)}) DO UPDATE SET ${x(I.reduce((D,M)=>({...D,[M]:x(`EXCLUDED.${M}`)}),{}))}`.execute()},async save(U,V){let Q=X?.primaryKeys[String(U)]??"id",O=V[Q];if(O!=null)if(await this.selectFrom(U).find(O)){await this.updateTable(U).set(V).where({[Q]:O}).execute();let I=await this.selectFrom(U).find(O);if(!I)throw Error("save() failed to retrieve updated row");return I}else return await this.create(U,V);return await this.create(U,V)},async remove(U,V){return await this.deleteFrom(U).where({id:V}).execute()},async find(U,V){return await this.selectFrom(U).find(V)},async findOrFail(U,V){return await this.selectFrom(U).findOrFail(V)},async findMany(U,V){return await this.selectFrom(U).findMany(V)},async latest(U,V){return await this.selectFrom(U).latest(V).first()},async oldest(U,V){return await this.selectFrom(U).oldest(V).first()},skip(U,V){return this.selectFrom(U).offset(V)},async rawQuery(U){let V=Date.now();try{y.hooks?.onQueryStart?.({sql:U,kind:"raw"});let Q=await x.unsafe(U);return y.hooks?.onQueryEnd?.({sql:U,durationMs:Date.now()-V,kind:"raw"}),Q}catch(Q){throw y.hooks?.onQueryError?.({sql:U,error:Q,durationMs:Date.now()-V,kind:"raw"}),Q}},async create(U,V){let Q=X?.primaryKeys[String(U)]??"id";try{await y.hooks?.beforeCreate?.({table:String(U),data:V})}catch(O){throw O}if(y.dialect==="postgres"){let O=x`INSERT INTO ${x(String(U))} ${x(V)} RETURNING ${x(String(Q))} as id`,[K]=await O.execute();if(console.log("resultId",K),!K?.id)throw console.error(`create() failed to get insert ID for table ${String(U)}`),console.error("Inserted values:",V),Error(`create() failed to get insert ID for table ${String(U)}`);let I=await this.selectFrom(U).find(K.id);if(!I)throw console.error(`create() failed to retrieve inserted row for table ${String(U)} with id ${K.id}`),console.error("Inserted values:",V),Error(`create() failed to retrieve inserted row for table ${String(U)} with id ${K.id}`);try{await y.hooks?.afterCreate?.({table:String(U),data:V,result:I})}catch{}return I}else{let O=await this.insertGetId(U,V,Q);if(O==null)throw Error(`create() failed to get insert ID for table ${String(U)}`);let K=await this.selectFrom(U).find(O);if(!K)throw console.error(`create() failed to retrieve inserted row for table ${String(U)} with id ${O}`),console.error("Inserted values:",V),Error(`create() failed to retrieve inserted row for table ${String(U)} with id ${O}`);try{await y.hooks?.afterCreate?.({table:String(U),data:V,result:K})}catch{}return K}},async createMany(U,V){if(!V?.length)return;let Q=V[0],O=Object.keys(Q),K=O.length,I=V.length,C=Array.from({length:I*K}),D=`INSERT INTO ${U}(${O.join(",")})VALUES`,M=0;for(let J=0;J<I;J++){if(J>0)D+=",";D+="(";let N=V[J];for(let T=0;T<K;T++){if(T>0)D+=",";D+=m(M+1),C[M++]=N[O[T]]}D+=")"}return Z.unsafe(D,C).execute()},async insertMany(U,V){if(!V?.length)return;let Q=V[0],O=Object.keys(Q),K=O.length,I=V.length,C=I*K,D=Array(C),M=y.dialect==="postgres",J;if(!M){let v=Array(K);for(let b=0;b<K;b++)v[b]="?";J=`(${v.join(",")})`}else J="";let N=Array(I+2);N[0]=`INSERT INTO ${U}(${O.join(",")})VALUES`;let T=0;if(!M){for(let v=0;v<I;v++){let b=V[v];N[v+1]=J;for(let f=0;f<K;f++)D[T++]=b[O[f]]}return Z.unsafe(N[0]+N.slice(1,I+1).join(","),D).execute()}for(let v=0;v<I;v++){let b=V[v],f=Array(K);for(let p=0;p<K;p++)f[p]=`$${T+1}`,D[T++]=b[O[p]];N[v+1]=`(${f.join(",")})`}return Z.unsafe(N[0]+N.slice(1,I+1).join(","),D).execute()},async updateMany(U,V,Q){let O=Object.keys(Q),K=O.length;if(K===0)return 0;let I=[],C=Array.from({length:K});for(let M=0;M<K;M++)C[M]=`${O[M]}=${m(M+1)}`,I.push(Q[O[M]]);let D=`UPDATE ${U} SET ${C.join(",")}`;if(Array.isArray(V))D+=` WHERE ${V[0]}${V[1]}${m(I.length+1)}`,I.push(V[2]);else if(V&&typeof V==="object"&&!("raw"in V)){let M=Object.keys(V),J=M.length;if(J>0){let N=I.length,T=Array.from({length:J});for(let v=0;v<J;v++)T[v]=`${M[v]}=${m(N+v+1)}`,I.push(V[M[v]]);D+=` WHERE ${T.join(" AND ")}`}}return Z.unsafe(D,I).execute()},async deleteMany(U,V){if(!Array.isArray(V)||V.length===0)return 0;let Q=X?.primaryKeys[String(U)]??"id",O=V.length;if(y.dialect==="postgres"){let I=Array(O);for(let C=0;C<O;C++)I[C]=`$${C+1}`;return Z.unsafe(`DELETE FROM ${U} WHERE ${Q} IN (${I.join(",")})`,V).execute()}let K=Array(O);for(let I=0;I<O;I++)K[I]="?";return Z.unsafe(`DELETE FROM ${U} WHERE ${Q} IN (${K.join(",")})`,V).execute()},async firstOrCreate(U,V,Q){let O=await this.selectFrom(U).where(V).first();if(O)return O;return await this.create(U,{...V,...Q})},async updateOrCreate(U,V,Q){let O=await this.selectFrom(U).where(V).first();if(O){await this.updateTable(U).set(Q).where(V).execute();let K=X?.primaryKeys[String(U)]??"id",I=O[K],C=I!=null?await this.selectFrom(U).find(I):await this.selectFrom(U).where(V).first();if(!C)throw Error("updateOrCreate() failed to retrieve updated row");return C}return await this.create(U,{...V,...Q})},async count(U,V){let Q=V?x(String(V)):x`*`,O=x`SELECT COUNT(${Q}) as c FROM ${x(String(U))}`,[K]=await O.execute();return Number(K?.c??0)},async sum(U,V){let Q=x`SELECT SUM(${x(String(V))}) as s FROM ${x(String(U))}`,[O]=await Q.execute();return Number(O?.s??0)},async avg(U,V){let Q=x`SELECT AVG(${x(String(V))}) as a FROM ${x(String(U))}`,[O]=await Q.execute();return Number(O?.a??0)},async min(U,V){let Q=x`SELECT MIN(${x(String(V))}) as m FROM ${x(String(U))}`,[O]=await Q.execute();return O?.m},async max(U,V){let Q=x`SELECT MAX(${x(String(V))}) as m FROM ${x(String(U))}`,[O]=await Q.execute();return O?.m},getRelationships(U){if(!X?.relations)return{};let V=X.relations[U];if(!V)return{};let Q={};for(let[O,K]of Object.entries(V))if(K&&typeof K==="object"&&Object.keys(K).length>0)Q[O]=K;return Q},hasRelationship(U,V){if(!X?.relations)return!1;let Q=X.relations[U];if(!Q)return!1;return Object.values(Q).some((O)=>O&&typeof O==="object"&&(V in O))},getRelationshipType(U,V){if(!X?.relations)return null;let Q=X.relations[U];if(!Q)return null;for(let[O,K]of Object.entries(Q))if(K&&typeof K==="object"&&V in K)return O;return null},getRelationshipTarget(U,V){if(!X?.relations)return null;let Q=X.relations[U];if(!Q)return null;for(let[O,K]of Object.entries(Q))if(K&&typeof K==="object"&&V in K){let I=K[V];if(typeof I==="string")return X.modelToTable[I]||I;else if(I&&typeof I==="object"){if("model"in I)return X.modelToTable[I.model]||I.model;if("target"in I)return X.modelToTable[I.target]||I.target}}return null}}}function pL(){X1.clear()}function dL($){X1.setMaxSize($)}var c,X1,i$=n(()=>{F9(),G8(),c={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},X1=new H2});async function eU(){console.log("-- Clearing query cache..."),pL(),console.log("-- \u2713 Query cache cleared")}async function $E(){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 ZE($={}){if(console.log("-- Configuring query cache..."),console.log(),$.size!==void 0){let Z=Number($.size);if(Number.isNaN(Z)||Z<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");dL(Z),console.log(`-- \u2713 Cache max size set to: ${Z}`)}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")}var cL=n(()=>{i$()});async function uL(){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 $=W0(),Z=mL({input:N1.stdin,output:N1.stdout,prompt:"qb> "}),X="",_=!1,L=`
78
+ `,[`User ${Q}`,`user${Q}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(Q){throw console.error("-- Failed to setup test table:",Q),Q}let U=[];if(Z.includes("select")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").where({active:1}).limit(10).execute(),Q.push(performance.now()-z)}U.push({operation:"SELECT with WHERE + LIMIT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("select")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").where({id:1}).first(),Q.push(performance.now()-z)}U.push({operation:"SELECT by ID (first)",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("count")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.selectFrom("bench_users").count(),Q.push(performance.now()-z)}U.push({operation:"COUNT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("insert")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.insertInto("bench_users").values({name:`Bench User ${L}`,email:`bench${L}@example.com`,created_at:new Date().toISOString()}).execute(),Q.push(performance.now()-z)}U.push({operation:"INSERT",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("update")){let Q=[];for(let L=0;L<$;L++){let z=performance.now();await Y.updateTable("bench_users").set({active:0}).where({id:1}).execute(),Q.push(performance.now()-z)}U.push({operation:"UPDATE by ID",avgTime:Q.reduce((L,z)=>L+z,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}if(Z.includes("delete")){let Q=[],L=[];for(let z=0;z<$;z++){let j=await Y.insertInto("bench_users").values({name:"To Delete",email:`delete${z}@example.com`,created_at:new Date().toISOString()}).execute();L.push(j)}for(let z=0;z<$;z++){let j=performance.now();await Y.deleteFrom("bench_users").where({id:L[z]}).execute(),Q.push(performance.now()-j)}U.push({operation:"DELETE by ID",avgTime:Q.reduce((z,j)=>z+j,0)/Q.length,minTime:Math.min(...Q),maxTime:Math.max(...Q),iterations:$})}console.log("-- Benchmark Results"),console.log();let _=Math.max(...U.map((Q)=>Q.operation.length));console.log("Operation".padEnd(_+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(_+2+12+12+12+12));for(let Q of U){let L=Q.operation.padEnd(_+2),z=Q.avgTime.toFixed(3).padStart(12),j=Q.minTime.toFixed(3).padStart(12),E=Q.maxTime.toFixed(3).padStart(12),V=(1000/Q.avgTime).toFixed(0).padStart(12);console.log(`${L}${z}${j}${E}${V}`)}console.log();try{await m.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(Q){console.error("-- Warning: Failed to cleanup test table:",Q)}}var x_=e(()=>{$X(),y0()});function B_(X){return X.endsWith("s")?X.slice(0,-1):X}function PX(X,$,Z,Y={}){let U=Y.singularize??B_,Q=X.relations?.[$]?.belongsToMany?.[Z];if(Q==null)return null;let L=typeof Q==="object",z=L?Q:null,j=L?z.model:Q,E=X.modelToTable[j]||j,V,G;if(z?.table)V=z.table;else if(z?.through){if(G=z.through,V=X.modelToTable[z.through],!V)throw Error(`[query-builder] belongsToMany relation '${Z}' on '${$}' references unknown through model '${z.through}'. Make sure '${z.through}' is registered via defineModels({...}).`)}else{let w=U($),T=U(E);V=[w,T].sort().join("_")}let J=z?.foreignKey??`${U($)}_id`,W=z?.relatedKey??`${U(E)}_id`,F={};if(z?.pivot?.columns)Object.assign(F,z.pivot.columns);if(G&&Y.models){let w=Y.models[G],T=w?.definition??w?.getDefinition?.()??w,N=T?.attributes??{};for(let[q,H]of Object.entries(N)){if(q===J||q===W||q===(T?.primaryKey??"id"))continue;F[q]={default:H?.default,nullable:H?.nullable,validation:H?.validation}}}let K=Boolean(z?.pivot?.timestamps),D=Object.keys(F);return{pivotTable:V,fkParent:J,fkRelated:W,pivotColumns:D,pivotColumnDefs:F,pivotModelName:G,timestamps:K,relatedModelName:j,relatedTable:E,hasConfig:L}}function*IG(X,$={}){let Z=X.relations;if(!Z)return;for(let[Y,U]of Object.entries(Z)){let _=U?.belongsToMany;if(!_)continue;for(let Q of Object.keys(_)){let L=PX(X,Y,Q,$);if(L)yield{parentTable:Y,relationKey:Q,resolved:L}}}}function d8(X){return typeof X==="object"&&X!==null&&"raw"in X&&typeof X.raw==="string"}function KG(X,...$){if(typeof X==="string")return{raw:X};let Z=X[0];for(let Y=0;Y<$.length;Y++)Z+=w9($[Y])+X[Y+1];return{raw:Z}}function a0(X){return J0(f.dialect)?`\`${X.replace(/`/g,"``")}\``:`"${X.replace(/"/g,'""')}"`}function e$(X,$=1){let Z=Object.keys(X[0]??{}),Y=[],U=$,_=X.map((Q)=>{return`(${Z.map((z)=>{return Y.push(Q[z]),i(U++)}).join(", ")})`});return{colsSql:Z.map(a0).join(", "),valuesSql:_.join(", "),params:Y,nextIndex:U}}function uX(X){return Boolean(X&&(X.onSlowQuery||X.slowQueryThresholdMs!=null&&X.slowQueryThresholdMs>=0))}function TY(X){if(typeof X==="string")return X;if(d8(X))return X.raw;if(X&&typeof X==="object"){let $=X;if(typeof $.raw==="function")return String($.raw());if(typeof $.sql==="string")return $.sql;let Z=String(X);if(Z!=="[object Object]")return Z}throw TypeError(`[query-builder] select(): unsupported column ${String(X)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function u(X,$){if(!s.IDENTIFIER.test(X)){let Z=$?` in ${$}`:"";throw Error(`[query-builder] Invalid identifier${Z}: '${X}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function v0(X,$){if(typeof X!=="string")throw TypeError(`[query-builder] ${$}: operator must be a string, got ${typeof X}`);let Z=X.toLowerCase();if(!w1.has(Z))throw TypeError(`[query-builder] ${$}: refusing to use '${X}' as a SQL operator \u2014 not in the allowed set (${[...w1].join(", ")})`);return X}function Q9(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);if(X.length>129)throw TypeError(`[query-builder] ${$}: identifier '${X}' too long`);let Z=X.split(".");if(Z.length>2)throw TypeError(`[query-builder] ${$}: identifier '${X}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let Y of Z)if(!/^[A-Z_][A-Z0-9_]*$/i.test(Y))throw TypeError(`[query-builder] ${$}: identifier segment '${Y}' contains characters outside [A-Za-z0-9_]`)}function KX(X,$){if(typeof X==="string")return y_($),X;if(X===null||X===void 0)throw TypeError(`[query-builder] ${$}: fragment must be a SqlFragment, got ${X}`);if(d8(X))return X.raw;if(typeof X==="object"){let Z=X;if(typeof Z.raw==="string")return Z.raw;if(typeof Z.raw==="function"){let U=Z.raw();if(typeof U==="string")return U}if(typeof Z.sql==="string")return Z.sql;let Y=String(X);if(Y!=="[object Object]"&&Y!=="[object Promise]")return Y}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').")}function y_(X){if(q1.has(X))return;q1.add(X),console.warn(`[query-builder] ${X}: bare string passed to a *Raw method. Prefer \`sql\`...\`\` tagged-template fragments so values are parameterised `+"instead of concatenated \u2014 concatenating request input into SQL is an "+"injection vector. This will become a hard error in a future release.")}function w9(X){if(X===null)return"NULL";if(typeof X==="number"&&Number.isFinite(X))return String(X);if(typeof X==="boolean")return X?"1":"0";if(typeof X==="string")return`'${X.replace(/'/g,"''")}'`;if(X instanceof Date)return`'${X.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof X}`)}function h_(X,$){let Z=Array.isArray(X)?X:X?[X]:[],Y=[];if(Z.length)Y.push(`PARTITION BY ${Z.join(", ")}`);if($&&$.length)Y.push(`ORDER BY ${$.map(([U,_])=>`${U} ${_==="desc"?"DESC":"ASC"}`).join(", ")}`);return Y.length?`OVER (${Y.join(" ")})`:"OVER ()"}class _U{cache=new Map;maxSize=100;get(X){let $=this.cache.get(X);if(!$)return null;if(Date.now()>$.expiresAt)return this.cache.delete(X),null;return this.cache.delete(X),this.cache.set(X,$),$.data}set(X,$,Z){if(this.cache.has(X))this.cache.delete(X);if(this.cache.size>=this.maxSize){let Y=Date.now(),U=!1;for(let[_,Q]of this.cache)if(Y>Q.expiresAt){if(this.cache.delete(_),U=!0,this.cache.size<this.maxSize)break}if(!U){let _=this.cache.keys().next().value;if(_!==void 0)this.cache.delete(_)}}this.cache.set(X,{data:$,expiresAt:Date.now()+Z})}clear(){this.cache.clear()}setMaxSize(X){this.maxSize=X}}function v_(X){let $=String(X?.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 b_(X,$){if(!$||$.length===0)return!1;let Z=X&&(X.code||X.sqlState||X.sqlstate);if(!Z)return!1;return $.includes(Z)}function f_(X){return new Promise(($)=>setTimeout($,X))}function X8(X){let $=oX.get(X);if($!==void 0)return $;let Z=g_(X);if(oX.size>=m_)oX.clear();return oX.set(X,Z),Z}function g_(X){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}],Z=[],Y=0,U=!1,_="";for(let E=0;E<X.length;E++){let V=X[E];if(U){if(V===_){if(X[E+1]===_){E++;continue}U=!1}continue}if(V==="'"||V==='"'||V==="`"){U=!0,_=V;continue}if(V==="("){Y++;continue}if(V===")"){Y--;continue}if(Y!==0)continue;if(E===0||!/\s/.test(X[E-1]))continue;let G=X.charCodeAt(E)&-33;if(G!==71&&G!==79&&G!==72&&G!==76&&G!==87)continue;let J=X.slice(E);for(let{key:W,tokens:F}of $){let K=J.match(F);if(!K)continue;Z.push({key:W,start:E}),E+=K[0].length-1;break}}if(Z.length<=1)return X;let Q=X.slice(0,Z[0].start).trimEnd(),L={};for(let E=0;E<Z.length;E++){let V=Z[E].start,G=E+1<Z.length?Z[E+1].start:X.length,J=X.slice(V,G).trim();if(!L[Z[E].key])L[Z[E].key]=[];L[Z[E].key].push(J)}let j=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((E)=>L[E]).map((E)=>L[E].join(" ")).join(" ");return j?`${Q} ${j}`:Q}function d_(X,$){let Z=Math.max(1,$?.baseMs??50),Y=Math.max(1,$?.factor??2),U=Math.max(Z,$?.maxMs??2000),_=Math.min(U,Z*Y**Math.max(0,X-1));if($?.jitter){let Q=Math.random()*_*0.2;_=_-Q/2}return Math.floor(_)}function K0(X){let $=X?.sql??BX(),Z=X?.meta,Y=X?.schema,U=new Map;function _(G){if(Array.isArray(G)){let[D,w,T]=G;u(D,"where(column)");let N=String(D);switch(w){case"in":if(Array.isArray(T)){let q=h0(T.length);return $.unsafe(`${N} IN (${q})`,T)}return $.unsafe(`${N} IN (${i(1)})`,[T]);case"not in":if(Array.isArray(T)){let q=h0(T.length);return $.unsafe(`${N} NOT IN (${q})`,T)}return $.unsafe(`${N} NOT IN (${i(1)})`,[T]);case"like":return $.unsafe(`${N} LIKE ${i(1)}`,[T]);case"is":case"is not":{if(T!==null&&T!==void 0)throw TypeError(`[query-builder] where(..., '${w}', ?): operator '${w}' only accepts NULL/undefined as value, got ${typeof T} (${String(T)})`);return $.unsafe(`${N} IS ${w==="is not"?"NOT ":""}NULL`)}case"!=":return $.unsafe(`${N} <> ${i(1)}`,[T]);case"<":case">":case"<=":case">=":case"=":return $.unsafe(`${N} ${w} ${i(1)}`,[T]);default:throw TypeError(`[query-builder] where(..., '${String(w)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in G)return G.raw;let J=Object.keys(G);if(J.length===0)return $.unsafe("");let W=[],F=[],K=1;for(let D of J){u(D,"where(object key)");let w=G[D];if(Array.isArray(w)){let T=h0(w.length,K);W.push(`${D} IN (${T})`),F.push(...w),K+=w.length}else W.push(`${D} = ${i(K++)}`),F.push(w)}return $.unsafe(W.join(" AND "),F)}function Q(G,J,W){if(!W)return J;let F=_(W);return $`${J} WHERE ${F}`}function L(G){let J=f.debug?.captureText;if(f.debug)f.debug.captureText=!0;let W=String(G);if(f.debug)f.debug.captureText=J;return W}function z(G){if(!G||typeof G!=="object")return;if(Array.isArray(G.values))return G.values;if(Array.isArray(G.parameters))return G.parameters;if(Array.isArray(G.params))return G.params;return}function j(G,J,W){let F=f.hooks,K=F?.slowQueryThresholdMs,D=K!=null&&K>=0,w=Boolean(F?.onSlowQuery||D),T=F&&(F.onQueryStart||F.onQueryEnd||F.onQueryError||F.startSpan||w),N=W?.timeoutMs&&W.timeoutMs>0||W?.signal;if(!T&&!N)return G.execute();let q=L(G),H=z(G),x=Date.now(),h;try{if(F?.onQueryStart?.({sql:q,params:H,kind:J}),F?.startSpan)h=F.startSpan({sql:q,params:H,kind:J})}catch{}let c=!1,y=(p,o)=>{if(c)return;c=!0;let D0=Date.now()-x;try{if(p)F?.onQueryError?.({sql:q,params:H,error:p,durationMs:D0,kind:J});else if(F?.onQueryEnd?.({sql:q,params:H,durationMs:D0,rowCount:o,kind:J}),D&&D0>=K)if(F?.onSlowQuery)F.onSlowQuery({sql:q,params:H,durationMs:D0,kind:J});else console.warn(`[query-builder] slow query (${D0}ms >= ${K}ms): ${q}`)}catch{}try{h?.end(p)}catch{}},g=G.execute(),v=[g],n;if(W?.timeoutMs&&W.timeoutMs>0){let p=new Promise((o,D0)=>{n=setTimeout(()=>{try{G.cancel?.()}catch{}let M0=Error(`Query timed out after ${W.timeoutMs}ms`);M0.code="EBQBTIMEOUT",D0(M0)},W.timeoutMs)});v.push(p)}if(W?.signal){if(W.signal.aborted){try{G.cancel?.()}catch{}let o=Error("Query aborted");return o.code="EBQBABORT",y(o),Promise.reject(o)}let p=()=>{try{G.cancel?.()}catch{}};W.signal.addEventListener("abort",p,{once:!0}),g.finally(()=>{W.signal?.removeEventListener("abort",p)})}return Promise.race(v).then((p)=>{clearTimeout(n);let o=Array.isArray(p)?p.length:typeof p==="number"?p:void 0;return y(void 0,o),p}).catch((p)=>{throw clearTimeout(n),y(p),p})}function E(G,J){let W=J??L(G);return{sql:W,toString:()=>W,execute:()=>G.execute(),values:()=>G.values(),raw:()=>G.raw()}}function V(G,J){let W=$,F=J&&J.length>0?`SELECT ${J.join(", ")} FROM ${String(G)}`:`SELECT * FROM ${String(G)}`,K=null,D=()=>{if(K===null){let O=X8(F);K=B.length>0?$.unsafe(O,B):$.unsafe(O)}return K},w=(O,I)=>{let M=!s.WHERE.test(F)?"WHERE":O==="WHERE"?"AND":O;F=`${F} ${M} ${I}`},T=(O,I)=>{let R=I.__rawState?.();if(R){let M=B.length,C=f.dialect==="postgres"?R.sql.replace(/\$(\d+)/g,(P,S)=>`$${Number(S)+M}`):R.sql;F+=` ${O} ${C}`,B.push(...R.params)}else F+=` ${O} ${String(I.toSQL())}`;K=null},N=(O)=>{let I=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,R=0,M=-1,C;while(C=I.exec(F))if(C[0]==="(")R++;else if(C[0]===")")R=Math.max(0,R-1);else if(R===0){M=C.index;break}F=M>=0?`${F.slice(0,M)}${O} ${F.slice(M)}`:`${F} ${O}`,K=null},q=new Set,H,x,h=!1,c=!1,y=!1,g=new Map,v=new Set,n=60000,p=(O)=>{if(f.relations.singularizeStrategy==="none")return O;return O.endsWith("s")?O.slice(0,-1):O},o=(O)=>{if(!Z)return null;return PX(Z,String(G),O,{singularize:p,models:Z.models})},D0=(O)=>{if(!O||typeof O!=="object"||v.size===0)return O;let I;for(let R of Object.keys(O))if(R.startsWith("pivot_")){if(!I)I={};I[R.slice(6)]=O[R],delete O[R]}if(I)O.pivot=I;return O},M0=(O)=>{if(v.size===0||!O)return O;if(Array.isArray(O))for(let I=0;I<O.length;I++)D0(O[I]);else D0(O);return O},o0=(O)=>{if(!Z)return;if(q.has(O.pivotTable))return;let I=String(G),R=Z.primaryKeys[I]??"id";u(O.pivotTable,"wherePivot auto-join (pivot table)"),u(O.fkParent,"wherePivot auto-join (parent FK)"),u(I,"wherePivot auto-join (parent table)"),u(R,"wherePivot auto-join (parent PK)"),K=W`${D()} LEFT JOIN ${W(O.pivotTable)} ON ${W(`${O.pivotTable}.${O.fkParent}`)} = ${W(`${I}.${R}`)}`,F=`${F} LEFT JOIN ${O.pivotTable} ON ${O.pivotTable}.${O.fkParent} = ${I}.${R}`,q.add(O.pivotTable)},a=[],B=[],u9=(O)=>{if(s.SELECT_STAR.test(F))F=F.replace(s.SELECT_STAR,`SELECT *, ${O}`);else if(s.SELECT.test(F))F=F.replace(s.SELECT_FROM,`SELECT $1, ${O} FROM`);let I=String(D());if(s.SELECT_STAR.test(I)){let R=I.replace(s.SELECT_STAR,`SELECT *, ${O}`);K=$.unsafe(R)}else if(s.SELECT.test(I)){if(s.SELECT_FROM.exec(I)){let M=I.replace(s.SELECT_FROM,`SELECT $1, ${O} FROM`);K=$.unsafe(M)}}},e0=(O,I,R,M)=>{u9(`${O} ${h_(R,M)} AS ${I}`)},UX=(O,I,R,M)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)");let C=`${O.endsWith("s")?O.slice(0,-1):O}_id`;u(C,"relationship subquery (foreign key)");let P=`SELECT 1 FROM ${I} WHERE ${I}.${C} = ${O}.${R}`;if(M){let A=M({where:(d,k,b)=>{return u(d,"relationship subquery condition"),`${I}.${d} ${v0(k,"whereHas callback")} ${w9(b)}`}});if(A)P+=` AND ${A}`}return P},h$=(O,I,R,M)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)");let C=`${I.endsWith("s")?I.slice(0,-1):I}_id`;u(C,"relationship subquery (foreign key)");let P=`SELECT 1 FROM ${I} WHERE ${I}.${R} = ${O}.${C}`;if(M){let A=M({where:(d,k,b)=>{return u(d,"relationship subquery condition"),`${I}.${d} ${v0(k,"whereHas callback")} ${w9(b)}`}});if(A)P+=` AND ${A}`}return P},v$=(O,I,R,M,C,P)=>{u(O,"relationship subquery (parent table)"),u(I,"relationship subquery (target table)"),u(R,"relationship subquery (primary key)"),u(M,"relationship subquery (target primary key)");let S=P&&Z?PX(Z,O,P,{singularize:p,models:Z.models}):null,A=p(O),d=p(I),k=S?.pivotTable??[A,d].sort().join("_"),b=S?.fkParent??`${A}_id`,l=S?.fkRelated??`${d}_id`;u(k,"relationship subquery (pivot table)"),u(b,"relationship subquery (foreign key A)"),u(l,"relationship subquery (foreign key B)");let X0=`SELECT 1 FROM ${k} JOIN ${I} ON ${I}.${M} = ${k}.${l} WHERE ${k}.${b} = ${O}.${R}`;if(C){let r=C({where:(T0,X9,_9)=>{return u(T0,"relationship subquery condition"),`${I}.${T0} ${v0(X9,"whereHas callback")} ${w9(_9)}`}});if(r)X0+=` AND ${r}`}return X0},S7=(O,I,R)=>{u(O,"withCount (parent table)"),u(I,"withCount (target table)"),u(R,"withCount (primary key)");let M=`${O.endsWith("s")?O.slice(0,-1):O}_id`;return u(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${I} WHERE ${I}.${M} = ${O}.${R})`},A7=(O,I,R,M)=>{u(O,"withCount (parent table)"),u(I,"withCount (target table)"),u(R,"withCount (primary key)");let C=M&&Z?PX(Z,O,M,{singularize:p,models:Z.models}):null,P=p(O),S=p(I),A=C?.pivotTable??[P,S].sort().join("_"),d=C?.fkParent??`${P}_id`;return u(A,"withCount (pivot table)"),u(d,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${A} WHERE ${A}.${d} = ${O}.${R})`},b$=(O,I,R)=>{if(!Z)return;u(R,`with${O[0]}${O.slice(1).toLowerCase()} (column)`);let M=String(G),C=Z.relations?.[M];if(!C)return;let P=Object.entries(C).find(([r,T0])=>T0&&typeof T0==="object"&&(I in T0));if(!P)return;let[S,A]=P,d=A[I],k=typeof d==="string"?d:d?.model||d?.target||d,b=Z.modelToTable[k]||k,l=Z.primaryKeys[M]??"id";u(b,`with${O} (target table)`);let X0=`${O}(${b}.${R})`,w0;if(S==="hasMany"||S==="hasOne"){let r=`${M.endsWith("s")?M.slice(0,-1):M}_id`;u(r,`with${O} (foreign key)`),w0=`(SELECT ${X0} FROM ${b} WHERE ${b}.${r} = ${M}.${l})`}else if(S==="belongsToMany"){let r=Z?PX(Z,M,I,{singularize:p,models:Z.models}):null,T0=p(M),X9=p(b),_9=r?.pivotTable??[T0,X9].sort().join("_"),_X=r?.fkParent??`${T0}_id`,U0=r?.fkRelated??`${X9}_id`,pX=Z.primaryKeys[b]??"id";u(_9,`with${O} (pivot table)`),u(_X,`with${O} (foreign key)`),u(U0,`with${O} (related key)`),w0=`(SELECT ${X0} FROM ${_9} JOIN ${b} ON ${b}.${pX} = ${_9}.${U0} WHERE ${_9}.${_X} = ${M}.${l})`}else return;u9(`${w0} AS ${I}_${O.toLowerCase()}_${R}`)},I5=()=>{if(g.size===0)return;let O=[];for(let[I,R]of g.entries()){let M=o(I);if(!M)continue;for(let P of R)u(P,"withPivot");let C=R.map((P)=>`${M.pivotTable}.${P} AS pivot_${P}`);O.push(...C)}if(O.length>0){let I=O.join(", ");u9(I)}};return new Proxy({distinct(){return F=F.replace(/^SELECT\s+/i,"SELECT DISTINCT "),K=null,this},distinctOn(...O){let I=O.map(String).join(", ");return F=F.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${I}) `),K=null,this},selectRaw(O){let I=KX(O,"selectRaw(fragment)"),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${I}${F.substring(R)}`;else F+=`, ${I}`;return K=null,this},rowNumber(O="row_number",I,R){let M=[];if(I){let A=Array.isArray(I)?I:[I];M.push(`PARTITION BY ${A.join(", ")}`)}if(R&&R.length)M.push(`ORDER BY ${R.map(([A,d])=>`${A} ${d==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${O}`,S=F.indexOf(" FROM ");if(S!==-1)F=`${F.substring(0,S)}, ${P}${F.substring(S)}`;else F+=`, ${P}`;return K=null,this},denseRank(O="dense_rank",I,R){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(R&&R.length)C.push(`ORDER BY ${R.map(([d,k])=>`${d} ${k==="desc"?"DESC":"ASC"}`).join(", ")}`);let S=`DENSE_RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,A=F.indexOf(" FROM ");if(A!==-1)F=`${F.substring(0,A)}, ${S}${F.substring(A)}`;else F+=`, ${S}`;return K=null,this},rank(O="rank",I,R){let M=Array.isArray(I)?I:I?[I]:[],C=[];if(M.length)C.push(`PARTITION BY ${M.join(", ")}`);if(R&&R.length)C.push(`ORDER BY ${R.map(([d,k])=>`${d} ${k==="desc"?"DESC":"ASC"}`).join(", ")}`);let S=`RANK() ${C.length?`OVER (${C.join(" ")})`:"OVER ()"} AS ${O}`,A=F.indexOf(" FROM ");if(A!==-1)F=`${F.substring(0,A)}, ${S}${F.substring(A)}`;else F+=`, ${S}`;return K=null,this},over(O,I,R={}){return e0(O,I,R.partitionBy,R.orderBy),this},lag(O,I={}){let R=[O,String(I.offset??1)];if(I.defaultValue!==void 0)R.push(String(I.defaultValue));return e0(`LAG(${R.join(", ")})`,I.alias??`${O}_lag`,I.partitionBy,I.orderBy),this},lead(O,I={}){let R=[O,String(I.offset??1)];if(I.defaultValue!==void 0)R.push(String(I.defaultValue));return e0(`LEAD(${R.join(", ")})`,I.alias??`${O}_lead`,I.partitionBy,I.orderBy),this},sumOver(O,I={}){return e0(`SUM(${O})`,I.alias??`${O}_sum`,I.partitionBy,I.orderBy),this},avgOver(O,I={}){return e0(`AVG(${O})`,I.alias??`${O}_avg`,I.partitionBy,I.orderBy),this},countOver(O="*",I={}){return e0(`COUNT(${O})`,I.alias??"count_over",I.partitionBy,I.orderBy),this},minOver(O,I={}){return e0(`MIN(${O})`,I.alias??`${O}_min`,I.partitionBy,I.orderBy),this},maxOver(O,I={}){return e0(`MAX(${O})`,I.alias??`${O}_max`,I.partitionBy,I.orderBy),this},firstValue(O,I={}){return e0(`FIRST_VALUE(${O})`,I.alias??`${O}_first`,I.partitionBy,I.orderBy),this},lastValue(O,I={}){return e0(`LAST_VALUE(${O})`,I.alias??`${O}_last`,I.partitionBy,I.orderBy),this},selectAll(){return this},select(O){if(!O)return this;let I=Array.isArray(O)?O:[O];if(I.length===0)return this;let R=I.map(TY),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(F),C=M?M[1]:"",P=F.indexOf(" FROM ");if(P!==-1)F=`SELECT ${C}${R.join(", ")}${F.substring(P)}`;else F=`SELECT ${C}${R.join(", ")} FROM ${G}`;return K=null,this},addSelect(...O){if(!O.length)return this;let I=O.map(TY),R=F.indexOf(" FROM ");if(R!==-1)F=`${F.substring(0,R)}, ${I.join(", ")}${F.substring(R)}`;else F+=`, ${I.join(", ")}`;return K=null,this},with(...O){if(!Z||!O||O.length===0)return this;let I=[];for(let k of O){if(!k)continue;if(typeof k==="string")I.push({name:k});else if(typeof k==="object"&&!Array.isArray(k))for(let[b,l]of Object.entries(k))if(typeof l==="function")I.push({name:b,callback:l});else I.push({name:b})}if(I.length===0)return this;let R=f.relations.maxEagerLoad??50;if(I.length>R)throw Error(`[query-builder] Too many relationships to eager load (${I.length}). Maximum allowed: ${R}`);let M=String(G),C=new Set,P=new Set,S=new Map,A=(k)=>{let b=Z.relations?.[k];if(!b)return[];return[...Object.keys(b.hasOne||{}),...Object.keys(b.hasMany||{}),...Object.keys(b.belongsTo||{}),...Object.keys(b.belongsToMany||{}),...Object.keys(b.hasOneThrough||{}),...Object.keys(b.hasManyThrough||{}),...Object.keys(b.morphOne||{}),...Object.keys(b.morphMany||{}),...Object.keys(b.morphToMany||{}),...Object.keys(b.morphedByMany||{})]},d=(k,b,l=0,X0)=>{let w0=f.relations.maxDepth??10;if(l>=w0)throw Error(`[query-builder] Maximum relationship depth (${w0}) exceeded at '${b}'. Consider using separate queries or increasing maxDepth.`);let r=Z.relations?.[k];if(!r)return k;let T0=($0)=>{if(f.softDeletes?.enabled&&f.softDeletes?.defaultFilter){let Z0=f.softDeletes.column||"deleted_at";return` AND ${$0}.${Z0} IS NULL`}return""},X9=($0)=>{if(!X0)return"";let Z0=[],H0=(Q0,r0,I9)=>{u(String(Q0),"with() constraint column");let QX=v0(r0,"with() constraint operator");Z0.push(`${$0}.${String(Q0)} ${QX} ${w9(I9)}`)},W0=(Q0)=>()=>{throw Error(`[query-builder] with('${b}', ...): ${Q0} 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.)`)},q0={where:(Q0,r0,I9)=>{if(Array.isArray(Q0))H0(Q0[0],Q0[1],Q0[2]);else if(Q0&&typeof Q0==="object")for(let QX of Object.keys(Q0))H0(QX,"=",Q0[QX]);else if(r0!==void 0&&I9!==void 0)H0(Q0,r0,I9);else if(r0!==void 0)H0(Q0,"=",r0);return q0},whereIn:(Q0,r0)=>{return u(String(Q0),"with() constraint column"),Z0.push(`${$0}.${String(Q0)} IN (${r0.map(w9).join(", ")})`),q0},whereNull:(Q0)=>{return u(String(Q0),"with() constraint column"),Z0.push(`${$0}.${String(Q0)} IS NULL`),q0},whereNotNull:(Q0)=>{return u(String(Q0),"with() constraint column"),Z0.push(`${$0}.${String(Q0)} IS NOT NULL`),q0},orderBy:W0("orderBy()"),limit:W0("limit()"),offset:W0("offset()"),take:W0("take()")};return X0(q0),Z0.length?` AND ${Z0.join(" AND ")}`:""},_9=()=>{let $0=(W0)=>{let q0=W0?.[b];return q0?Z.modelToTable[q0]:void 0},Z0=(W0)=>{let q0=W0?.[b],Q0=typeof q0==="string"?q0:q0?.model;return Q0?Z.modelToTable[Q0]:void 0},H0=(W0)=>{let q0=W0?.[b];return q0?.target?Z.modelToTable[q0.target]:void 0};return $0(r?.hasOne)||$0(r?.hasMany)||$0(r?.belongsTo)||Z0(r?.belongsToMany)||H0(r?.hasOneThrough)||H0(r?.hasManyThrough)||$0(r?.morphOne)||$0(r?.morphMany)||$0(r?.morphToMany)||$0(r?.morphedByMany)},_X=_9()??(Z.modelToTable[b]||Z.tableToModel[b]?Z.modelToTable[b]??b:b),U0=String(_X);if(!_X||!_9()&&!Z.modelToTable[b]&&!Z.tableToModel[b]){let $0=A(k);if($0.length>0&&!$0.includes(b)){let Z0=` Available relationships: ${$0.join(", ")}`;throw Error(`[query-builder] Relationship '${b}' not found on table '${k}'.${Z0}`)}}if(f.relations.detectCycles!==!1){let $0=`${k}->${U0}`;if(C.has($0))throw Error(`[query-builder] Circular relationship detected: ${$0}. This would cause an infinite loop.`);C.add($0)}if(!U0||U0===k)return k;let pX=r?.hasOneThrough?.[b]||r?.hasManyThrough?.[b];if(pX){let{through:$0,target:Z0}=pX,H0=Z.modelToTable[$0]||$0,W0=Z.modelToTable[Z0]||Z0,q0=Z.primaryKeys[k]??"id",Q0=Z.primaryKeys[H0]??"id",r0=`${p(k)}_id`,I9=`${p(H0)}_id`;return N(`LEFT JOIN ${H0} ON ${H0}.${r0} = ${k}.${q0} LEFT JOIN ${W0} ON ${W0}.${I9} = ${H0}.${Q0}`),q.add(H0),q.add(W0),W0}if(Boolean(r?.belongsToMany?.[b])){let $0=PX(Z,k,b,{singularize:p,models:Z.models}),Z0=$0?.pivotTable??[p(k),p(U0)].sort().join("_"),H0=Z.primaryKeys[k]??"id",W0=Z.primaryKeys[U0]??"id",q0=$0?.fkParent??`${p(k)}_id`,Q0=$0?.fkRelated??`${p(U0)}_id`;return N(`LEFT JOIN ${Z0} ON ${Z0}.${q0} = ${k}.${H0} LEFT JOIN ${U0} ON ${U0}.${W0} = ${Z0}.${Q0}${X9(U0)}`),q.add(Z0),q.add(U0),U0}if(Boolean(r?.morphToMany?.[b])){let $0=b,Z0=`${p(U0)}_${$0}`,H0=Z.primaryKeys[k]??"id",W0=Z.primaryKeys[U0]??"id",q0=`${$0}_type`,Q0=`${$0}_id`,r0=`${p(U0)}_id`,I9=w9(Z.tableToModel[k]||k);return N(`LEFT JOIN ${Z0} ON ${Z0}.${Q0} = ${k}.${H0} AND ${Z0}.${q0} = ${I9} LEFT JOIN ${U0} ON ${U0}.${W0} = ${Z0}.${r0}`),q.add(Z0),q.add(U0),U0}if(Boolean(r?.morphedByMany?.[b])){let $0=r.morphedByMany?.[b]||b,Z0=Z.modelToTable[$0]||$0,H0=p(k),W0=`${p(Z0)}_${H0}`,q0=Z.primaryKeys[k]??"id",Q0=Z.primaryKeys[Z0]??"id",r0=`${H0}_type`,I9=`${H0}_id`,QX=`${p(Z0)}_id`,v7=w9(Z.tableToModel[Z0]||Z0);return N(`LEFT JOIN ${W0} ON ${W0}.${QX} = ${k}.${q0} LEFT JOIN ${Z0} ON ${Z0}.${Q0} = ${W0}.${I9} AND ${W0}.${r0} = ${v7}`),q.add(W0),q.add(Z0),Z0}if(Boolean(r?.belongsTo?.[b])){let $0=`${p(U0)}_id`,Z0=Z.primaryKeys[U0]??"id";return N(`LEFT JOIN ${U0} ON ${k}.${$0} = ${U0}.${Z0}${X9(U0)}`),q.add(U0),U0}let k7=Boolean(r?.morphOne?.[b]),x7=Boolean(r?.morphMany?.[b]);if(k7||x7){let $0=`${b}_type`,Z0=`${b}_id`,H0=Z.primaryKeys[k]??"id",W0=w9(Z.tableToModel[k]||k);return N(`LEFT JOIN ${U0} ON ${U0}.${Z0} = ${k}.${H0} AND ${U0}.${$0} = ${W0}`),q.add(U0),U0}let B7=`${p(k)}_id`,y7=Z.primaryKeys[k]??"id",h7=`${T0(U0)}${X9(U0)}`;return N(`LEFT JOIN ${U0} ON ${U0}.${B7} = ${k}.${y7}${h7}`),q.add(U0),U0};for(let k of I){let b=k.name.trim();if(k.callback)S.set(b,k.callback);let l=b.split("."),X0=M,w0=0;for(let r of l){if(!r||r.trim().length===0)continue;let T0=r.trim(),X9=S.get(T0);X0=d(X0,T0,w0,X9)||X0,w0++}P.add(b)}if(g.size>0){let k=[];for(let[b,l]of g.entries()){let X0=o(b);if(!X0)continue;let w0=l.map((r)=>`${X0.pivotTable}.${r} AS pivot_${r}`);k.push(...w0)}if(k.length>0){let b=k.join(", ");u9(b)}}return K=null,this},whereHas(O,I){if(!Z)return this;let R=String(G),M=Z.relations?.[R];if(!M)throw Error(`[query-builder] No relationships defined for table '${R}'`);let C=Object.entries(M).find(([l,X0])=>X0&&typeof X0==="object"&&(O in X0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${R}'`);let[P,S]=C,A=S[O],d=typeof A==="string"?A:A?.model||A?.target||A,k=Z.modelToTable[d]||d,b;if(P==="hasMany"||P==="hasOne"){let l=Z.primaryKeys[R]??"id";b=UX(R,k,l,I)}else if(P==="belongsTo"){let l=Z.primaryKeys[k]??"id";b=h$(R,k,l,I)}else if(P==="belongsToMany"){let l=Z.primaryKeys[R]??"id",X0=Z.primaryKeys[k]??"id";b=v$(R,k,l,X0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${P}' for whereHas`);K=W`${D()} WHERE EXISTS (${W([b])})`;try{w("WHERE",`EXISTS (${b})`)}catch{}return this},whereDoesntHave(O,I){if(!Z)return this;let R=String(G),M=Z.relations?.[R];if(!M)throw Error(`[query-builder] No relationships defined for table '${R}'`);let C=Object.entries(M).find(([l,X0])=>X0&&typeof X0==="object"&&(O in X0));if(!C)throw Error(`[query-builder] Relationship '${O}' not found on table '${R}'`);let[P,S]=C,A=S[O],d=typeof A==="string"?A:A?.model||A?.target||A,k=Z.modelToTable[d]||d,b;if(P==="hasMany"||P==="hasOne"){let l=Z.primaryKeys[R]??"id";b=UX(R,k,l,I)}else if(P==="belongsTo"){let l=Z.primaryKeys[k]??"id";b=h$(R,k,l,I)}else if(P==="belongsToMany"){let l=Z.primaryKeys[R]??"id",X0=Z.primaryKeys[k]??"id";b=v$(R,k,l,X0,I,O)}else throw Error(`[query-builder] Unsupported relationship type '${P}' for whereDoesntHave`);K=W`${D()} WHERE NOT EXISTS (${W([b])})`;try{w("WHERE",`NOT EXISTS (${b})`)}catch{}return this},has(O){if(!Z)return this;let I=String(G),R=Z.relations?.[I];if(!R)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(R).find(([b,l])=>l&&typeof l==="object"&&(O in l));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,P]=M,S=P[O],A=typeof S==="string"?S:S?.model||S?.target||S,d=Z.modelToTable[A]||A,k;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";k=UX(I,d,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[d]??"id";k=h$(I,d,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",l=Z.primaryKeys[d]??"id";k=v$(I,d,b,l,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for has`);K=W`${D()} WHERE EXISTS (${W([k])})`;try{w("WHERE",`EXISTS (${k})`)}catch{}return this},doesntHave(O){if(!Z)return this;let I=String(G),R=Z.relations?.[I];if(!R)throw Error(`[query-builder] No relationships defined for table '${I}'`);let M=Object.entries(R).find(([b,l])=>l&&typeof l==="object"&&(O in l));if(!M)throw Error(`[query-builder] Relationship '${O}' not found on table '${I}'`);let[C,P]=M,S=P[O],A=typeof S==="string"?S:S?.model||S?.target||S,d=Z.modelToTable[A]||A,k;if(C==="hasMany"||C==="hasOne"){let b=Z.primaryKeys[I]??"id";k=UX(I,d,b)}else if(C==="belongsTo"){let b=Z.primaryKeys[d]??"id";k=h$(I,d,b)}else if(C==="belongsToMany"){let b=Z.primaryKeys[I]??"id",l=Z.primaryKeys[d]??"id";k=v$(I,d,b,l,void 0,O)}else throw Error(`[query-builder] Unsupported relationship type '${C}' for doesntHave`);K=W`${D()} WHERE NOT EXISTS (${W([k])})`;try{w("WHERE",`NOT EXISTS (${k})`)}catch{}return this},withCount(...O){if(!Z||!O||O.length===0)return this;let I=String(G);for(let R of O){let M=Z.relations?.[I];if(!M)continue;let C=Object.entries(M).find(([w0,r])=>r&&typeof r==="object"&&(R in r));if(!C)continue;let[P,S]=C,A=S[R],d=typeof A==="string"?A:A?.model||A?.target||A,k=Z.modelToTable[d]||d,b=Z.primaryKeys[I]??"id",l;if(P==="hasMany"||P==="hasOne")l=S7(I,k,b);else if(P==="belongsToMany")l=A7(I,k,b,R);else continue;let X0=`${R}_count`;u9(`${l} AS ${X0}`)}return this},withSum(O,I){return b$("SUM",O,I),this},withAvg(O,I){return b$("AVG",O,I),this},withMax(O,I){return b$("MAX",O,I),this},withMin(O,I){return b$("MIN",O,I),this},applyPivotColumns(){return I5(),this},withPivot(O,...I){if(!Z)return this;let R=String(G),M=o(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${R}'`);let C=I&&I.length>0?I:M.hasConfig?M.pivotColumns:[];if(C.length===0)return this;if(g.set(O,C),M.hasConfig)v.add(O);return I5(),this},wherePivot(O,I,R,M){if(!Z)return this;let C=o(O);if(!C)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(C.pivotTable,"wherePivot (pivot table)"),u(I,"wherePivot (column)"),o0(C);let P=M===void 0?"=":String(R),S=M===void 0?R:M,A=B.length+1,d=`${C.pivotTable}.${I} ${P} ${i(A)}`;a.push(d),B.push(S);let k=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${k} ${d}`,K=null,C.hasConfig)v.add(O);return this},wherePivotIn(O,I,R){if(!Z||!Array.isArray(R)||R.length===0)return this;let M=o(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(M.pivotTable,"wherePivotIn (pivot table)"),u(I,"wherePivotIn (column)"),o0(M);let C=h0(R.length,B.length+1),P=`${M.pivotTable}.${I} IN (${C})`;a.push(P),B.push(...R);let S=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${S} ${P}`,K=null,M.hasConfig)v.add(O);return this},wherePivotNotIn(O,I,R){if(!Z||!Array.isArray(R)||R.length===0)return this;let M=o(O);if(!M)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(M.pivotTable,"wherePivotNotIn (pivot table)"),u(I,"wherePivotNotIn (column)"),o0(M);let C=h0(R.length,B.length+1),P=`${M.pivotTable}.${I} NOT IN (${C})`;a.push(P),B.push(...R);let S=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${S} ${P}`,K=null,M.hasConfig)v.add(O);return this},wherePivotNull(O,I){if(!Z)return this;let R=o(O);if(!R)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(R.pivotTable,"wherePivotNull (pivot table)"),u(I,"wherePivotNull (column)"),o0(R);let M=`${R.pivotTable}.${I} IS NULL`;a.push(M);let C=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,K=null,R.hasConfig)v.add(O);return this},wherePivotNotNull(O,I){if(!Z)return this;let R=o(O);if(!R)throw Error(`[query-builder] Relationship '${O}' is not a belongsToMany relationship on table '${String(G)}'`);u(R.pivotTable,"wherePivotNotNull (pivot table)"),u(I,"wherePivotNotNull (column)"),o0(R);let M=`${R.pivotTable}.${I} IS NOT NULL`;a.push(M);let C=s.WHERE.test(F)?"AND":"WHERE";if(F=`${F} ${C} ${M}`,K=null,R.hasConfig)v.add(O);return this},where(O,I,R){let M=()=>s.WHERE.test(F)?"AND":"WHERE";if(typeof O==="string"&&I!==void 0){u(String(O),"where(column)"),v0(I,"where(operator)");let C=String(I).toLowerCase();if(C==="in"||C==="not in"){let S=Array.isArray(R)?R:[R],A=h0(S.length,B.length+1),d=`${String(O)} ${C.toUpperCase()} (${A})`;return a.push(d),B.push(...S),F=`${F} ${M()} ${d}`,K=null,this}let P=B.length+1;return a.push(`${String(O)} ${String(I)} ${i(P)}`),B.push(R),F=`${F} ${M()} ${String(O)} ${String(I)} ${i(P)}`,K=null,this}if(Array.isArray(O)){let[C,P,S]=O,A=String(C);u(A,"where(column)");let d=v0(P,"where(operator)");if(d==="in"||d==="not in"){let k=Array.isArray(S)?S:[S],b=h0(k.length,B.length+1);a.push(`${A} ${d.toUpperCase()} (${b})`),B.push(...k),F=`${F} ${M()} ${A} ${d.toUpperCase()} (${b})`,K=null}else{let k=B.length+1;a.push(`${A} ${d} ${i(k)}`),B.push(S),F=`${F} ${M()} ${A} ${d} ${i(k)}`,K=null}return this}if(O&&typeof O==="object"&&!d8(O)){let C=O,P=Object.keys(C),S=[];for(let A of P){u(A,"where(column)");let d=C[A];if(Array.isArray(d)){let k=h0(d.length,B.length+1);S.push(`${A} IN (${k})`),a.push(`${A} IN (${k})`),B.push(...d)}else{let k=B.length+1;S.push(`${A} = ${i(k)}`),a.push(`${A} = ${i(k)}`),B.push(d)}}if(S.length>0)F=`${F} ${M()} ${S.join(" AND ")}`,K=null;return this}if(d8(O))return a.push(O.raw),F=`${F} ${M()} ${O.raw}`,K=null,this;return this},whereNull(O){u(String(O),"whereNull(column)");let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NULL`,K=null,this},whereNotNull(O){u(String(O),"whereNotNull(column)");let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} ${String(O)} IS NOT NULL`,K=null,this},whereBetween(O,I,R){u(String(O),"whereBetween(column)");let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1;return F=`${F} ${M} ${String(O)} BETWEEN ${i(C)} AND ${i(C+1)}`,B.push(I,R),K=null,this},whereExists(O){let I=s.WHERE.test(F)?"AND":"WHERE";return F=`${F} ${I} EXISTS (${O.toSQL()})`,K=null,this},whereJsonContains(O,I){u(String(O),"whereJsonContains(column)");let R=s.WHERE.test(F)?"AND":"WHERE",M=f.dialect,C=B.length+1;if(M==="postgres"){if(f.sql?.jsonContainsMode==="function")F+=` ${R} jsonb_contains(${O}, ${i(C)})`;else F+=` ${R} ${O} @> ${i(C)}`;B.push(JSON.stringify(I))}else if(J0(M))F+=` ${R} JSON_CONTAINS(${O}, ${i(C)})`,B.push(JSON.stringify(I));else if(Array.isArray(I)){let P=I.map((S,A)=>`EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${i(C+A)})`);F+=` ${R} (${P.join(" AND ")})`;for(let S of I)B.push(S)}else if(I!==null&&typeof I==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else F+=` ${R} EXISTS (SELECT 1 FROM json_each(${O}) WHERE json_each.value = ${i(C)})`,B.push(I);return K=null,this},whereJsonPath(O,I,R){if(v0(I,"whereJsonPath(op)"),typeof O!=="string"||O.length===0||O.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof O==="string"?`'${O.slice(0,32)}...'`:typeof O}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(O))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${O}' \u2014 contains characters outside the allowed JSON-path set`);let M=f.dialect,C=s.WHERE.test(F)?"AND":"WHERE",P=B.length+1;if(M==="postgres")F+=` ${C} ${O} ${I} ${i(P)}`;else if(J0(M))F+=` ${C} JSON_EXTRACT(${O}) ${I} ${i(P)}`;else F+=` ${C} json_extract(${O}) ${I} ${i(P)}`;return B.push(R),K=null,this},whereLike(O,I,R=!1){let M=i(B.length+1);return w("WHERE",`${R?String(O):`LOWER(${String(O)})`} LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},whereILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("WHERE",`${String(O)} ILIKE ${R}`);else w("WHERE",`LOWER(${String(O)}) LIKE LOWER(${R})`);return B.push(I),K=null,this},orWhereLike(O,I,R=!1){let M=i(B.length+1);return w("OR",`${R?String(O):`LOWER(${String(O)})`} LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},orWhereILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("OR",`${String(O)} ILIKE ${R}`);else w("OR",`LOWER(${String(O)}) LIKE LOWER(${R})`);return B.push(I),K=null,this},whereNotLike(O,I,R=!1){let M=i(B.length+1);return w("WHERE",`${R?String(O):`LOWER(${String(O)})`} NOT LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},whereNotILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("WHERE",`${String(O)} NOT ILIKE ${R}`);else w("WHERE",`LOWER(${String(O)}) NOT LIKE LOWER(${R})`);return B.push(I),K=null,this},orWhereNotLike(O,I,R=!1){let M=i(B.length+1);return w("OR",`${R?String(O):`LOWER(${String(O)})`} NOT LIKE ${R?M:`LOWER(${M})`}`),B.push(I),K=null,this},orWhereNotILike(O,I){let R=i(B.length+1);if(f.dialect==="postgres")w("OR",`${String(O)} NOT ILIKE ${R}`);else w("OR",`LOWER(${String(O)}) NOT LIKE LOWER(${R})`);return B.push(I),K=null,this},whereAny(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1,P=O.map((S,A)=>`${S} ${I} ${i(C+A)}`);F+=` ${M} (${P.join(" OR ")})`;for(let S=0;S<O.length;S++)B.push(R);return K=null,this},whereAll(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1,P=O.map((S,A)=>`${S} ${I} ${i(C+A)}`);F+=` ${M} (${P.join(" AND ")})`;for(let S=0;S<O.length;S++)B.push(R);return K=null,this},whereNone(O,I,R){if(O.length===0)return this;let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1,P=O.map((S,A)=>`${S} ${I} ${i(C+A)}`);F+=` ${M} NOT (${P.join(" OR ")})`;for(let S=0;S<O.length;S++)B.push(R);return K=null,this},whereNotBetween(O,I,R){u(String(O),"whereNotBetween(column)");let M=s.WHERE.test(F)?"AND":"WHERE",C=B.length+1;return F+=` ${M} ${O} NOT BETWEEN ${i(C)} AND ${i(C+1)}`,B.push(I,R),K=null,this},whereDate(O,I,R){u(O,"whereDate(column)");let M=R instanceof Date?R.toISOString():typeof R==="string"?R:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof R}`)})(),C=s.WHERE.test(F)?"AND":"WHERE",P=B.length+1;return F+=` ${C} ${O} ${I} ${i(P)}`,B.push(M),K=null,this},whereRaw(O){let I=KX(O,"whereRaw(fragment)"),R=s.WHERE.test(F)?"AND":"WHERE";return F+=` ${R} ${I}`,K=null,this},whereColumn(O,I,R){u(O,"whereColumn(left)"),u(R,"whereColumn(right)");let M=s.WHERE.test(F)?"AND":"WHERE";return F+=` ${M} ${O} ${I} ${R}`,K=null,this},orWhereColumn(O,I,R){return u(O,"orWhereColumn(left)"),u(R,"orWhereColumn(right)"),F+=` OR ${O} ${I} ${R}`,K=null,this},whereIn(O,I){u(String(O),"whereIn(column)");let R=s.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=h0(I.length,B.length+1);F+=` ${R} ${O} IN (${M})`,B.push(...I)}else F+=` ${R} ${O} IN (${String(I.toSQL())})`;return K=null,this},orWhereIn(O,I){if(u(String(O),"orWhereIn(column)"),Array.isArray(I)){let R=h0(I.length,B.length+1);F+=` OR ${O} IN (${R})`,B.push(...I)}else F+=` OR ${O} IN (${String(I.toSQL())})`;return K=null,this},whereNotIn(O,I){u(String(O),"whereNotIn(column)");let R=s.WHERE.test(F)?"AND":"WHERE";if(Array.isArray(I)){let M=h0(I.length,B.length+1);F+=` ${R} ${O} NOT IN (${M})`,B.push(...I)}else F+=` ${R} ${O} NOT IN (${String(I.toSQL())})`;return K=null,this},orWhereNotIn(O,I){if(u(String(O),"orWhereNotIn(column)"),Array.isArray(I)){let R=h0(I.length,B.length+1);F+=` OR ${O} NOT IN (${R})`,B.push(...I)}else F+=` OR ${O} NOT IN (${String(I.toSQL())})`;return K=null,this},whereNested(O){let I=s.WHERE.test(F)?"AND":"WHERE",R=O.toSQL?String(O.toSQL()):String(O);return F+=` ${I} (${R})`,K=null,this},orWhereNested(O){let I=O.toSQL?String(O.toSQL()):String(O);return F+=` OR (${I})`,K=null,this},andWhere(O,I,R){if(typeof O==="string"&&I!==void 0){u(String(O),"andWhere(column)"),v0(I,"andWhere(operator)");let M=B.length+1;return a.push(`${String(O)} ${String(I)} ${i(M)}`),B.push(R),F=`${F} AND ${String(O)} ${String(I)} ${i(M)}`,K=null,this}if(Array.isArray(O)){let[M,C,P]=O,S=String(M);u(S,"andWhere(column)");let A=v0(C,"andWhere(operator)");if(A==="in"||A==="not in"){let d=Array.isArray(P)?P:[P],k=h0(d.length,B.length+1);a.push(`${S} ${A.toUpperCase()} (${k})`),B.push(...d),F=`${F} AND ${S} ${A.toUpperCase()} (${k})`,K=null}else{let d=B.length+1;a.push(`${S} ${A} ${i(d)}`),B.push(P),F=`${F} AND ${S} ${A} ${i(d)}`,K=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let P of M){let S=O[P];if(Array.isArray(S)){let A=h0(S.length,B.length+1);C.push(`${P} IN (${A})`),a.push(`${P} IN (${A})`),B.push(...S)}else{let A=B.length+1;C.push(`${P} = ${i(A)}`),a.push(`${P} = ${i(A)}`),B.push(S)}}if(C.length>0)F=`${F} AND ${C.join(" AND ")}`,K=null;return this}if(O&&typeof O.raw<"u")return a.push(O.raw),F=`${F} AND ${O.raw}`,K=null,this;return this},orWhere(O,I,R){if(typeof O==="string"&&I!==void 0){u(String(O),"orWhere(column)"),v0(I,"orWhere(operator)");let M=B.length+1;return a.push(`OR ${String(O)} ${String(I)} ${i(M)}`),B.push(R),F=`${F} OR ${String(O)} ${String(I)} ${i(M)}`,K=null,this}if(Array.isArray(O)){let[M,C,P]=O,S=String(M);u(S,"orWhere(column)");let A=v0(C,"orWhere(operator)");if(A==="in"||A==="not in"){let d=Array.isArray(P)?P:[P],k=h0(d.length,B.length+1);a.push(`OR ${S} ${A.toUpperCase()} (${k})`),B.push(...d),F=`${F} OR ${S} ${A.toUpperCase()} (${k})`,K=null}else{let d=B.length+1;a.push(`OR ${S} ${A} ${i(d)}`),B.push(P),F=`${F} OR ${S} ${A} ${i(d)}`,K=null}return this}if(O&&typeof O==="object"&&!("raw"in O)){let M=Object.keys(O),C=[];for(let P of M){let S=O[P];if(Array.isArray(S)){let A=h0(S.length,B.length+1);C.push(`${P} IN (${A})`),a.push(`OR ${P} IN (${A})`),B.push(...S)}else{let A=B.length+1;C.push(`${P} = ${i(A)}`),a.push(`OR ${P} = ${i(A)}`),B.push(S)}}if(C.length>0)F=`${F} OR ${C.join(" AND ")}`,K=null;return this}if(O&&typeof O.raw<"u")return a.push(`OR ${O.raw}`),F=`${F} OR ${O.raw}`,K=null,this;return this},orderBy(O,I="asc"){let R=I==="asc"?"ASC":"DESC";return F=s.ORDER_BY.test(F)?`${F}, ${O} ${R}`:`${F} ORDER BY ${O} ${R}`,K=null,this},orderByDesc(O){return F=s.ORDER_BY.test(F)?`${F}, ${O} DESC`:`${F} ORDER BY ${O} DESC`,K=null,this},inRandomOrder(){let O=f.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return F=s.ORDER_BY.test(F)?`${F}, ${O}`:`${F} ORDER BY ${O}`,K=null,this},reorder(O,I="asc"){return F=F.replace(/ORDER BY[\s\S]*$/i,""),F+=` ORDER BY ${O} ${I==="asc"?"ASC":"DESC"}`,K=null,this},latest(O){let I=O??f.timestamps.defaultOrderColumn;return F=s.ORDER_BY.test(F)?`${F}, ${I} DESC`:`${F} ORDER BY ${I} DESC`,K=null,this},oldest(O){let I=O??f.timestamps.defaultOrderColumn;return F=s.ORDER_BY.test(F)?`${F}, ${I} ASC`:`${F} ORDER BY ${I} ASC`,K=null,this},limit(O){if(!Number.isFinite(O)||O<0||!Number.isInteger(O))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${O}`);return F=s.LIMIT.test(F)?F.replace(s.LIMIT,` LIMIT ${O}`):`${F} LIMIT ${O}`,K=null,this},offset(O){if(!Number.isFinite(O)||O<0||!Number.isInteger(O))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${O}`);return F=s.OFFSET.test(F)?F.replace(s.OFFSET,` OFFSET ${O}`):`${F} OFFSET ${O}`,K=null,this},join(O,I,R,M){return u(O,"join(table)"),Q9(I,"join(onLeft)"),Q9(M,"join(onRight)"),v0(R,"join(operator)"),N(`JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},joinSub(O,I,R,M,C){return u(I,"joinSub(alias)"),Q9(R,"joinSub(onLeft)"),Q9(C,"joinSub(onRight)"),v0(M,"joinSub(operator)"),N(`JOIN (${String(O.toSQL())}) AS ${I} ON ${R} ${M} ${C}`),q.add(I),this},innerJoin(O,I,R,M){return u(O,"innerJoin(table)"),Q9(I,"innerJoin(onLeft)"),Q9(M,"innerJoin(onRight)"),v0(R,"innerJoin(operator)"),N(`INNER JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},leftJoin(O,I,R,M){return u(O,"leftJoin(table)"),Q9(I,"leftJoin(onLeft)"),Q9(M,"leftJoin(onRight)"),v0(R,"leftJoin(operator)"),N(`LEFT JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},leftJoinSub(O,I,R,M,C){return u(I,"leftJoinSub(alias)"),Q9(R,"leftJoinSub(onLeft)"),Q9(C,"leftJoinSub(onRight)"),v0(M,"leftJoinSub(operator)"),N(`LEFT JOIN (${String(O.toSQL())}) AS ${I} ON ${R} ${M} ${C}`),q.add(I),this},rightJoin(O,I,R,M){return u(O,"rightJoin(table)"),Q9(I,"rightJoin(onLeft)"),Q9(M,"rightJoin(onRight)"),v0(R,"rightJoin(operator)"),N(`RIGHT JOIN ${O} ON ${I} ${R} ${M}`),q.add(O),this},crossJoin(O){return u(O,"crossJoin(table)"),N(`CROSS JOIN ${O}`),q.add(O),this},crossJoinSub(O,I){return u(I,"crossJoinSub(alias)"),N(`CROSS JOIN (${String(O.toSQL())}) AS ${I}`),q.add(I),this},selectAllRelations(){if(!Y)return this;let O=String(G),I=Object.keys(Y[O]?.columns??{}),R=[];if(I.length>0)R.push(W`${W(O)}.*`);for(let M of q){let C=Object.keys(Y[M]?.columns??{});for(let P of C){let S=f.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${P}`.replace(/_([a-z])/g,(A,d)=>d.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${P}`:`${M}_${P}`;R.push(W`${W(`${M}.${P}`)} AS ${W(S)}`)}}if(R.length>0){let M=I.length>0?`${O}.*`:"",C=[];for(let A of q){let d=Object.keys(Y[A]?.columns??{});for(let k of d){let b=f.aliasing.relationColumnAliasFormat==="camelCase"?`${A}_${k}`.replace(/_([a-z])/g,(l,X0)=>X0.toUpperCase()):f.aliasing.relationColumnAliasFormat==="table.dot.column"?`${A}.${k}`:`${A}_${k}`;C.push(`${A}.${k} AS ${b}`)}}let P=[M,...C].filter(Boolean).join(", "),S=F.indexOf(" FROM ");if(S!==-1)F=`SELECT ${P}${F.substring(S)}`;else F=`SELECT ${P} FROM ${O}`;K=null}return this},groupBy(...O){if(O.length)F=s.GROUP_BY.test(F)?`${F}, ${O.join(", ")}`:`${F} GROUP BY ${O.join(", ")}`,K=null;return this},groupByRaw(O){let I=KX(O,"groupByRaw(fragment)");return F=s.GROUP_BY.test(F)?`${F}, ${I}`:`${F} GROUP BY ${I}`,K=null,this},having(O){let I=/\bHAVING\b/i.test(F)?"AND":"HAVING";if(Array.isArray(O)){let R=B.length+1;F=`${F} ${I} ${O[0]} ${O[1]} ${i(R)}`,B.push(O[2]),K=null}else if(O&&typeof O==="object"&&!("raw"in O)){let R=Object.keys(O),M=R.length;if(M){let C=B.length,P=Array.from({length:M});for(let S=0;S<M;S++){let A=R[S];P[S]=`${A} = ${i(C+S+1)}`,B.push(O[A])}F=`${F} ${I} ${P.join(" AND ")}`,K=null}}else if(O&&typeof O.raw<"u")F+=` ${I} ${O.raw}`,K=null;return this},havingRaw(O){let I=KX(O,"havingRaw(fragment)"),R=/\bHAVING\b/i.test(F)?"AND":"HAVING";return F+=` ${R} ${I}`,K=null,this},orderByRaw(O){let I=KX(O,"orderByRaw(fragment)");return F=s.ORDER_BY.test(F)?`${F}, ${I}`:`${F} ORDER BY ${I}`,K=null,this},union(O){return T("UNION",O),this},unionAll(O){return T("UNION ALL",O),this},intersect(O){return T("INTERSECT",O),this},intersectAll(O){return T("INTERSECT ALL",O),this},except(O){return T("EXCEPT",O),this},exceptAll(O){return T("EXCEPT ALL",O),this},forPage(O,I){let R=Math.max(1,Math.floor(O)),M=Math.max(1,Math.floor(I));return F+=` LIMIT ${M} OFFSET ${(R-1)*M}`,K=null,this},toSQL(){let O=X8(F);return{sql:O,toString:()=>O,execute:()=>D().execute(),values:()=>D().values(),raw:()=>D().raw()}},async value(O){let I=W`${D()} LIMIT 1`,R=await j(I,"select",{signal:x,timeoutMs:H}),[M]=R;return M?.[O]},async pluck(O,I){let R=await j(D(),"select",{signal:x,timeoutMs:H});if(I){let M={};for(let C of R){let P=String(C?.[I]);if(Object.prototype.hasOwnProperty.call(M,P))throw Error(`[query-builder] pluck(${O}, ${I}): duplicate key '${P}' \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.`);M[P]=C?.[O]}return M}return R.map((M)=>M?.[O])},async exists(){let O=W`SELECT EXISTS (${D()}) as e`,I=await j(O,"select",{signal:x,timeoutMs:H}),[R]=I;return Boolean(R?.e)},async doesntExist(){return!await this.exists()},async paginate(O,I=1,R={}){if(!Number.isFinite(O)||O<=0||!Number.isInteger(O))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${O}`);if(!Number.isFinite(I)||I<1||!Number.isInteger(I))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${I}`);if(R.tx){let l=X8(F),X0=[...B],w0=await R.tx.unsafe(`SELECT COUNT(*) as c FROM (${l}) as sub`,X0),r=Number(w0?.[0]?.c??0),T0=Math.max(1,Math.ceil(r/O)),X9=Math.max(1,Math.min(I,T0)),_9=(X9-1)*O;return{data:await R.tx.unsafe(`${l} LIMIT ${O} OFFSET ${_9}`,X0),meta:{perPage:O,page:X9,total:r,lastPage:T0}}}let M=W`SELECT COUNT(*) as c FROM (${D()}) as sub`,C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C,S=Number(P?.c??0),A=Math.max(1,Math.ceil(S/O)),d=Math.max(1,Math.min(I,A)),k=(d-1)*O;return{data:await j(W`${D()} LIMIT ${O} OFFSET ${k}`,"select",{signal:x,timeoutMs:H}),meta:{perPage:O,page:d,total:S,lastPage:A}}},async simplePaginate(O,I=1){let R=Math.max(1,I),M=(R-1)*O,C=await j(W`${D()} LIMIT ${O+1} OFFSET ${M}`,"select",{signal:x,timeoutMs:H}),P=C.length>O;return{data:P?C.slice(0,O):C,meta:{perPage:O,page:R,hasMore:P}}},async cursorPaginate(O,I,R="id",M="asc"){let C=D();if(I!==void 0&&I!==null)if(Array.isArray(R)){let l=R.map((T0)=>W(String(T0))),X0=M==="asc"?W`>`:W`<`,w0=W`(${W(l)})`,r=W`(${W(I)})`;C=W`${C} WHERE ${w0} ${X0} ${r}`}else C=M==="asc"?W`${C} WHERE ${W(String(R))} > ${I}`:W`${C} WHERE ${W(String(R))} < ${I}`;if(Array.isArray(R)){let X0=R.map((w0)=>W`${W(String(w0))} ${M==="asc"?W`ASC`:W`DESC`}`).reduce((w0,r,T0)=>T0===0?r:W`${w0}, ${r}`);C=W`${C} ORDER BY ${X0} LIMIT ${O+1}`}else C=W`${C} ORDER BY ${W(String(R))} ${M==="asc"?W`ASC`:W`DESC`} LIMIT ${O+1}`;let P=await j(C,"select",{signal:x,timeoutMs:H}),S=P.length>O,A=P.slice(0,O),d=A[A.length-1],k=S&&d?Array.isArray(R)?R.map((l)=>d[l]):d[R]:null,b=A.length?Array.isArray(R)?R.map((l)=>A[0]?.[l]):A[0]?.[R]:null;return{data:A,meta:{perPage:O,nextCursor:k??null,prevCursor:b}}},async chunk(O,I){let R=1;while(!0){let{data:M,meta:C}=await this.paginate(O,R);if(M.length===0)break;if(await I(M),R>=C.lastPage)break;R+=1}},async chunkById(O,I="id",R){let M;while(!0){let{data:C,meta:P}=await this.cursorPaginate(O,M,I,"asc");if(C.length===0)break;if(R)await R(C);if(M=P.nextCursor,!M)break}},async eachById(O,I="id",R){await this.chunkById(O,I,async(M)=>{for(let C of M)await R?.(C)})},withTimeout(O){return H=Math.max(1,Math.floor(O)),this},abort(O){return x=O,this},withTrashed(){return h=!0,c=!1,this},onlyTrashed(){h=!0,c=!0;let O=f.softDeletes?.column||"deleted_at",I=(C,P)=>{let S=C.toUpperCase(),A=0;for(let d=0;d<C.length;d++){let k=C[d];if(k==="(")A++;else if(k===")")A--;else if(A===0&&S.substring(d,d+5)==="WHERE"&&(d===0||/\s/.test(C[d-1]??""))&&/\s/.test(C[d+5]??""))return`${C.substring(0,d)}WHERE ${P} AND ${C.substring(d+6)}`}return`${C} WHERE ${P}`},R=`${G}.${O} IS NOT NULL`;F=I(F,R);let M=String(D());return K=W([I(M,R)]),this},scope(O,I){let R=String(G),C=Z?.scopes?.[R]?.[O];if(C)return C(this,I);return this},when(O,I,R){if(O)return I(this);if(R)return R(this);return this},tap(O){return O(this),this},dump(){return console.log(String(D())),this},dd(){throw console.log(String(D())),Error("Dump and Die")},cache(O=60000){return n=O,y=!0,this},async explain(){let O=W`EXPLAIN ${D()}`;return await j(O,"select",{signal:x,timeoutMs:H})},simple(){return D().simple()},toText(){return F},async get(){let O=f.hooks,I=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan||uX(O));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!I){let P=$._prepareStatement;if(P){let S=P(F);return M0(B.length>0?S.all(...B):S.all())}}if(K=B.length>0?$.unsafe(F,B):$.unsafe(F),!f.softDeletes?.enabled&&!y&&!H&&!x&&!I){let P=D()._stmt,S=D()._params;if(P)return M0(S&&S.length>0?P.all(...S):P.all());return M0(await D().execute())}if(!f.softDeletes?.enabled&&!y&&!H&&!x)return M0(await j(D(),"select"));let R=D();if(f.softDeletes?.enabled&&f.softDeletes.defaultFilter&&!h){let P=f.softDeletes.column,S=String(G);if((Y?Boolean(Y[S]?.columns?.[P]):!0)&&!s.DELETED_AT.test(F))R=W`${D()} WHERE ${W(String(P))} IS ${c?W`NOT NULL`:W`NULL`}`,w("WHERE",`${String(P)} IS ${c?"NOT ":""}NULL`)}let M=y?`${String(R)}\x00${JSON.stringify(B)}`:"";if(y){let P=S$.get(M);if(P)return P}let C=await j(R,"select",{signal:x,timeoutMs:H});if(y)S$.set(M,C,n);return M0(C)},async executeTakeFirst(){let O=await j(D(),"select",{signal:x,timeoutMs:H});return D0(Array.isArray(O)?O[0]:O)},async executeTakeFirstOrThrow(){let O=await this.executeTakeFirst();if(!O)throw Error("Record not found");return O},async first(){let O=f.hooks,I=O&&(O.onQueryStart||O.onQueryEnd||O.onQueryError||O.startSpan||uX(O));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!I){let C=$._prepareStatement;if(C){let P=F.includes(" LIMIT ")?F:`${F} LIMIT 1`,S=C(P),A=B.length>0?S.all(...B):S.all();return D0(A[0])}}let R=await j(W`${D()} LIMIT 1`,"select",{signal:x,timeoutMs:H}),[M]=R;return D0(M)},async firstOrFail(){let O=await this.first();if(!O)throw Error("Record not found");return O},async find(O){let I=Z?.primaryKeys[String(G)]??"id",R=await j(W`${D()} WHERE ${W(I)} = ${O} LIMIT 1`,"select",{signal:x,timeoutMs:H}),[M]=R;return M},async findOrFail(O){let I=await this.find(O);if(!I)throw Error("Record not found");return I},async findMany(O){let I=Z?.primaryKeys[String(G)]??"id";return await j(W`${D()} WHERE ${W(String(I))} IN ${W(O)}`,"select",{signal:x,timeoutMs:H})},async*lazy(){let O,I=Z?.primaryKeys[String(G)]??"id";while(!0){let M=await(O==null?W`${D()} ORDER BY ${W(String(I))} ASC LIMIT 100`:W`${D()} WHERE ${W(String(I))} > ${O} ORDER BY ${W(String(I))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let C of M)yield C;if(O=M[M.length-1]?.[I],O==null)break}},async*lazyById(){let O=Z?.primaryKeys[String(G)]??"id",I;while(!0){let M=await(I==null?W`${D()} ORDER BY ${W(String(O))} ASC LIMIT 100`:W`${D()} WHERE ${W(String(O))} > ${I} ORDER BY ${W(String(O))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let C of M)yield C;if(I=M[M.length-1]?.[O],I==null)break}},pipe(O){return O(this)},async count(){let O=F.indexOf(" FROM "),I=/ GROUP BY /i.test(F),R;if(I)R=`SELECT COUNT(*) as c FROM (${F}) AS _bqb_count_sub`;else if(O!==-1)R=`SELECT COUNT(*) as c${F.substring(O)}`;else R=`SELECT COUNT(*) as c FROM ${G}`;let M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||uX(M));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!C){let d=$._prepareStatement;if(d){let k=d(R),b=B.length>0?k.all(...B):k.all();return Number(b[0]?.c??0)}}let P=B.length>0?$.unsafe(R,B):$.unsafe(R),S=await j(P,"select",{signal:x,timeoutMs:H}),[A]=S;return Number(A?.c??0)},async avg(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT AVG(${O}) as a${F.substring(I)}`:`SELECT AVG(${O}) as a FROM ${G}`,M=f.hooks,C=M&&(M.onQueryStart||M.onQueryEnd||M.onQueryError||M.startSpan||uX(M));if(!f.softDeletes?.enabled&&!y&&!H&&!x&&!C){let d=$._prepareStatement;if(d){let k=d(R),b=B.length>0?k.all(...B):k.all();return Number(b[0]?.a??0)}}let P=B.length>0?$.unsafe(R,B):$.unsafe(R),S=await j(P,"select",{signal:x,timeoutMs:H}),[A]=S;return Number(A?.a??0)},async sum(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT SUM(${O}) as s${F.substring(I)}`:`SELECT SUM(${O}) as s FROM ${G}`,M=B.length>0?$.unsafe(R,B):$.unsafe(R),C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C;return Number(P?.s??0)},async max(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT MAX(${O}) as m${F.substring(I)}`:`SELECT MAX(${O}) as m FROM ${G}`,M=B.length>0?$.unsafe(R,B):$.unsafe(R),C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C;return P?.m},async min(O){let I=F.indexOf(" FROM "),R=I!==-1?`SELECT MIN(${O}) as m${F.substring(I)}`:`SELECT MIN(${O}) as m FROM ${G}`,M=B.length>0?$.unsafe(R,B):$.unsafe(R),C=await j(M,"select",{signal:x,timeoutMs:H}),[P]=C;return P?.m},lockForUpdate(){return F+=" FOR UPDATE",K=null,this},sharedLock(){let O=f.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return F+=` ${O}`,K=null,this},withCTE(O,I){return u(O,"withCTE(name)"),F=`WITH ${O} AS (${String(I.toSQL())}) ${F}`,K=null,this},withRecursive(O,I){return u(O,"withRecursive(name)"),F=`WITH RECURSIVE ${O} AS (${String(I.toSQL())}) ${F}`,K=null,this},execute(){return j(D(),"select",{signal:x,timeoutMs:H})},values(){return D().values()},toParams(){return[...B]},__rawState(){return{sql:X8(F),params:[...B]}},raw(){return D().raw()},get rows(){return},get row(){return},cancel(){try{D().cancel()}catch{}}},{get(O,I,R){let M=Reflect.get(O,I,R);if(M!==void 0)return M;if(typeof I==="string"&&(I.startsWith("where")||I.startsWith("orWhere")||I.startsWith("andWhere"))){let C=I.startsWith("orWhere"),P=I.startsWith("andWhere"),S=`${String(G)}|${I}`,A=U.get(S);if(A===void 0){let k=I.replace(/^(?:or|and)?where/i,"");if(!k)U.set(S,""),A="";else{let b=k.charAt(0).toLowerCase()+k.slice(1),l=k.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),X0=Y?Object.keys(Y[String(G)]?.columns??{}):[];A=[l,b,b.toLowerCase()].find((w0)=>X0.includes(w0))??l,U.set(S,A)}}if(A==="")return()=>R;let d=A;return(k)=>{let b=Array.isArray(k)?W`${W(d)} IN ${W(k)}`:W`${W(d)} = ${k}`;if(K=C?W`${D()} OR ${b}`:P?W`${D()} AND ${b}`:W`${D()} WHERE ${b}`,Array.isArray(k)){let l=h0(k.length,B.length+1);w(C?"OR":P?"AND":"WHERE",`${d} IN (${l})`),B.push(...k)}else{let l=i(B.length+1);w(C?"OR":P?"AND":"WHERE",`${d} = ${l}`),B.push(k)}return R}}return Reflect.get(O,I,R)}})}return{configure(G){return Object.assign(f,G),this},id(G){if(!s.IDENTIFIER.test(G))throw Error(`[query-builder] Invalid identifier: '${G}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(String(G))},ids(...G){for(let J of G)if(!s.IDENTIFIER.test(J))throw Error(`[query-builder] Invalid identifier: '${J}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return $(G)},select(G,...J){return V(G,J)},selectFrom(G){return V(G)},selectFromSub(G,J){function W(H){return()=>{throw Error(`[query-builder] selectFromSub(...).${H}() is not supported. Apply ${H}() 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.")}}u(String(J),"selectFromSub(alias)");let F=typeof G.__rawState==="function"?G.__rawState():null,K=G.toSQL(),D=F?.sql??(typeof K==="string"?K:K?.sql??String(K)),w=F?.params??(Array.isArray(K?.values)?K.values:[]),T=`SELECT * FROM (${D}) AS ${String(J)}`,N=(H,x,h,c,y,g,v)=>{let n=!h?"WHERE":v==="WHERE"?"AND":v,p=[...x],o=(M0,o0,a)=>{u(M0,"selectFromSub where(column)");let B=v0(o0,"selectFromSub where(operator)");if(B==="in"||B==="not in"){let e0=Array.isArray(a)?a:[a],UX=h0(e0.length,p.length+1);return p.push(...e0),`${M0} ${B.toUpperCase()} (${UX})`}let u9=i(p.length+1);return p.push(a),`${M0} ${B} ${u9}`},D0;if(typeof c==="string"&&y!==void 0)D0=o(c,y,g);else if(Array.isArray(c)&&c.length===3)D0=o(c[0],c[1],c[2]);else if(c&&typeof c==="object")D0=Object.entries(c).map(([M0,o0])=>o(M0,"=",o0)).join(" AND ");else return{text:H,params:x};return{text:`${H} ${n} ${D0}`,params:p}};function q(H,x,h=!1){let c=()=>x.length>0?$.unsafe(H,x):$.unsafe(H),y={distinct(){return q(H.replace(/^SELECT\s+/i,"SELECT DISTINCT "),x,h)},distinctOn(...g){let v=g.map(String).join(", ");return q(H.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${v}) `),x,h)},selectRaw(g){let v=KX(g,"selectFromSub.selectRaw(fragment)"),n=H.indexOf(" FROM "),p=n!==-1?`${H.slice(0,n)}, ${v}${H.slice(n)}`:`${H}, ${v}`;return q(p,x,h)},where(g,v,n){let p=N(H,x,h,g,v,n,"WHERE");return q(p.text,p.params,!0)},andWhere(g,v,n){let p=N(H,x,h,g,v,n,"AND");return q(p.text,p.params,!0)},orWhere(g,v,n){let p=N(H,x,h,g,v,n,"OR");return q(p.text,p.params,!0)},orderBy(g,v="asc"){u(String(g),"selectFromSub.orderBy(column)");let n=v==="asc"?"ASC":"DESC",p=s.ORDER_BY.test(H)?`${H}, ${g} ${n}`:`${H} ORDER BY ${g} ${n}`;return q(p,x,h)},limit(g){if(!Number.isInteger(g)||g<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${g}`);let v=s.LIMIT.test(H)?H.replace(s.LIMIT,` LIMIT ${g}`):`${H} LIMIT ${g}`;return q(v,x,h)},offset(g){if(!Number.isInteger(g)||g<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${g}`);let v=s.OFFSET.test(H)?H.replace(s.OFFSET,` OFFSET ${g}`):`${H} OFFSET ${g}`;return q(v,x,h)},toSQL(){return E(c(),H)},async execute(){return j(c(),"select")},async executeTakeFirst(){let g=await j(c(),"select");return Array.isArray(g)?g[0]:g},async executeTakeFirstOrThrow(){let g=await j(c(),"select"),v=Array.isArray(g)?g[0]:g;if(!v)throw Error("Record not found");return v},async get(){return j(c(),"select")},async first(){let g=await j(c(),"select");return Array.isArray(g)?g[0]:g},async firstOrFail(){let g=await j(c(),"select"),v=Array.isArray(g)?g[0]:g;if(!v)throw Error("No rows found");return v},async count(){let g=x.length>0?$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`,x):$.unsafe(`SELECT COUNT(*) as c FROM (${H}) as sub`),v=await j(g,"select");return Number(v?.[0]?.c??0)},async exists(){let g=x.length>0?$.unsafe(`SELECT EXISTS(${H}) as e`,x):$.unsafe(`SELECT EXISTS(${H}) as e`),v=await j(g,"select");return Boolean(v?.[0]?.e)},async doesntExist(){return!await y.exists()},values(){return c().values()},raw(){return c().raw()},cancel(){try{c().cancel()}catch{}},whereRaw:W("whereRaw"),whereColumn:W("whereColumn"),orWhereColumn:W("orWhereColumn"),whereIn:W("whereIn"),orWhereIn:W("orWhereIn"),whereNotIn:W("whereNotIn"),orWhereNotIn:W("orWhereNotIn"),whereLike:W("whereLike"),whereILike:W("whereILike"),orWhereLike:W("orWhereLike"),orWhereILike:W("orWhereILike"),whereNotLike:W("whereNotLike"),whereNotILike:W("whereNotILike"),orWhereNotLike:W("orWhereNotLike"),orWhereNotILike:W("orWhereNotILike"),whereAny:W("whereAny"),whereAll:W("whereAll"),whereNone:W("whereNone"),whereNested:W("whereNested"),orWhereNested:W("orWhereNested"),whereDate:W("whereDate"),whereBetween:W("whereBetween"),whereNotBetween:W("whereNotBetween"),whereJsonContains:W("whereJsonContains"),whereJsonPath:W("whereJsonPath"),whereNull:W("whereNull"),whereNotNull:W("whereNotNull"),whereExists:W("whereExists"),whereJsonDoesntContain:W("whereJsonDoesntContain"),whereJsonContainsKey:W("whereJsonContainsKey"),whereJsonDoesntContainKey:W("whereJsonDoesntContainKey"),whereJsonLength:W("whereJsonLength"),join:W("join"),joinSub:W("joinSub"),innerJoin:W("innerJoin"),leftJoin:W("leftJoin"),leftJoinSub:W("leftJoinSub"),rightJoin:W("rightJoin"),crossJoin:W("crossJoin"),crossJoinSub:W("crossJoinSub"),groupBy:W("groupBy"),groupByRaw:W("groupByRaw"),having:W("having"),havingRaw:W("havingRaw"),addSelect:W("addSelect"),select:W("select"),selectAll:W("selectAll"),orderByDesc:W("orderByDesc"),inRandomOrder:W("inRandomOrder"),reorder:W("reorder"),orderByRaw:W("orderByRaw"),union:W("union"),unionAll:W("unionAll"),forPage:W("forPage"),selectAllRelations:W("selectAllRelations"),with:W("with"),value:W("value"),pluck:W("pluck"),cursorPaginate:W("cursorPaginate"),paginate:W("paginate"),simplePaginate:W("simplePaginate"),chunk:W("chunk"),chunkById:W("chunkById"),eachById:W("eachById"),avg:W("avg"),sum:W("sum"),max:W("max"),min:W("min"),find:W("find"),findOrFail:W("findOrFail"),findMany:W("findMany"),latest:W("latest"),oldest:W("oldest"),lazy:W("lazy"),lazyById:W("lazyById"),pipe:(g)=>g(y),when:W("when"),tap:()=>y,dump:()=>y,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>c().simple(),toText:()=>H,toParams:()=>[...x],withTimeout:()=>y,abort:()=>y,lockForUpdate:()=>y,sharedLock:()=>y,withCTE:()=>y,withRecursive:()=>y,cache:()=>y,clone:()=>y,withTrashed:()=>y,onlyTrashed:()=>y,scope:()=>y,get rows(){return[]},get row(){return}};return y}return q(T,w)},insertInto(G){let J,W="",F=[],K=f.dialect==="postgres",D=K?(T)=>`"${String(T).replace(/"/g,'""')}"`:J0(f.dialect)?(T)=>`\`${String(T).replace(/`/g,"``")}\``:(T)=>`"${String(T).replace(/"/g,'""')}"`,w=K?(T)=>`$${T+1}`:(T)=>"?";return{values(T){let N=Array.isArray(T)?T:[T],q=N.length;if(q===0)return J=$.unsafe("SELECT 1"),this;let H=N[0],x=Object.keys(H),h=x.length,c=q*h;if(F.length=c,q===1)if(!K){let y=D(x[0]),g="?";F[0]=H[x[0]];for(let v=1;v<h;v++)y+=`,${D(x[v])}`,g+=",?",F[v]=H[x[v]];W=`INSERT INTO ${D(G)}(${y})VALUES(${g})`}else{let y=x.map((g)=>D(g)).join(",");W=`INSERT INTO ${D(G)}(${y})VALUES(`;for(let g=0;g<h;g++){if(g>0)W+=",";W+=w(g),F[g]=H[x[g]]}W+=")"}else{let y=x.map((v)=>D(v)).join(",");W=`INSERT INTO ${D(G)}(${y})VALUES`;let g=0;for(let v=0;v<q;v++){let n=N[v];if(v===0)W+="(";else W+="),(";for(let p=0;p<h;p++){if(p>0)W+=",";W+=w(g),F[g++]=n[x[p]]}}W+=")"}if(!$._prepareStatement)J=$.unsafe(W,F);return this},returning(...T){let N=`${W} RETURNING ${T.join(", ")}`,q=$.unsafe(N,F),H=async()=>{let x=await j(q,"insert");return Array.isArray(x)?x[0]:x};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>E(q,N),execute:()=>j(q,"insert"),get:()=>j(q,"insert"),first:H,executeTakeFirst:H,async firstOrFail(){let x=await H();if(!x)throw Error("Insert with RETURNING returned no rows");return x},async executeTakeFirstOrThrow(){let x=await H();if(!x)throw Error("Insert with RETURNING returned no rows");return x}}},toSQL(){if(!J)J=$.unsafe(W,F);return E(J,W)},execute(){let T=f.hooks;if(!(T&&(T.onQueryStart||T.onQueryEnd||T.onQueryError||T.startSpan||T.beforeCreate||T.afterCreate||uX(T)))){let q=$._prepareStatement;if(q){let H=q(W);return F.length>0?H.run(...F):H.run()}}if(!J)J=$.unsafe(W,F);return j(J,"insert")},async executeTakeFirst(){if(!J)J=$.unsafe(W,F);return await j(J,"insert")},async executeTakeFirstOrThrow(){if(!J)J=$.unsafe(W,F);let T=await j(J,"insert");if(!T)throw Error("Insert failed");return T},returningAll(){let T=`${W} RETURNING *`,N=$.unsafe(T,F),q=async()=>{let H=await j(N,"insert");return Array.isArray(H)?H[0]:H};return{toSQL:()=>E(N,T),execute:()=>j(N,"insert"),get:()=>j(N,"insert"),first:q,executeTakeFirst:q,async firstOrFail(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await q();if(!H)throw Error("Insert with RETURNING returned no rows");return H}}}}},updateTable(G){let J,W=[],F=(D)=>{let w=String(D);if(J0(f.dialect))return`\`${w.replace(/`/g,"``")}\``;return`"${w.replace(/"/g,'""')}"`},K=`UPDATE ${F(String(G))}`;return{set(D){let w=Object.keys(D),T=w.length,N=Array.from({length:T});for(let q=0;q<T;q++){let H=w[q];N[q]=`${F(H)} = ${i(q+1)}`,W.push(D[H])}return K=`${K} SET ${N.join(", ")}`,J=$.unsafe(K,W),this},where(D,w,T){let N=()=>s.WHERE.test(K)?"AND":"WHERE";if(typeof D==="string"&&w!==void 0){let q=W.length+1;return K=`${K} ${N()} ${F(D)} ${w} ${i(q)}`,W.push(T),J=$.unsafe(K,W),this}if(Array.isArray(D)){let[q,H,x]=D,h=W.length+1;return K=`${K} ${N()} ${F(String(q))} ${String(H)} ${i(h)}`,W.push(x),J=$.unsafe(K,W),this}if(D&&typeof D==="object"&&!("raw"in D)){let q=Object.keys(D),H=q.length,x=W.length,h=Array.from({length:H});for(let c=0;c<H;c++)h[c]=`${F(q[c])} = ${i(x+c+1)}`,W.push(D[q[c]]);K=`${K} ${N()} ${h.join(" AND ")}`,J=$.unsafe(K,W)}return this},returning(...D){let w=`${K} RETURNING ${D.join(", ")}`,T=W.length>0?$.unsafe(w,W):$.unsafe(w),N=async()=>{let H=await j(T,"update");return Array.isArray(H)?H[0]:H},q={where:()=>q,andWhere:()=>q,orWhere:()=>q,orderBy:()=>q,limit:()=>q,offset:()=>q,toSQL:()=>E(T,w),execute:()=>j(T,"update"),get:()=>j(T,"update"),first:N,executeTakeFirst:N,async firstOrFail(){let H=await N();if(!H)throw Error("Update with RETURNING returned no rows");return H},async executeTakeFirstOrThrow(){let H=await N();if(!H)throw Error("Update with RETURNING returned no rows");return H}};return q},toSQL(){if(!J)J=W.length>0?$.unsafe(K,W):$.unsafe(K);return E(J,K)},execute(){return j(J,"update")},async executeTakeFirst(){return{numUpdatedRows:await j(J,"update")}},async executeTakeFirstOrThrow(){let D=await j(J,"update");if(D===0)throw Error("No rows updated");return{numUpdatedRows:D}},returningAll(){let D=`${K} RETURNING *`,w=W.length>0?$.unsafe(D,W):$.unsafe(D);return{toSQL:()=>E(w,D),execute:()=>j(w,"update"),async executeTakeFirst(){let T=await j(w,"update");return Array.isArray(T)?T[0]:T},async executeTakeFirstOrThrow(){let T=await j(w,"update"),N=Array.isArray(T)?T[0]:T;if(!N)throw Error("Update with RETURNING failed");return N}}}}},deleteFrom(G){let J=(q)=>{let H=String(q);if(J0(f.dialect))return`\`${H.replace(/`/g,"``")}\``;return`"${H.replace(/"/g,'""')}"`},F=`DELETE FROM ${J(String(G))}`,K=null,D=[],w=null,T=()=>s.WHERE.test(F)?"AND":"WHERE",N=()=>{if(K===null)K=D.length>0?$.unsafe(F,D):$.unsafe(F);return K};return{where(q,H,x){if(w=q,typeof q==="string"&&H!==void 0){let h=D.length+1;return F+=` ${T()} ${J(q)} ${H} ${i(h)}`,D.push(x),K=null,this}if(Array.isArray(q)){let[h,c,y]=q,g=D.length+1;return F+=` ${T()} ${J(String(h))} ${c} ${i(g)}`,D.push(y),K=null,this}if(q&&typeof q==="object"&&!("raw"in q)){let h=Object.keys(q),c=[];for(let y of h){let g=D.length+1;c.push(`${J(y)} = ${i(g)}`),D.push(q[y])}return F+=` ${T()} ${c.join(" AND ")}`,K=null,this}return K=Q({},N(),q),this},returning(...q){let H=`${F} RETURNING ${q.join(", ")}`,x=D.length>0?$.unsafe(H,D):$.unsafe(H),h=async()=>{let y=await j(x,"delete");return Array.isArray(y)?y[0]:y},c={where:()=>c,andWhere:()=>c,orWhere:()=>c,orderBy:()=>c,limit:()=>c,offset:()=>c,toSQL:()=>E(x,H),execute:()=>j(x,"delete"),get:()=>j(x,"delete"),first:h,executeTakeFirst:h,async firstOrFail(){let y=await h();if(!y)throw Error("Delete with RETURNING returned no rows");return y},async executeTakeFirstOrThrow(){let y=await h();if(!y)throw Error("Delete with RETURNING returned no rows");return y}};return c},toSQL(){return E(N(),F)},async execute(){try{await f.hooks?.beforeDelete?.({table:String(G),where:w})}catch(H){throw H}let q=await j(N(),"delete");try{await f.hooks?.afterDelete?.({table:String(G),where:w,result:q})}catch{}return q},async executeTakeFirst(){return{numDeletedRows:await j(N(),"delete")}},async executeTakeFirstOrThrow(){let q=await j(N(),"delete");if(q===0)throw Error("No rows deleted");return{numDeletedRows:q}},returningAll(){let q=`${F} RETURNING *`,H=D.length>0?$.unsafe(q,D):$.unsafe(q);return{toSQL:()=>E(H,q),execute:()=>j(H,"delete"),async executeTakeFirst(){let x=await j(H,"delete");return Array.isArray(x)?x[0]:x},async executeTakeFirstOrThrow(){let x=await j(H,"delete"),h=Array.isArray(x)?x[0]:x;if(!h)throw Error("Delete with RETURNING failed");return h}}}}},table(G){let J=this;return{insert(W){return J.insertInto(G).values(W)},update(W){return J.updateTable(G).set(W)},delete(){return J.deleteFrom(G)},select(...W){if(W.length===0)return J.selectFrom(G);return J.select(G,...W)}}},sql:$,raw(G,...J){return $(G,...J)},simple(G,...J){return $(G,...J).simple()},async advisoryLock(G){if(f.dialect==="postgres"){let J=String(G),W=7;for(let D=0;D<J.length;D++)W=W*31+J.charCodeAt(D)|0;let F=typeof G==="number"?G:Math.abs(W),K=m`SELECT pg_advisory_lock(${F})`;await j(K,"raw");return}if(J0(f.dialect)){let J=`bqb:${String(G)}`,W=m`SELECT GET_LOCK(${J}, -1) AS ok`;await j(W,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(G){if(f.dialect==="postgres"){let J=String(G),W=7;for(let w=0;w<J.length;w++)W=W*31+J.charCodeAt(w)|0;let F=typeof G==="number"?G:Math.abs(W),K=m`SELECT pg_try_advisory_lock(${F}) as ok`,D=await j(K,"raw");return Boolean(D?.[0]?.ok)}if(J0(f.dialect)){let J=`bqb:${String(G)}`,W=m`SELECT GET_LOCK(${J}, 0) AS ok`,F=await j(W,"raw");return Number(F?.[0]?.ok)===1}return!1},unsafe(G,J){return m.unsafe(G,J)},file(G,J){return m.file(G,J)},async reserve(){let G=await m.reserve(),J=K0({sql:G,meta:Z,schema:Y});return J.release=()=>G.release(),J},async close(G){await m.close(G)},async listen(G,J){},async unlisten(G){},async notify(G,J){},async copyTo(G,J){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(G,J,W){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let G=m`SELECT 1`;return await j(G,"select"),!0}catch{return!1}},async waitForReady(G){let J=Math.max(1,G?.attempts??10),W=Math.max(10,G?.delayMs??100);for(let F=0;F<J;F++){if(await this.ping())return;await new Promise((K)=>setTimeout(K,W))}throw Error("Database not ready after waiting")},async transaction(G,J){let F={...X?.txDefaults,...J},K=X?.sql??m,D=X?.inTransaction===!0,w=D&&typeof K?.savepoint==="function"?"savepoint":"begin",T=async(H)=>{F.logger?.({type:"start",attempt:H});let x=Date.now();return await K[w](async(h)=>{let c=K0({sql:h,meta:Z,schema:Y,inTransaction:!0});if(F?.isolation&&!D){let v=F.isolation,n=v==="read committed"?"READ COMMITTED":v==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(f.dialect==="postgres")await h.unsafe(`SET TRANSACTION ISOLATION LEVEL ${n}`);else if(J0(f.dialect))await h.unsafe(`SET TRANSACTION ISOLATION LEVEL ${n}`);else if(v!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${v}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(F?.readOnly)if(f.dialect==="postgres")await h.unsafe("SET TRANSACTION READ ONLY");else if(J0(f.dialect))await h.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let y=await G(c),g=Date.now()-x;return F.logger?.({type:"commit",attempt:H,durationMs:g}),y})},N=Math.max(0,F?.retries??0),q=0;for(;;)try{let H=await T(q+1);return F?.afterCommit?.(),H}catch(H){let x=v_(H)||b_(H,F.sqlStates);if(q<N&&x){q++,F?.onRetry?.(q,H);let h=d_(q,F.backoff);if(h>0)await f_(h);continue}try{F.onRollback?.(H)}catch{}try{F.afterRollback?.()}catch{}throw H}},async savepoint(G){let J=$;if(!J||typeof J.savepoint!=="function")throw Error("savepoint() must be called inside a transaction");return await J.savepoint(async(W)=>{let F=K0({sql:W,meta:Z,schema:Y});return await G(F)})},async beginDistributed(G,J){return await(X?.sql??m).beginDistributed(G,async(K)=>{let D=K0({sql:K,meta:Z,schema:Y});return await J(D)})},async commitDistributed(G){await m.commitDistributed(G)},async rollbackDistributed(G){await m.rollbackDistributed(G)},setTransactionDefaults(G){X={...X,txDefaults:{...X?.txDefaults,...G}}},transactional(G,J){return(...W)=>{return this.transaction((F)=>G(F,...W),J)}},async insertOrIgnore(G,J){let W=Array.isArray(J)?J:[J];if(!W.length)return;let{colsSql:F,valuesSql:K,params:D}=e$(W),w=a0(String(G)),T=J0(f.dialect)?`INSERT IGNORE INTO ${w} (${F}) VALUES ${K}`:`INSERT INTO ${w} (${F}) VALUES ${K} ON CONFLICT DO NOTHING`;return m.unsafe(T,D).execute()},async insertGetId(G,J,W="id"){let{colsSql:F,valuesSql:K,params:D}=e$([J]),w=a0(String(G));if(J0(f.dialect)){await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K}`,D).execute();let[N]=await m.unsafe("SELECT LAST_INSERT_ID() as id").execute();return N?.id}if(f.dialect==="sqlite"){let N=await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K}`,D).execute();if(N?.lastInsertRowid!=null)return N.lastInsertRowid;let[q]=await m.unsafe("SELECT last_insert_rowid() as id").execute();return q?.id}let[T]=await m.unsafe(`INSERT INTO ${w} (${F}) VALUES ${K} RETURNING ${a0(String(W))} as id`,D).execute();return T?.id},async updateOrInsert(G,J,W){let F=a0(String(G)),K=Object.keys(J),D=1,w=K.map((h)=>`${a0(h)} = ${i(D++)}`).join(" AND "),T=K.map((h)=>J[h]);if((await m.unsafe(`SELECT 1 FROM ${F} WHERE ${w} LIMIT 1`,T).execute()).length){let h=Object.keys(W),c=1,y=h.map((n)=>`${a0(n)} = ${i(c++)}`).join(", "),g=K.map((n)=>`${a0(n)} = ${i(c++)}`).join(" AND "),v=[...h.map((n)=>W[n]),...K.map((n)=>J[n])];return await m.unsafe(`UPDATE ${F} SET ${y} WHERE ${g}`,v).execute(),!0}let{colsSql:q,valuesSql:H,params:x}=e$([{...J,...W}]);return await m.unsafe(`INSERT INTO ${F} (${q}) VALUES ${H}`,x).execute(),!0},async upsert(G,J,W,F){let K=W.map((y)=>String(y)),D=(F??[]).map((y)=>String(y)),w=J;if(!w.length)return;let{colsSql:T,valuesSql:N,params:q}=e$(w),H=a0(String(G)),x=`INSERT INTO ${H} (${T}) VALUES ${N}`;if(J0(f.dialect)){if(D.length===0)return m.unsafe(`INSERT IGNORE INTO ${H} (${T}) VALUES ${N}`,q).execute();let y=D.map((g)=>`${a0(g)} = VALUES(${a0(g)})`).join(", ");return m.unsafe(`${x} ON DUPLICATE KEY UPDATE ${y}`,q).execute()}let h=K.map(a0).join(", ");if(D.length===0)return m.unsafe(`${x} ON CONFLICT (${h}) DO NOTHING`,q).execute();let c=D.map((y)=>`${a0(y)} = EXCLUDED.${a0(y)}`).join(", ");return m.unsafe(`${x} ON CONFLICT (${h}) DO UPDATE SET ${c}`,q).execute()},async save(G,J){let W=Z?.primaryKeys[String(G)]??"id",F=J[W];if(F!=null)if(await this.selectFrom(G).find(F)){await this.updateTable(G).set(J).where({[W]:F}).execute();let D=await this.selectFrom(G).find(F);if(!D)throw Error("save() failed to retrieve updated row");return D}else return await this.create(G,J);return await this.create(G,J)},async remove(G,J){return await this.deleteFrom(G).where({id:J}).execute()},async find(G,J){return await this.selectFrom(G).find(J)},async findOrFail(G,J){return await this.selectFrom(G).findOrFail(J)},async findMany(G,J){return await this.selectFrom(G).findMany(J)},async latest(G,J){return await this.selectFrom(G).latest(J).first()},async oldest(G,J){return await this.selectFrom(G).oldest(J).first()},skip(G,J){return this.selectFrom(G).offset(J)},async rawQuery(G){let J=Date.now();try{f.hooks?.onQueryStart?.({sql:G,kind:"raw"});let W=await m.unsafe(G);return f.hooks?.onQueryEnd?.({sql:G,durationMs:Date.now()-J,kind:"raw"}),W}catch(W){throw f.hooks?.onQueryError?.({sql:G,error:W,durationMs:Date.now()-J,kind:"raw"}),W}},async create(G,J){let W=Z?.primaryKeys[String(G)]??"id";try{await f.hooks?.beforeCreate?.({table:String(G),data:J})}catch(F){throw F}if(f.dialect==="postgres"){let F=m`INSERT INTO ${m(String(G))} ${m(J)} RETURNING ${m(String(W))} as id`,[K]=await F.execute();if(console.log("resultId",K),!K?.id)throw console.error(`create() failed to get insert ID for table ${String(G)}`),console.error("Inserted values:",J),Error(`create() failed to get insert ID for table ${String(G)}`);let D=await this.selectFrom(G).find(K.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${K.id}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${K.id}`);try{await f.hooks?.afterCreate?.({table:String(G),data:J,result:D})}catch{}return D}else{let F=await this.insertGetId(G,J,W);if(F==null)throw Error(`create() failed to get insert ID for table ${String(G)}`);let K=await this.selectFrom(G).find(F);if(!K)throw console.error(`create() failed to retrieve inserted row for table ${String(G)} with id ${F}`),console.error("Inserted values:",J),Error(`create() failed to retrieve inserted row for table ${String(G)} with id ${F}`);try{await f.hooks?.afterCreate?.({table:String(G),data:J,result:K})}catch{}return K}},async createMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),K=F.length,D=J.length,w=Array.from({length:D*K}),T=J0(f.dialect)?(H)=>`\`${String(H).replace(/`/g,"``")}\``:(H)=>`"${String(H).replace(/"/g,'""')}"`,N=`INSERT INTO ${T(String(G))}(${F.map(T).join(",")})VALUES`,q=0;for(let H=0;H<D;H++){if(H>0)N+=",";N+="(";let x=J[H];for(let h=0;h<K;h++){if(h>0)N+=",";N+=i(q+1),w[q++]=x[F[h]]}N+=")"}return $.unsafe(N,w).execute()},async insertMany(G,J){if(!J?.length)return;let W=J[0],F=Object.keys(W),K=F.length,D=J.length,w=D*K,T=Array(w),N=f.dialect==="postgres",q;if(!N){let h=Array(K);for(let c=0;c<K;c++)h[c]="?";q=`(${h.join(",")})`}else q="";let H=Array(D+2);H[0]=`INSERT INTO ${G}(${F.join(",")})VALUES`;let x=0;if(!N){for(let h=0;h<D;h++){let c=J[h];H[h+1]=q;for(let y=0;y<K;y++)T[x++]=c[F[y]]}return $.unsafe(H[0]+H.slice(1,D+1).join(","),T).execute()}for(let h=0;h<D;h++){let c=J[h],y=Array(K);for(let g=0;g<K;g++)y[g]=`$${x+1}`,T[x++]=c[F[g]];H[h+1]=`(${y.join(",")})`}return $.unsafe(H[0]+H.slice(1,D+1).join(","),T).execute()},async updateMany(G,J,W){let F=Object.keys(W),K=F.length;if(K===0)return 0;let D=[],w=Array.from({length:K});for(let N=0;N<K;N++)w[N]=`${F[N]}=${i(N+1)}`,D.push(W[F[N]]);let T=`UPDATE ${G} SET ${w.join(",")}`;if(Array.isArray(J))T+=` WHERE ${J[0]}${J[1]}${i(D.length+1)}`,D.push(J[2]);else if(J&&typeof J==="object"&&!("raw"in J)){let N=Object.keys(J),q=N.length;if(q>0){let H=D.length,x=Array.from({length:q});for(let h=0;h<q;h++)x[h]=`${N[h]}=${i(H+h+1)}`,D.push(J[N[h]]);T+=` WHERE ${x.join(" AND ")}`}}return $.unsafe(T,D).execute()},async deleteMany(G,J){if(!Array.isArray(J)||J.length===0)return 0;let W=Z?.primaryKeys[String(G)]??"id",F=J.length;if(f.dialect==="postgres"){let D=Array(F);for(let w=0;w<F;w++)D[w]=`$${w+1}`;return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${D.join(",")})`,J).execute()}let K=Array(F);for(let D=0;D<F;D++)K[D]="?";return $.unsafe(`DELETE FROM ${G} WHERE ${W} IN (${K.join(",")})`,J).execute()},async firstOrCreate(G,J,W){let F=await this.selectFrom(G).where(J).first();if(F)return F;return await this.create(G,{...J,...W})},async updateOrCreate(G,J,W){let F=await this.selectFrom(G).where(J).first();if(F){await this.updateTable(G).set(W).where(J).execute();let K=Z?.primaryKeys[String(G)]??"id",D=F[K],w=D!=null?await this.selectFrom(G).find(D):await this.selectFrom(G).where(J).first();if(!w)throw Error("updateOrCreate() failed to retrieve updated row");return w}return await this.create(G,{...J,...W})},async count(G,J){let W=J?m(String(J)):m`*`,F=m`SELECT COUNT(${W}) as c FROM ${m(String(G))}`,[K]=await F.execute();return Number(K?.c??0)},async sum(G,J){let W=m`SELECT SUM(${m(String(J))}) as s FROM ${m(String(G))}`,[F]=await W.execute();return Number(F?.s??0)},async avg(G,J){let W=m`SELECT AVG(${m(String(J))}) as a FROM ${m(String(G))}`,[F]=await W.execute();return Number(F?.a??0)},async min(G,J){let W=m`SELECT MIN(${m(String(J))}) as m FROM ${m(String(G))}`,[F]=await W.execute();return F?.m},async max(G,J){let W=m`SELECT MAX(${m(String(J))}) as m FROM ${m(String(G))}`,[F]=await W.execute();return F?.m},getRelationships(G){if(!Z?.relations)return{};let J=Z.relations[G];if(!J)return{};let W={};for(let[F,K]of Object.entries(J))if(K&&typeof K==="object"&&Object.keys(K).length>0)W[F]=K;return W},hasRelationship(G,J){if(!Z?.relations)return!1;let W=Z.relations[G];if(!W)return!1;return Object.values(W).some((F)=>F&&typeof F==="object"&&(J in F))},getRelationshipType(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,K]of Object.entries(W))if(K&&typeof K==="object"&&J in K)return F;return null},getRelationshipTarget(G,J){if(!Z?.relations)return null;let W=Z.relations[G];if(!W)return null;for(let[F,K]of Object.entries(W))if(K&&typeof K==="object"&&J in K){let D=K[J];if(typeof D==="string")return Z.modelToTable[D]||D;else if(D&&typeof D==="object"){if("model"in D)return Z.modelToTable[D.model]||D.model;if("target"in D)return Z.modelToTable[D.target]||D.target}}return null}}}function p_(){S$.clear()}function c_(X){S$.setMaxSize(X)}var s,w1,q1,S$,oX,m_=500,UZ=e(()=>{d0(),$X(),s={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},w1=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]),q1=new Set,S$=new _U,oX=new Map});async function RG(){console.log("-- Clearing query cache..."),p_(),console.log("-- \u2713 Query cache cleared")}async function DG(){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 MG(X={}){if(console.log("-- Configuring query cache..."),console.log(),X.size!==void 0){let $=Number(X.size);if(Number.isNaN($)||$<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");c_($),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")}var u_=e(()=>{UZ()});async function i_(){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 X=K0(),$=n_({input:$8.stdin,output:$8.stdout,prompt:"qb> "}),Z="",Y=!1,U=`
78
79
  Available Commands:
79
80
  .help Show this help message
80
81
  .exit Exit the console
@@ -93,92 +94,92 @@ Tips:
93
94
  - Use 'await' for async operations
94
95
  - Multi-line input: end with \\ to continue on next line
95
96
  - Press Enter on an empty line to execute multi-line input
96
- `,j=async(z)=>{try{let U=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${z})`)($);if(U!==void 0)if(Array.isArray(U))console.log(`-- ${U.length} row(s) returned`),console.table(U);else if(typeof U==="object"&&U!==null)console.log(U);else console.log(U)}catch(F){console.error("Error:",F.message)}},Y=async(z)=>{let F=z.trim();if(F.startsWith(".")){let E=F.toLowerCase();if(E===".exit"||E===".quit")console.log("Goodbye!"),Z.close(),N1.exit(0);else if(E===".help")console.log(L);else if(E===".clear")console.clear();else if(E===".tables")try{let U=await $.unsafe(`
97
+ `,_=async(L)=>{try{let E=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${L})`)(X);if(E!==void 0)if(Array.isArray(E))console.log(`-- ${E.length} row(s) returned`),console.table(E);else if(typeof E==="object"&&E!==null)console.log(E);else console.log(E)}catch(z){console.error("Error:",z.message)}},Q=async(L)=>{let z=L.trim();if(z.startsWith(".")){let j=z.toLowerCase();if(j===".exit"||j===".quit")console.log("Goodbye!"),$.close(),$8.exit(0);else if(j===".help")console.log(U);else if(j===".clear")console.clear();else if(j===".tables")try{let E=await X.unsafe(`
97
98
  SELECT name FROM sqlite_master
98
99
  WHERE type = 'table'
99
100
  AND name NOT LIKE 'sqlite_%'
100
101
  ORDER BY name
101
- `);if(U.length>0){console.log("Tables:");for(let V of U)console.log(` - ${V.name}`)}else console.log("No tables found")}catch(U){console.error("Error listing tables:",U.message)}else console.log(`Unknown command: ${F}`),console.log("Type .help for available commands");return}if(F.endsWith("\\")){_=!0,X+=`${F.slice(0,-1)}
102
- `;return}if(_){if(F==="")await j(X),X="",_=!1;else X+=`${F}
103
- `;return}if(F)await j(F)};Z.on("line",async(z)=>{await Y(z),Z.prompt()}),Z.on("SIGINT",()=>{if(_)console.log(`
104
- -- Multi-line input cancelled`),X="",_=!1,Z.prompt();else console.log(`
105
- -- Type .exit to quit`),Z.prompt()}),Z.on("close",()=>{console.log(`
106
- Goodbye!`),N1.exit(0)}),Z.prompt()}async function LE(){return uL()}var nL=n(()=>{P0()});async function YE($,Z={}){let X=Z.format||"json",_=Z.output||`${$}.${X}`,L=Z.limit;if(console.log(`-- Exporting data from table: ${$}`),console.log(`-- Format: ${X}`),console.log(`-- Output: ${_}`),L)console.log(`-- Limit: ${L} rows`);console.log();try{let Y=W0().selectFrom($);if(L)Y=Y.limit(L);let z=await Y.execute();if(console.log(`-- Retrieved ${z.length} rows`),X==="json")N8(_,JSON.stringify(z,null,2)),console.log(`-- \u2713 Exported to JSON: ${_}`);else if(X==="csv"){if(z.length===0){N8(_,""),console.log(`-- \u2713 Exported to CSV: ${_} (empty)`);return}let F=Object.keys(z[0]),E=[F.join(",")];for(let U of z){let V=F.map((Q)=>{let O=U[Q];if(O===null||O===void 0)return"";let K=String(O);if(K.includes(",")||K.includes('"')||K.includes(`
107
- `))return`"${K.replace(/"/g,'""')}"`;return K});E.push(V.join(","))}N8(_,E.join(`
108
- `)),console.log(`-- \u2713 Exported to CSV: ${_}`)}else if(X==="sql"){let F=[];for(let E of z){let U=Object.keys(E),V=U.map((Q)=>{let O=E[Q];if(O===null||O===void 0)return"NULL";if(typeof O==="number")return String(O);return`'${String(O).replace(/'/g,"''")}'`});F.push(`INSERT INTO ${$} (${U.join(", ")}) VALUES (${V.join(", ")});`)}N8(_,F.join(`
109
- `)),console.log(`-- \u2713 Exported to SQL: ${_}`)}}catch(j){throw console.error(`-- Failed to export data from ${$}:`,j),j}}async function FE($,Z,X={}){if(!iL(Z))throw console.error(`-- File not found: ${Z}`),Error(`File not found: ${Z}`);let _=X.format||(Z.endsWith(".json")?"json":"csv"),L=X.truncate??!1;console.log(`-- Importing data into table: ${$}`),console.log(`-- Format: ${_}`),console.log(`-- File: ${Z}`),console.log(`-- Truncate: ${L}`),console.log();try{let j=W0();if(L)await j.deleteFrom($).execute(),console.log("-- Table truncated");let Y=lL(Z,"utf8"),z=[];if(_==="json"){if(z=JSON.parse(Y),!Array.isArray(z))throw TypeError("JSON file must contain an array of objects")}else if(_==="csv"){let U=Y.split(`
110
- `).filter((Q)=>Q.trim());if(U.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let V=U[0].split(",").map((Q)=>Q.trim());for(let Q=1;Q<U.length;Q++){let O=U[Q].split(",").map((I)=>I.trim()),K={};for(let I=0;I<V.length;I++){let C=O[I];if(C.startsWith('"')&&C.endsWith('"'))C=C.slice(1,-1).replace(/""/g,'"');if(C==="")C=null;else if(!Number.isNaN(Number(C)))C=Number(C);K[V[I]]=C}z.push(K)}}if(z.length===0){console.log("-- No data to import");return}let F=100,E=0;for(let U=0;U<z.length;U+=F){let V=z.slice(U,U+F);await j.insertInto($).values(V).execute(),E+=V.length,console.log(`-- Imported ${E}/${z.length} rows...`)}console.log(`-- \u2713 Successfully imported ${z.length} rows`)}catch(j){throw console.error(`-- Failed to import data into ${$}:`,j),j}}async function zE($={}){let Z=y.dialect||"postgres",X=$.output||`dump-${Date.now()}.sql`,_=$.tables?.split(",").map((L)=>L.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${Z}`),console.log(`-- Output: ${X}`),_)console.log(`-- Tables: ${_.join(", ")}`);console.log();try{let L=W0(),j=[];if(Z==="sqlite")j=(await L.unsafe(`
102
+ `);if(E.length>0){console.log("Tables:");for(let V of E)console.log(` - ${V.name}`)}else console.log("No tables found")}catch(E){console.error("Error listing tables:",E.message)}else console.log(`Unknown command: ${z}`),console.log("Type .help for available commands");return}if(z.endsWith("\\")){Y=!0,Z+=`${z.slice(0,-1)}
103
+ `;return}if(Y){if(z==="")await _(Z),Z="",Y=!1;else Z+=`${z}
104
+ `;return}if(z)await _(z)};$.on("line",async(L)=>{await Q(L),$.prompt()}),$.on("SIGINT",()=>{if(Y)console.log(`
105
+ -- Multi-line input cancelled`),Z="",Y=!1,$.prompt();else console.log(`
106
+ -- Type .exit to quit`),$.prompt()}),$.on("close",()=>{console.log(`
107
+ Goodbye!`),$8.exit(0)}),$.prompt()}async function wG(){return i_()}var l_=e(()=>{y0()});async function PG(X,$={}){let Z=$.format||"json",Y=$.output||`${X}.${Z}`,U=$.limit;if(console.log(`-- Exporting data from table: ${X}`),console.log(`-- Format: ${Z}`),console.log(`-- Output: ${Y}`),U)console.log(`-- Limit: ${U} rows`);console.log();try{let Q=K0().selectFrom(X);if(U)Q=Q.limit(U);let L=await Q.execute();if(console.log(`-- Retrieved ${L.length} rows`),Z==="json")rX(Y,JSON.stringify(L,null,2)),console.log(`-- \u2713 Exported to JSON: ${Y}`);else if(Z==="csv"){if(L.length===0){rX(Y,""),console.log(`-- \u2713 Exported to CSV: ${Y} (empty)`);return}let z=Object.keys(L[0]),j=[z.join(",")];for(let E of L){let V=z.map((G)=>{let J=E[G];if(J===null||J===void 0)return"";let W=String(J);if(W.includes(",")||W.includes('"')||W.includes(`
108
+ `))return`"${W.replace(/"/g,'""')}"`;return W});j.push(V.join(","))}rX(Y,j.join(`
109
+ `)),console.log(`-- \u2713 Exported to CSV: ${Y}`)}else if(Z==="sql"){let z=[];for(let j of L){let E=Object.keys(j),V=E.map((G)=>{let J=j[G];if(J===null||J===void 0)return"NULL";if(typeof J==="number")return String(J);return`'${String(J).replace(/'/g,"''")}'`});z.push(`INSERT INTO ${X} (${E.join(", ")}) VALUES (${V.join(", ")});`)}rX(Y,z.join(`
110
+ `)),console.log(`-- \u2713 Exported to SQL: ${Y}`)}}catch(_){throw console.error(`-- Failed to export data from ${X}:`,_),_}}async function TG(X,$,Z={}){if(!s_($))throw console.error(`-- File not found: ${$}`),Error(`File not found: ${$}`);let Y=Z.format||($.endsWith(".json")?"json":"csv"),U=Z.truncate??!1;console.log(`-- Importing data into table: ${X}`),console.log(`-- Format: ${Y}`),console.log(`-- File: ${$}`),console.log(`-- Truncate: ${U}`),console.log();try{let _=K0();if(U)await _.deleteFrom(X).execute(),console.log("-- Table truncated");let Q=o_($,"utf8"),L=[];if(Y==="json"){if(L=JSON.parse(Q),!Array.isArray(L))throw TypeError("JSON file must contain an array of objects")}else if(Y==="csv"){let E=Q.split(`
111
+ `).filter((G)=>G.trim());if(E.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let V=E[0].split(",").map((G)=>G.trim());for(let G=1;G<E.length;G++){let J=E[G].split(",").map((F)=>F.trim()),W={};for(let F=0;F<V.length;F++){let K=J[F];if(K.startsWith('"')&&K.endsWith('"'))K=K.slice(1,-1).replace(/""/g,'"');if(K==="")K=null;else if(!Number.isNaN(Number(K)))K=Number(K);W[V[F]]=K}L.push(W)}}if(L.length===0){console.log("-- No data to import");return}let z=100,j=0;for(let E=0;E<L.length;E+=z){let V=L.slice(E,E+z);await _.insertInto(X).values(V).execute(),j+=V.length,console.log(`-- Imported ${j}/${L.length} rows...`)}console.log(`-- \u2713 Successfully imported ${L.length} rows`)}catch(_){throw console.error(`-- Failed to import data into ${X}:`,_),_}}async function NG(X={}){let $=f.dialect||"postgres",Z=X.output||`dump-${Date.now()}.sql`,Y=X.tables?.split(",").map((U)=>U.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${$}`),console.log(`-- Output: ${Z}`),Y)console.log(`-- Tables: ${Y.join(", ")}`);console.log();try{let U=K0(),_=[];if($==="sqlite")_=(await U.unsafe(`
111
112
  SELECT name FROM sqlite_master
112
113
  WHERE type = 'table'
113
114
  AND name NOT LIKE 'sqlite_%'
114
115
  ORDER BY name
115
- `)).map((F)=>F.name);else if(Z==="postgres")j=(await L.unsafe(`
116
+ `)).map((z)=>z.name);else if($==="postgres")_=(await U.unsafe(`
116
117
  SELECT table_name
117
118
  FROM information_schema.tables
118
119
  WHERE table_schema = 'public'
119
120
  AND table_type = 'BASE TABLE'
120
121
  ORDER BY table_name
121
- `)).map((F)=>F.table_name);else if(Z==="mysql")j=(await L.unsafe(`
122
+ `)).map((z)=>z.table_name);else if(J0($))_=(await U.unsafe(`
122
123
  SELECT table_name
123
124
  FROM information_schema.tables
124
125
  WHERE table_schema = DATABASE()
125
126
  AND table_type = 'BASE TABLE'
126
127
  ORDER BY table_name
127
- `)).map((F)=>F.table_name);if(_)j=j.filter((z)=>_.includes(z));if(j.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${j.length} table(s)`);let Y=[];Y.push("-- Database dump"),Y.push(`-- Generated at: ${new Date().toISOString()}`),Y.push(`-- Dialect: ${Z}`),Y.push("");for(let z of j){console.log(`-- Dumping table: ${z}`);let F=await L.selectFrom(z).execute();Y.push(`-- Table: ${z}`),Y.push(`-- Rows: ${F.length}`),Y.push("");for(let E of F){let U=Object.keys(E),V=U.map((Q)=>{let O=E[Q];if(O===null||O===void 0)return"NULL";if(typeof O==="number")return String(O);return`'${String(O).replace(/'/g,"''")}'`});Y.push(`INSERT INTO ${z} (${U.join(", ")}) VALUES (${V.join(", ")});`)}Y.push("")}N8(X,Y.join(`
128
- `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${X}`)}catch(L){throw console.error("-- Failed to dump database:",L),L}}var sL=n(()=>{F9(),i$()});async function oL(){let $=y.dialect||"postgres",Z=y.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${$}`),console.log(`-- Database: ${Z}`),console.log();try{let X=W0(),_=[],L=[];if($==="postgres")L=(await X.unsafe(`
128
+ `)).map((z)=>z.table_name);if(Y)_=_.filter((L)=>Y.includes(L));if(_.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${_.length} table(s)`);let Q=[];Q.push("-- Database dump"),Q.push(`-- Generated at: ${new Date().toISOString()}`),Q.push(`-- Dialect: ${$}`),Q.push("");for(let L of _){console.log(`-- Dumping table: ${L}`);let z=await U.selectFrom(L).execute();Q.push(`-- Table: ${L}`),Q.push(`-- Rows: ${z.length}`),Q.push("");for(let j of z){let E=Object.keys(j),V=E.map((G)=>{let J=j[G];if(J===null||J===void 0)return"NULL";if(typeof J==="number")return String(J);return`'${String(J).replace(/'/g,"''")}'`});Q.push(`INSERT INTO ${L} (${E.join(", ")}) VALUES (${V.join(", ")});`)}Q.push("")}rX(Z,Q.join(`
129
+ `)),console.log(),console.log(`-- \u2713 Database dump saved to: ${Z}`)}catch(U){throw console.error("-- Failed to dump database:",U),U}}var r_=e(()=>{d0(),UZ()});async function a_(){let X=f.dialect||"postgres",$=f.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${X}`),console.log(`-- Database: ${$}`),console.log();try{let Z=K0(),Y=[],U=[];if(X==="postgres")U=(await Z.unsafe(`
129
130
  SELECT table_name
130
131
  FROM information_schema.tables
131
132
  WHERE table_schema = 'public'
132
133
  AND table_type = 'BASE TABLE'
133
134
  ORDER BY table_name
134
- `)).map((z)=>z.table_name);else if($==="mysql")L=(await X.unsafe(`
135
+ `)).map((L)=>L.table_name);else if(J0(X))U=(await Z.unsafe(`
135
136
  SELECT table_name
136
137
  FROM information_schema.tables
137
138
  WHERE table_schema = DATABASE()
138
139
  AND table_type = 'BASE TABLE'
139
140
  ORDER BY table_name
140
- `)).map((z)=>z.table_name);else if($==="sqlite")L=(await X.unsafe(`
141
+ `)).map((L)=>L.table_name);else if(X==="sqlite")U=(await Z.unsafe(`
141
142
  SELECT name
142
143
  FROM sqlite_master
143
144
  WHERE type = 'table'
144
145
  AND name NOT LIKE 'sqlite_%'
145
146
  ORDER BY name
146
- `)).map((z)=>z.name);for(let Y of L)try{let z=await X.unsafe(`SELECT COUNT(*) as count FROM ${Y}`),F=Number(z[0]?.count||0),E=0,U=0;if($==="postgres"){let V=await X.unsafe(`
147
+ `)).map((L)=>L.name);for(let Q of U)try{let L=await Z.unsafe(`SELECT COUNT(*) as count FROM ${Q}`),z=Number(L[0]?.count||0),j=0,E=0;if(X==="postgres"){let V=await Z.unsafe(`
147
148
  SELECT COUNT(*) as count
148
149
  FROM information_schema.columns
149
150
  WHERE table_name = $1
150
- `,[Y]);E=Number(V[0]?.count||0);let Q=await X.unsafe(`
151
+ `,[Q]);j=Number(V[0]?.count||0);let G=await Z.unsafe(`
151
152
  SELECT COUNT(*) as count
152
153
  FROM pg_indexes
153
154
  WHERE tablename = $1
154
- `,[Y]);U=Number(Q[0]?.count||0)}else if($==="mysql"){let V=await X.unsafe(`
155
+ `,[Q]);E=Number(G[0]?.count||0)}else if(J0(X)){let V=await Z.unsafe(`
155
156
  SELECT COUNT(*) as count
156
157
  FROM information_schema.columns
157
158
  WHERE table_name = ?
158
159
  AND table_schema = DATABASE()
159
- `,[Y]);E=Number(V[0]?.count||0);let Q=await X.unsafe(`
160
+ `,[Q]);j=Number(V[0]?.count||0);let G=await Z.unsafe(`
160
161
  SELECT COUNT(*) as count
161
162
  FROM information_schema.statistics
162
163
  WHERE table_name = ?
163
164
  AND table_schema = DATABASE()
164
- `,[Y]);U=Number(Q[0]?.count||0)}else if($==="sqlite")E=(await X.unsafe(`PRAGMA table_info(${Y})`)).length,U=(await X.unsafe(`PRAGMA index_list(${Y})`)).length;_.push({name:Y,rowCount:F,columns:E,indexes:U})}catch(z){console.error(`-- Error getting info for table ${Y}:`,z)}let j=_.reduce((Y,z)=>Y+z.rowCount,0);if(console.log(`-- Total Tables: ${_.length}`),console.log(`-- Total Rows: ${j.toLocaleString()}`),console.log(),_.length>0){console.log("Tables:"),console.log();let Y=Math.max(..._.map((E)=>E.name.length)),z=Y+2,F="Table".padEnd(z)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(F),console.log("-".repeat(F.length));for(let E of _){let U=E.name.padEnd(Y+2),V=E.rowCount.toLocaleString().padStart(12),Q=(E.columns||0).toString().padStart(10),O=(E.indexes||0).toString().padStart(10);console.log(`${U}${V}${Q}${O}`)}}else console.log("-- No tables found");return{dialect:$,database:Z,tables:_,totalTables:_.length,totalRows:j}}catch(X){throw console.error("-- Failed to get database info:",X),X}}async function UE(){return oL()}var rL=n(()=>{F9(),P0()});async function OE($={}){let Z=$.dialect||l6.env.DB_DIALECT||"postgres",X=$.aggressive||!1;if($.verbose)console.log(`Optimizing ${Z} database${X?" (aggressive mode)":""}...`);try{if(Z==="postgres"){if($.tables&&$.tables.length>0)for(let _ of $.tables){if($.verbose)console.log(`Analyzing table: ${_}`);if(X)await x`VACUUM FULL ANALYZE ${x(_)}`;else await x`VACUUM ANALYZE ${x(_)}`}else{if($.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(X)await x`VACUUM FULL`,await x`ANALYZE`;else await x`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(Z==="mysql"){if($.tables&&$.tables.length>0)for(let _ of $.tables){if($.verbose)console.log(`Optimizing table: ${_}`);await x`OPTIMIZE TABLE ${x(_)}`,await x`ANALYZE TABLE ${x(_)}`}else{let _=l6.env.DB_NAME||"test",L=await x`
165
+ `,[Q]);E=Number(G[0]?.count||0)}else if(X==="sqlite")j=(await Z.unsafe(`PRAGMA table_info(${Q})`)).length,E=(await Z.unsafe(`PRAGMA index_list(${Q})`)).length;Y.push({name:Q,rowCount:z,columns:j,indexes:E})}catch(L){console.error(`-- Error getting info for table ${Q}:`,L)}let _=Y.reduce((Q,L)=>Q+L.rowCount,0);if(console.log(`-- Total Tables: ${Y.length}`),console.log(`-- Total Rows: ${_.toLocaleString()}`),console.log(),Y.length>0){console.log("Tables:"),console.log();let Q=Math.max(...Y.map((j)=>j.name.length)),L=Q+2,z="Table".padEnd(L)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(z),console.log("-".repeat(z.length));for(let j of Y){let E=j.name.padEnd(Q+2),V=j.rowCount.toLocaleString().padStart(12),G=(j.columns||0).toString().padStart(10),J=(j.indexes||0).toString().padStart(10);console.log(`${E}${V}${G}${J}`)}}else console.log("-- No tables found");return{dialect:X,database:$,tables:Y,totalTables:Y.length,totalRows:_}}catch(Z){throw console.error("-- Failed to get database info:",Z),Z}}async function SG(){return a_()}var t_=e(()=>{d0(),y0()});async function kG(X={}){let $=X.dialect||NY.env.DB_DIALECT||"postgres",Z=X.aggressive||!1;if(X.verbose)console.log(`Optimizing ${$} database${Z?" (aggressive mode)":""}...`);try{if($==="postgres"){if(X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);if(Z)await m`VACUUM FULL ANALYZE ${m(Y)}`;else await m`VACUUM ANALYZE ${m(Y)}`}else{if(X.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(Z)await m`VACUUM FULL`,await m`ANALYZE`;else await m`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(J0($)){if(X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Optimizing table: ${Y}`);await m`OPTIMIZE TABLE ${m(Y)}`,await m`ANALYZE TABLE ${m(Y)}`}else{let Y=NY.env.DB_NAME||"test",U=await m`
165
166
  SELECT table_name
166
167
  FROM information_schema.tables
167
- WHERE table_schema = ${_}
168
- `;for(let j of L){let Y=j.table_name||j.TABLE_NAME;if($.verbose)console.log(`Optimizing table: ${Y}`);await x`OPTIMIZE TABLE ${x(Y)}`,await x`ANALYZE TABLE ${x(Y)}`}}console.log("\u2713 MySQL optimization complete")}else if(Z==="sqlite"){if($.verbose)console.log("Running VACUUM on SQLite database...");if(await x`VACUUM`,$.tables&&$.tables.length>0)for(let _ of $.tables){if($.verbose)console.log(`Analyzing table: ${_}`);await x`ANALYZE ${x(_)}`}else await x`ANALYZE`;if(X){if($.verbose)console.log("Running aggressive SQLite optimizations...");await x`PRAGMA optimize`,await x`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${Z}`)}catch(_){throw console.error("Error optimizing database:",_.message),_}}var tL=n(()=>{G8()});async function VE($={}){let Z=$.dialect||s6.env.DB_DIALECT||"postgres";if($.verbose)console.log(`Wiping all tables from ${Z} database...`);try{let X=[];if(Z==="postgres")X=(await x`
168
+ WHERE table_schema = ${Y}
169
+ `;for(let _ of U){let Q=_.table_name||_.TABLE_NAME;if(X.verbose)console.log(`Optimizing table: ${Q}`);await m`OPTIMIZE TABLE ${m(Q)}`,await m`ANALYZE TABLE ${m(Q)}`}}console.log("\u2713 MySQL optimization complete")}else if($==="sqlite"){if(X.verbose)console.log("Running VACUUM on SQLite database...");if(await m`VACUUM`,X.tables&&X.tables.length>0)for(let Y of X.tables){if(X.verbose)console.log(`Analyzing table: ${Y}`);await m`ANALYZE ${m(Y)}`}else await m`ANALYZE`;if(Z){if(X.verbose)console.log("Running aggressive SQLite optimizations...");await m`PRAGMA optimize`,await m`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${$}`)}catch(Y){throw console.error("Error optimizing database:",Y.message),Y}}var e_=e(()=>{d0(),$X()});async function BG(X={}){let $=X.dialect||SY.env.DB_DIALECT||"postgres";if(X.verbose)console.log(`Wiping all tables from ${$} database...`);try{let Z=[];if($==="postgres")Z=(await m`
169
170
  SELECT tablename
170
171
  FROM pg_tables
171
172
  WHERE schemaname = 'public'
172
- `).map((L)=>L.tablename);else if(Z==="mysql"){let _=s6.env.DB_NAME||"test";X=(await x`
173
+ `).map((U)=>U.tablename);else if(J0($)){let Y=SY.env.DB_NAME||"test";Z=(await m`
173
174
  SELECT table_name
174
175
  FROM information_schema.tables
175
- WHERE table_schema = ${_}
176
- `).map((j)=>j.table_name||j.TABLE_NAME)}else if(Z==="sqlite")X=(await x`
176
+ WHERE table_schema = ${Y}
177
+ `).map((_)=>_.table_name||_.TABLE_NAME)}else if($==="sqlite")Z=(await m`
177
178
  SELECT name
178
179
  FROM sqlite_master
179
180
  WHERE type = 'table'
180
181
  AND name NOT LIKE 'sqlite_%'
181
- `).map((L)=>L.name);if(X.length===0){console.log("No tables found to drop.");return}if($.verbose)console.log(`Found ${X.length} tables: ${X.join(", ")}`);if(Z==="postgres")for(let _ of X){if($.verbose)console.log(`Dropping table: ${_}`);await x`DROP TABLE IF EXISTS ${x(_)} CASCADE`}else if(Z==="mysql"){await x`SET FOREIGN_KEY_CHECKS = 0`;for(let _ of X){if($.verbose)console.log(`Dropping table: ${_}`);await x`DROP TABLE IF EXISTS ${x(_)}`}await x`SET FOREIGN_KEY_CHECKS = 1`}else if(Z==="sqlite"){await x`PRAGMA foreign_keys = OFF`;for(let _ of X){if($.verbose)console.log(`Dropping table: ${_}`);await x`DROP TABLE IF EXISTS ${x(_)}`}await x`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${X.length} tables`)}catch(X){throw console.error("Error wiping database:",X.message),X}}var aL=n(()=>{G8()});async function GE($){let _=await(W0().raw([$]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(_,null,2)),_}var eL=n(()=>{P0()});async function KE($,Z={}){let X=W0(),_=Z.params?JSON.parse(Z.params):void 0,L=await X.file($,_);return console.log(JSON.stringify(L)),L}var $j=n(()=>{P0()});async function Zj($,Z={}){let X=y.dialect||"postgres",_=Z.verbose??!0;if(_)console.log(`-- Inspecting table: ${$}`),console.log(`-- Dialect: ${X}`),console.log();try{let L=W0(),j=[],Y=[],z=await L.unsafe(`SELECT COUNT(*) as count FROM ${$}`),F=Number(z[0]?.count||0);if(X==="postgres"){let E=await L.unsafe(`
182
+ `).map((U)=>U.name);if(Z.length===0){console.log("No tables found to drop.");return}if(X.verbose)console.log(`Found ${Z.length} tables: ${Z.join(", ")}`);if($==="postgres")for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)} CASCADE`}else if(J0($)){await m`SET FOREIGN_KEY_CHECKS = 0`;for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)}`}await m`SET FOREIGN_KEY_CHECKS = 1`}else if($==="sqlite"){await m`PRAGMA foreign_keys = OFF`;for(let Y of Z){if(X.verbose)console.log(`Dropping table: ${Y}`);await m`DROP TABLE IF EXISTS ${m(Y)}`}await m`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${Z.length} tables`)}catch(Z){throw console.error("Error wiping database:",Z.message),Z}}var XQ=e(()=>{d0(),$X()});async function yG(X){let Y=await(K0().raw([X]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(Y,null,2)),Y}var $Q=e(()=>{y0()});async function hG(X,$={}){let Z=K0(),Y=$.params?JSON.parse($.params):void 0,U=await Z.file(X,Y);return console.log(JSON.stringify(U)),U}var ZQ=e(()=>{y0()});async function YQ(X,$={}){let Z=f.dialect||"postgres",Y=$.verbose??!0;if(Y)console.log(`-- Inspecting table: ${X}`),console.log(`-- Dialect: ${Z}`),console.log();try{let U=K0(),_=[],Q=[],L=await U.unsafe(`SELECT COUNT(*) as count FROM ${X}`),z=Number(L[0]?.count||0);if(Z==="postgres"){let j=await U.unsafe(`
182
183
  SELECT
183
184
  c.column_name,
184
185
  c.data_type,
@@ -211,7 +212,7 @@ Goodbye!`),N1.exit(0)}),Z.prompt()}async function LE(){return uL()}var nL=n(()=>
211
212
  ) fk ON c.column_name = fk.column_name
212
213
  WHERE c.table_name = $1
213
214
  ORDER BY c.ordinal_position
214
- `,[$]);for(let V of E)j.push({name:V.column_name,type:V.data_type,nullable:V.is_nullable==="YES",default:V.column_default,isPrimaryKey:V.is_primary_key,isForeignKey:V.is_foreign_key});let U=await L.unsafe(`
215
+ `,[X]);for(let V of j)_.push({name:V.column_name,type:V.data_type,nullable:V.is_nullable==="YES",default:V.column_default,isPrimaryKey:V.is_primary_key,isForeignKey:V.is_foreign_key});let E=await U.unsafe(`
215
216
  SELECT
216
217
  i.indexname as name,
217
218
  i.indexdef,
@@ -220,7 +221,7 @@ Goodbye!`),N1.exit(0)}),Z.prompt()}async function LE(){return uL()}var nL=n(()=>
220
221
  JOIN pg_class c ON c.relname = i.indexname
221
222
  JOIN pg_index ix ON ix.indexrelid = c.oid
222
223
  WHERE i.tablename = $1
223
- `,[$]);for(let V of U){let Q=V.indexdef?.match(/\(([^)]+)\)/),K=(Q?Q[1]:"").split(",").map((I)=>I.trim());Y.push({name:V.name,columns:K,unique:V.is_unique})}}else if(X==="mysql"){let E=await L.unsafe(`
224
+ `,[X]);for(let V of E){let G=V.indexdef?.match(/\(([^)]+)\)/),W=(G?G[1]:"").split(",").map((F)=>F.trim());Q.push({name:V.name,columns:W,unique:V.is_unique})}}else if(J0(Z)){let j=await U.unsafe(`
224
225
  SELECT
225
226
  COLUMN_NAME as column_name,
226
227
  DATA_TYPE as data_type,
@@ -231,19 +232,68 @@ Goodbye!`),N1.exit(0)}),Z.prompt()}async function LE(){return uL()}var nL=n(()=>
231
232
  WHERE TABLE_NAME = ?
232
233
  AND TABLE_SCHEMA = DATABASE()
233
234
  ORDER BY ORDINAL_POSITION
234
- `,[$]);for(let Q of E)j.push({name:Q.column_name,type:Q.data_type,nullable:Q.is_nullable==="YES",default:Q.column_default,isPrimaryKey:Q.column_key==="PRI",isForeignKey:Q.column_key==="MUL"});let U=await L.unsafe(`
235
- SHOW INDEXES FROM ${$}
236
- `),V=new Map;for(let Q of U){let O=Q.Key_name;if(!V.has(O))V.set(O,{columns:[],unique:Q.Non_unique===0});V.get(O).columns.push(Q.Column_name)}for(let[Q,O]of V)Y.push({name:Q,columns:O.columns,unique:O.unique})}else if(X==="sqlite"){let E=await L.unsafe(`PRAGMA table_info(${$})`);for(let V of E)j.push({name:V.name,type:V.type,nullable:V.notnull===0,default:V.dflt_value,isPrimaryKey:V.pk===1});let U=await L.unsafe(`PRAGMA index_list(${$})`);for(let V of U){let Q=await L.unsafe(`PRAGMA index_info(${V.name})`);Y.push({name:V.name,columns:Q.map((O)=>O.name),unique:V.unique===1})}}if(_){console.log(`Table: ${$}`),console.log(`Rows: ${F.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let E=Math.max(...j.map((K)=>K.name.length),10),U=Math.max(...j.map((K)=>K.type.length),10),V=E+2,Q=U+2,O=`${"Name".padEnd(V)+"Type".padEnd(Q)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(O),console.log("-".repeat(O.length));for(let K of j){let I=K.name.padEnd(V),C=K.type.padEnd(Q),D=(K.nullable?"YES":"NO").padEnd(10),M=String(K.default||"").padEnd(20),J=[K.isPrimaryKey?"PK":"",K.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${I}${C}${D}${M}${J}`)}if(console.log(),Y.length>0){console.log("Indexes:"),console.log();for(let K of Y){let I=K.unique?" (UNIQUE)":"";console.log(` - ${K.name}${I}: [${K.columns.join(", ")}]`)}console.log()}}return{tableName:$,rowCount:F,columns:j,indexes:Y}}catch(L){throw console.error(`-- Failed to inspect table ${$}:`,L),L}}async function IE($,Z={}){return Zj($,Z)}var Xj=n(()=>{F9(),P0()});async function WE($,Z={}){let X=await W8({modelsDir:$}),_=AX(X);return console.log(JSON.stringify(_,null,2)),{models:X,schema:_}}var _j=n(()=>{P0()});function Yj($){let Z=$;while(Z!==o6(Z)){if(XZ(_Z(Z,"package.json")))return Z;Z=o6(Z)}return N2.cwd()}async function RE($,Z={}){let X=Yj(N2.cwd()),_=Z.dir||_Z(X,"app/Models");if(!XZ(_))Lj(_,{recursive:!0}),console.log(`-- Created models directory: ${_}`);let L=$.charAt(0).toUpperCase()+$.slice(1),j=Z.table||`${$.toLowerCase()}s`,Y=`${L}.ts`,z=_Z(_,Y);if(XZ(z))throw console.error(`-- Model already exists: ${z}`),Error(`Model already exists: ${z}`);let E=Z.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
237
- updated_at: { validation: { rule: v.date() } },`:"",U=`import { v } from '@stacksjs/ts-validation'
235
+ `,[X]);for(let G of j)_.push({name:G.column_name,type:G.data_type,nullable:G.is_nullable==="YES",default:G.column_default,isPrimaryKey:G.column_key==="PRI",isForeignKey:G.column_key==="MUL"});let E=await U.unsafe(`
236
+ SHOW INDEXES FROM ${X}
237
+ `),V=new Map;for(let G of E){let J=G.Key_name;if(!V.has(J))V.set(J,{columns:[],unique:G.Non_unique===0});V.get(J).columns.push(G.Column_name)}for(let[G,J]of V)Q.push({name:G,columns:J.columns,unique:J.unique})}else if(Z==="sqlite"){let j=await U.unsafe(`PRAGMA table_info(${X})`);for(let V of j)_.push({name:V.name,type:V.type,nullable:V.notnull===0,default:V.dflt_value,isPrimaryKey:V.pk===1});let E=await U.unsafe(`PRAGMA index_list(${X})`);for(let V of E){let G=await U.unsafe(`PRAGMA index_info(${V.name})`);Q.push({name:V.name,columns:G.map((J)=>J.name),unique:V.unique===1})}}if(Y){console.log(`Table: ${X}`),console.log(`Rows: ${z.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let j=Math.max(..._.map((W)=>W.name.length),10),E=Math.max(..._.map((W)=>W.type.length),10),V=j+2,G=E+2,J=`${"Name".padEnd(V)+"Type".padEnd(G)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(J),console.log("-".repeat(J.length));for(let W of _){let F=W.name.padEnd(V),K=W.type.padEnd(G),D=(W.nullable?"YES":"NO").padEnd(10),w=String(W.default||"").padEnd(20),T=[W.isPrimaryKey?"PK":"",W.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${F}${K}${D}${w}${T}`)}if(console.log(),Q.length>0){console.log("Indexes:"),console.log();for(let W of Q){let F=W.unique?" (UNIQUE)":"";console.log(` - ${W.name}${F}: [${W.columns.join(", ")}]`)}console.log()}}return{tableName:X,rowCount:z,columns:_,indexes:Q}}catch(U){throw console.error(`-- Failed to inspect table ${X}:`,U),U}}async function vG(X,$={}){return YQ(X,$)}var UQ=e(()=>{d0(),y0()});async function bG(X,$={}){let Z=await dX({modelsDir:X}),Y=K7(Z);return console.log(JSON.stringify(Y,null,2)),{models:Z,schema:Y}}var _Q=e(()=>{y0()});function QQ(X){let $=X.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 zQ(X){if(/ies$/i.test(X))return X.replace(/ies$/i,"y");if(/ses$/i.test(X))return X.replace(/es$/i,"");if(/s$/i.test(X)&&!/ss$/i.test(X))return X.replace(/s$/i,"");return X}function LQ(X){return X.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join("")}function QU(X){return LQ(zQ(X))}async function zU(X,$){if($==="postgres")return(await X.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((U)=>U.table_name);if(J0($))return(await X.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((U)=>U.table_name??U.TABLE_NAME);return(await X.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((Y)=>Y.name)}async function jQ(X,$,Z){if($==="sqlite")return(await X.unsafe(`PRAGMA table_info(${Z})`)).map((_)=>({name:_.name,sqlType:String(_.type||""),nullable:Number(_.notnull)===0,isPrimaryKey:Number(_.pk)>0}));if($==="postgres")return(await X.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
238
+ (SELECT COUNT(*) FROM information_schema.table_constraints tc
239
+ JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
240
+ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
241
+ FROM information_schema.columns c
242
+ WHERE c.table_name = $1 AND c.table_schema = 'public'
243
+ ORDER BY c.ordinal_position`,[Z])).map((_)=>({name:_.column_name,sqlType:String(_.data_type||""),nullable:String(_.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(_.is_pk)>0}));return(await X.unsafe(`SELECT column_name, data_type, is_nullable, column_key
244
+ FROM information_schema.columns
245
+ WHERE table_name = ? AND table_schema = DATABASE()
246
+ ORDER BY ordinal_position`,[Z])).map((U)=>({name:U.column_name??U.COLUMN_NAME,sqlType:String(U.data_type??U.DATA_TYPE??""),nullable:String(U.is_nullable??U.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(U.column_key??U.COLUMN_KEY).toUpperCase()==="PRI"}))}function EQ(X,$){let Z=QU(X),Y=$.find((_)=>_.isPrimaryKey)?.name??"id",U=$.map((_)=>{let Q=[`type: '${QQ(_.sqlType)}'`];if(!_.nullable&&!_.isPrimaryKey)Q.push("required: true");return` ${_.name}: { ${Q.join(", ")} },`}).join(`
247
+ `);return`export const ${Z} = defineModel({
248
+ name: '${Z}',
249
+ table: '${X}',
250
+ primaryKey: '${Y}',
251
+ attributes: {
252
+ ${U}
253
+ },
254
+ })
255
+ `}async function fG(X={}){let $=f.dialect||"postgres",Z=K0(),Y=X.tables?.length?X.tables:await zU(Z,$),U=[];for(let _ of Y){let Q=await jQ(Z,$,_);if(!Q.length)continue;U.push({table:_,modelName:QU(_),primaryKey:Q.find((L)=>L.isPrimaryKey)?.name??"id",columns:Q,source:EQ(_,Q)})}return U}function X5(X,$,Z){if(Z?.enumValues&&Z.enumValues.length>0)return"enum";let Y=String(X||"").toLowerCase().trim(),U=Y.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(J0($)&&/^tinyint\(1\)/.test(Y))return"boolean";if(/^bool/.test(U))return"boolean";if(U==="int8"||U==="bigint"||U==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(U))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(U)){let _=Y.match(/\((\d+)\)/),Q=_?Number(_[1]):void 0;return Q!==void 0&&Q>255?"text":"string"}if(/text|clob/.test(U))return"text";if(U==="float8"||/^double/.test(U))return"double";if(/^(?:real|float4|float)/.test(U))return"float";if(/^(?:numeric|decimal|money)/.test(U))return"decimal";if(U==="date")return"date";if(/^(?:timestamp|datetime)/.test(U))return"datetime";if(/^time/.test(U))return"string";if(/json/.test(U))return"json";if(/^enum/.test(U))return"enum";return"string"}function LU(X,$){let Z=`${$}_`;return X.startsWith(Z)?X.slice(Z.length):X}function yX(X){let $=String(X??"").toLowerCase().trim();if($==="cascade"||$==="restrict"||$==="set null")return $;return}async function GQ(X,$){let Z=await X.unsafe(`PRAGMA table_info(${JSON.stringify($)})`),Y=await X.unsafe(`PRAGMA index_list(${JSON.stringify($)})`),U=await X.unsafe(`PRAGMA foreign_key_list(${JSON.stringify($)})`),_=await X.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[$]),Q=String(_?.[0]?.sql??""),L=new Map;for(let V of U)L.set(String(V.from),{table:String(V.table),column:String(V.to??"id"),onDelete:yX(V.on_delete),onUpdate:yX(V.on_update)});let z=[],j=new Set;for(let V of Y){let G=String(V.origin??""),J=String(V.name??"");if(G==="pk"||J.startsWith("sqlite_autoindex_"))continue;let F=(await X.unsafe(`PRAGMA index_info(${JSON.stringify(J)})`)).map((D)=>String(D.name)).filter(Boolean);if(F.length===0)continue;let K=Number(V.unique)===1;if(K&&F.length===1)j.add(F[0]);z.push({name:LU(J,$),columns:F,type:K?"unique":"index"})}let E=Z.map((V)=>{let G=String(V.name),J=FQ(Q,G),W=Number(V.pk)>0,F=V.dflt_value,K=F!==null&&F!==void 0;return{name:G,type:X5(String(V.type??""),"sqlite",{enumValues:J}),isPrimaryKey:W,isUnique:j.has(G),isNullable:W?!1:Number(V.notnull)===0,hasDefault:K,defaultValue:K?$5(F):void 0,enumValues:J,references:L.get(G)}});return{table:$,columns:E,indexes:z}}function FQ(X,$){if(!X)return;let Z=new RegExp(`(?:"${$}"|\`${$}\`|\\b${$}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),Y=X.match(Z);if(!Y)return;let U=Y[1].split(",").map((_)=>_.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((_)=>_.length>0);return U.length>0?U:void 0}function $5(X){if(typeof X==="number"||typeof X==="boolean")return X;return String(X)}async function OQ(X,$){let Z=await X.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
256
+ (SELECT COUNT(*) FROM information_schema.table_constraints tc
257
+ JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
258
+ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
259
+ FROM information_schema.columns c
260
+ WHERE c.table_name = $1 AND c.table_schema = 'public'
261
+ ORDER BY c.ordinal_position`,[$]),Y=await X.unsafe(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
262
+ a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
263
+ pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
264
+ FROM pg_class t
265
+ JOIN pg_index ix ON t.oid = ix.indrelid
266
+ JOIN pg_class i ON i.oid = ix.indexrelid
267
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
268
+ WHERE t.relname = $1 AND t.relkind = 'r'
269
+ ORDER BY i.relname, ord`,[$]),U=await X.unsafe(`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column,
270
+ rc.delete_rule, rc.update_rule
271
+ FROM information_schema.table_constraints tc
272
+ JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
273
+ JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
274
+ JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
275
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[$]),_=new Map;for(let j of U)_.set(String(j.column_name),{table:String(j.ref_table),column:String(j.ref_column??"id"),onDelete:yX(j.delete_rule),onUpdate:yX(j.update_rule)});let{indexes:Q,uniqueColumns:L}=jU($,Y.map((j)=>({indexName:String(j.index_name),isUnique:j.is_unique===!0||j.is_unique==="t",isPrimary:j.is_primary===!0||j.is_primary==="t",column:String(j.column_name),where:j.where_clause?String(j.where_clause):void 0}))),z=Z.map((j)=>{let E=String(j.column_name),V=Number(j.is_pk)>0,G=j.column_default==null?null:String(j.column_default),J=G!=null&&/nextval\(/i.test(G),W=G!=null&&!J;return{name:E,type:X5(String(j.data_type??j.udt_name??""),"postgres"),isPrimaryKey:V,isUnique:L.has(E),isNullable:V?!1:String(j.is_nullable).toUpperCase()==="YES",hasDefault:W,defaultValue:W?$5(G):void 0,references:_.get(E)}});return{table:$,columns:z,indexes:Q}}async function JQ(X,$){let Z=await X.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
276
+ FROM information_schema.columns
277
+ WHERE table_name = ? AND table_schema = DATABASE()
278
+ ORDER BY ordinal_position`,[$]),Y=await X.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
279
+ FROM information_schema.statistics
280
+ WHERE table_name = ? AND table_schema = DATABASE()
281
+ ORDER BY index_name, seq_in_index`,[$]),U=await X.unsafe(`SELECT kcu.column_name, kcu.referenced_table_name AS ref_table, kcu.referenced_column_name AS ref_column,
282
+ rc.delete_rule, rc.update_rule
283
+ FROM information_schema.key_column_usage kcu
284
+ JOIN information_schema.referential_constraints rc
285
+ ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
286
+ WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[$]),_=new Map;for(let j of U)_.set(String(j.column_name??j.COLUMN_NAME),{table:String(j.ref_table??j.REF_TABLE),column:String(j.ref_column??j.REF_COLUMN??"id"),onDelete:yX(j.delete_rule??j.DELETE_RULE),onUpdate:yX(j.update_rule??j.UPDATE_RULE)});let{indexes:Q,uniqueColumns:L}=jU($,Y.map((j)=>({indexName:String(j.index_name??j.INDEX_NAME),isUnique:Number(j.non_unique??j.NON_UNIQUE)===0,isPrimary:String(j.index_name??j.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(j.column_name??j.COLUMN_NAME)}))),z=Z.map((j)=>{let E=String(j.column_name??j.COLUMN_NAME),V=String(j.column_type??j.COLUMN_TYPE??""),G=WQ(V),W=String(j.column_key??j.COLUMN_KEY??"").toUpperCase()==="PRI",F=j.column_default??j.COLUMN_DEFAULT,K=F!=null;return{name:E,type:X5(String(j.data_type??j.DATA_TYPE??V),"mysql",{enumValues:G}),isPrimaryKey:W,isUnique:L.has(E),isNullable:W?!1:String(j.is_nullable??j.IS_NULLABLE).toUpperCase()==="YES",hasDefault:K,defaultValue:K?$5(F):void 0,enumValues:G,references:_.get(E)}});return{table:$,columns:z,indexes:Q}}function WQ(X){let $=X.match(/^enum\((.*)\)$/i);if(!$)return;return $[1].split(",").map((Z)=>Z.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((Z)=>Z.length>0)}function jU(X,$){let Z=new Map;for(let _ of $){if(_.isPrimary)continue;let Q=Z.get(_.indexName)??{isUnique:_.isUnique,isPrimary:_.isPrimary,columns:[],where:_.where};Q.columns.push(_.column),Z.set(_.indexName,Q)}let Y=[],U=new Set;for(let[_,Q]of Z){if(Q.columns.length===0)continue;if(Q.isUnique&&Q.columns.length===1)U.add(Q.columns[0]);Y.push({name:LU(_,X),columns:Q.columns,type:Q.isUnique?"unique":"index",where:Q.where})}return{indexes:Y,uniqueColumns:U}}async function VQ(X,$={}){let Z=X||f.dialect||"postgres",Y=K0(),_=(($.tables?.length)?$.tables:await zU(Y,Z)).filter((L)=>L!=="migrations"),Q=[];for(let L of _){let z;if(Z==="sqlite")z=await GQ(Y,L);else if(Z==="postgres")z=await OQ(Y,L);else z=await JQ(Y,L);if(z.columns.length>0)Q.push(z)}return{dialect:Z,tables:Q}}var EU=e(()=>{d0(),y0()});function RQ(X){let $=X;while($!==AY($)){if(P1(T1($,"package.json")))return $;$=AY($)}return GU.cwd()}async function cG(X,$={}){let Z=RQ(GU.cwd()),Y=$.dir||T1(Z,"app/Models");if(!P1(Y))IQ(Y,{recursive:!0}),console.log(`-- Created models directory: ${Y}`);let U=X.charAt(0).toUpperCase()+X.slice(1),_=$.table||`${X.toLowerCase()}s`,Q=`${U}.ts`,L=T1(Y,Q);if(P1(L))throw console.error(`-- Model already exists: ${L}`),Error(`Model already exists: ${L}`);let j=$.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
287
+ updated_at: { validation: { rule: v.date() } },`:"",E=`import { v } from '@stacksjs/ts-validation'
238
288
  import { defineModel } from 'bun-query-builder'
239
289
 
240
290
  const model = defineModel({
241
- name: '${L}',
242
- table: '${j}',
291
+ name: '${U}',
292
+ table: '${_}',
243
293
  primaryKey: 'id',
244
294
  attributes: {
245
295
  id: { validation: { rule: v.integer() } },
246
- ${E}
296
+ ${j}
247
297
  // Add your model attributes here
248
298
  // Example:
249
299
  // name: { validation: { rule: v.string() } },
@@ -253,52 +303,62 @@ ${E}
253
303
  })
254
304
 
255
305
  export default model
256
- `;jj(z,U),console.log(`-- \u2713 Created model: ${z}`),console.log(`-- Table: ${j}`)}var Fj=()=>{};class P2{quoteIdentifier($){return`\`${$.replace(/`/g,"``")}\``}getColumnType($){switch($.type){case"string":return"varchar(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"json":return"json";case"enum":if($.enumValues&&$.enumValues.length>0)return`ENUM(${$.enumValues.map((X)=>`'${X.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType($){return this.getColumnType($)}getAutoIncrementClause($){if($.isPrimaryKey&&($.type==="integer"||$.type==="bigint"))return"auto_increment";return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let Z=$.defaultValue;if(typeof Z==="string"){let X=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],_=Z.toUpperCase();if(X.includes(_))return`default ${_}`;return`default '${Z.replace(/'/g,"''")}'`}else if(typeof Z==="number"||typeof Z==="bigint")return`default ${Z}`;else if(typeof Z==="boolean")return`default ${Z?1:0}`;else if(Z instanceof Date)return`default '${Z.toISOString()}'`;return""}createEnumType($,Z){return""}createTable($){let Z=$.columns.map((X)=>this.renderColumn(X)).join(`,
257
- `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
258
- ${Z}
259
- );`}createIndex($,Z){if(Z.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${Z.name}' on table '${$}' uses WHERE clause: ${Z.where}`);let X=Z.type==="unique"?"UNIQUE ":"",_=`${$}_${Z.name}`,L=Z.columns.map((j)=>this.quoteIdentifier(j)).join(", ");return`CREATE ${X}INDEX ${this.quoteIdentifier(_)} ON ${this.quoteIdentifier($)} (${L});`}addForeignKey($,Z,X,_,L,j){let Y=`${$}_${Z}_fk`,z=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(Y)} FOREIGN KEY (${this.quoteIdentifier(Z)}) REFERENCES ${this.quoteIdentifier(X)}(${this.quoteIdentifier(_)})`;if(L)z+=` ON DELETE ${L.toUpperCase()}`;if(j)z+=` ON UPDATE ${j.toUpperCase()}`;return`${z};`}addColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let L=this.getDefaultValue(Z);if(L)_.push(L);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${_.join(" ")};`}modifyColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let L=this.getDefaultValue(Z);if(L)_.push(L);return`ALTER TABLE ${this.quoteIdentifier($)} MODIFY COLUMN ${_.join(" ")};`}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,Z){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(Z)};`}dropIndex($,Z){let X=`${$}_${Z}`;return`DROP INDEX ${this.quoteIdentifier(X)} ON ${this.quoteIdentifier($)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
306
+ `;KQ(L,E),console.log(`-- \u2713 Created model: ${L}`),console.log(`-- Table: ${_}`)}var DQ=()=>{};class Z5{quoteIdentifier(X){return`\`${X.replace(/`/g,"``")}\``}getColumnType(X){switch(X.type){case"string":return`varchar(${X.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"json":return"json";case"enum":if(X.enumValues&&X.enumValues.length>0)return`ENUM(${X.enumValues.map((Z)=>`'${Z.replace(/'/g,"''")}'`).join(", ")})`;return"text";default:return"text"}}getPrimaryKeyType(X){return this.getColumnType(X)}getAutoIncrementClause(X){if(X.isPrimaryKey&&(X.type==="integer"||X.type==="bigint"))return"auto_increment";return""}getDefaultValue(X){if(!X.hasDefault||X.defaultValue===void 0)return"";let $=X.defaultValue;if(typeof $==="string"){let Z=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],Y=$.toUpperCase();if(Z.includes(Y))return`default ${Y}`;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(X,$){return""}createTable(X){let $=X.columns.map((Z)=>this.renderColumn(Z)).join(`,
307
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(X.table)} (
308
+ ${$}
309
+ );`}createIndex(X,$){if($.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${$.name}' on table '${X}' uses WHERE clause: ${$.where}`);let Z=$.type==="unique"?"UNIQUE ":"",Y=`${X}_${$.name}`,U=$.columns.map((_)=>this.quoteIdentifier(_)).join(", ");return`CREATE ${Z}INDEX ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(X)} (${U});`}addForeignKey(X,$,Z,Y,U,_){let Q=`${X}_${$}_fk`,L=`ALTER TABLE ${this.quoteIdentifier(X)} ADD CONSTRAINT ${this.quoteIdentifier(Q)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Z)}(${this.quoteIdentifier(Y)})`;if(U)L+=` ON DELETE ${U.toUpperCase()}`;if(_)L+=` ON UPDATE ${_.toUpperCase()}`;return`${L};`}addColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} ADD COLUMN ${Y.join(" ")};`}modifyColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} MODIFY COLUMN ${Y.join(" ")};`}renameColumn(X,$,Z){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Z)};`}renameTable(X,$){return`RENAME TABLE ${this.quoteIdentifier(X)} TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable(X){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(X)}`}dropColumn(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(X,$){let Z=`${X}_${$}`;return`DROP INDEX ${this.quoteIdentifier(Z)} ON ${this.quoteIdentifier(X)};`}dropEnumType(X){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
260
310
  id INT AUTO_INCREMENT PRIMARY KEY,
261
311
  migration VARCHAR(255) NOT NULL UNIQUE,
262
312
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
263
- )`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn($){let Z=this.getColumnType($),X=[this.quoteIdentifier($.name),Z];if($.isPrimaryKey){X.push("PRIMARY KEY");let L=this.getAutoIncrementClause($);if(L)X.push(L)}if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let _=this.getDefaultValue($);if(_)X.push(_);return X.join(" ")}}class T2{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){switch($.type){case"string":return"varchar(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"json":return"jsonb";case"enum":if($.enumValues&&$.enumValues.length>0)return`${$.name}_type`;return"text";default:return"text"}}getPrimaryKeyType($){switch($.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType($)}}getAutoIncrementClause($){return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let Z=$.defaultValue;if(typeof Z==="string"){let X=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],_=Z.toUpperCase();if(X.includes(_))return`default ${_}`;return`default '${Z.replace(/'/g,"''")}'`}else if(typeof Z==="number"||typeof Z==="bigint")return`default ${Z}`;else if(typeof Z==="boolean")return`default ${Z?"true":"false"}`;else if(Z instanceof Date)return`default '${Z.toISOString()}'`;return""}createEnumType($,Z){let X=Z.map((_)=>`'${_.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier($)} AS ENUM (${X});`}createTable($){let Z=$.columns.map((X)=>this.renderColumn(X)).join(`,
264
- `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
265
- ${Z}
266
- );`}createIndex($,Z){let X=Z.type==="unique"?"UNIQUE ":"",_=`${$}_${Z.name}`,L=Z.columns.map((Y)=>this.quoteIdentifier(Y)).join(", "),j=Z.where?` WHERE ${Z.where}`:"";return`CREATE ${X}INDEX IF NOT EXISTS ${this.quoteIdentifier(_)} ON ${this.quoteIdentifier($)} (${L})${j};`}addForeignKey($,Z,X,_,L,j){let Y=`${$}_${Z}_fk`,z=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(Y)} FOREIGN KEY (${this.quoteIdentifier(Z)}) REFERENCES ${this.quoteIdentifier(X)}(${this.quoteIdentifier(_)})`;if(L)z+=` ON DELETE ${L.toUpperCase()}`;if(j)z+=` ON UPDATE ${j.toUpperCase()}`;return`${z};`}addColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let L=this.getDefaultValue(Z);if(L)_.push(L);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${_.join(" ")};`}modifyColumn($,Z){let X=this.getColumnType(Z);return`ALTER TABLE ${this.quoteIdentifier($)} ALTER COLUMN ${this.quoteIdentifier(Z.name)} TYPE ${X} USING ${this.quoteIdentifier(Z.name)}::${X};`}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}dropColumn($,Z){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(Z)};`}dropIndex($,Z){let X=`${$}_${Z}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(X)};`}dropEnumType($){return`DROP TYPE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
313
+ )`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(X){let $=this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey){Z.push("PRIMARY KEY");let U=this.getAutoIncrementClause(X);if(U)Z.push(U)}if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);return Z.join(" ")}}class FU{quoteIdentifier(X){return`"${X.replace(/"/g,'""')}"`}getColumnType(X){switch(X.type){case"string":return`varchar(${X.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"json":return"jsonb";case"enum":if(X.enumValues&&X.enumValues.length>0)return this.quoteIdentifier(X.enumTypeName??`${X.name}_type`);return"text";default:return"text"}}getPrimaryKeyType(X){switch(X.type){case"integer":return"SERIAL";case"bigint":return"BIGSERIAL";default:return this.getColumnType(X)}}getAutoIncrementClause(X){return""}getDefaultValue(X){if(!X.hasDefault||X.defaultValue===void 0)return"";let $=X.defaultValue;if(typeof $==="string"){let Z=["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"],Y=$.toUpperCase();if(Z.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(X,$){let Z=$.map((Y)=>`'${Y.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier(X)} AS ENUM (${Z});`}createTable(X){let $=X.columns.map((Z)=>this.renderColumn(Z)).join(`,
314
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(X.table)} (
315
+ ${$}
316
+ );`}createIndex(X,$){let Z=$.type==="unique"?"UNIQUE ":"",Y=`${X}_${$.name}`,U=$.columns.map((Q)=>this.quoteIdentifier(Q)).join(", "),_=$.where?` WHERE ${$.where}`:"";return`CREATE ${Z}INDEX IF NOT EXISTS ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(X)} (${U})${_};`}addForeignKey(X,$,Z,Y,U,_){let Q=`${X}_${$}_fk`,L=`ALTER TABLE ${this.quoteIdentifier(X)} ADD CONSTRAINT ${this.quoteIdentifier(Q)} FOREIGN KEY (${this.quoteIdentifier($)}) REFERENCES ${this.quoteIdentifier(Z)}(${this.quoteIdentifier(Y)})`;if(U)L+=` ON DELETE ${U.toUpperCase()}`;if(_)L+=` ON UPDATE ${_.toUpperCase()}`;return`${L};`}addColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} ADD COLUMN ${Y.join(" ")};`}modifyColumn(X,$){let Z=this.getColumnType($);return`ALTER TABLE ${this.quoteIdentifier(X)} ALTER COLUMN ${this.quoteIdentifier($.name)} TYPE ${Z} USING ${this.quoteIdentifier($.name)}::${Z};`}renameColumn(X,$,Z){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Z)};`}renameTable(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable(X){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(X)} CASCADE`}dropColumn(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(X,$){let Z=`${X}_${$}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Z)};`}dropEnumType(X){return`DROP TYPE IF EXISTS ${this.quoteIdentifier(X)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
267
317
  id SERIAL PRIMARY KEY,
268
318
  migration VARCHAR(255) NOT NULL UNIQUE,
269
319
  executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
270
- )`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}renderColumn($){let Z=$.isPrimaryKey?this.getPrimaryKeyType($):this.getColumnType($),X=[this.quoteIdentifier($.name),Z];if($.isPrimaryKey)X.push("PRIMARY KEY");if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let _=this.getDefaultValue($);if(_)X.push(_);return X.join(" ")}}class k2{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){if($.name.endsWith("_id"))return"INTEGER";switch($.type){case"string":return"TEXT";case"text":return"TEXT";case"boolean":return"INTEGER";case"integer":return"INTEGER";case"bigint":return"INTEGER";case"float":return"REAL";case"double":return"REAL";case"decimal":return"REAL";case"date":return"TEXT";case"datetime":return"TEXT";case"json":return"TEXT";case"enum":if($.enumValues&&$.enumValues.length>0){let Z=$.enumValues.map((X)=>`'${X.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier($.name)} IN (${Z}))`}return"TEXT";default:return"TEXT"}}getPrimaryKeyType($){return this.getColumnType($)}getAutoIncrementClause($){if($.isPrimaryKey&&($.type==="integer"||$.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let Z=$.defaultValue;if(typeof Z==="string"){if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(Z.toUpperCase()))return`default ${Z.toUpperCase()}`;return`default '${Z.replace(/'/g,"''")}'`}else if(typeof Z==="number"||typeof Z==="bigint")return`default ${Z}`;else if(typeof Z==="boolean")return`default ${Z?1:0}`;else if(Z instanceof Date)return`default '${Z.toISOString()}'`;return""}createEnumType($,Z){return""}createTable($){let Z=$.columns.map((X)=>this.renderColumn(X)).join(`,
271
- `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
272
- ${Z}
273
- );`}createIndex($,Z){let X=Z.type==="unique"?"UNIQUE ":"",_=`${$}_${Z.name}`,L=Z.columns.map((Y)=>this.quoteIdentifier(Y)).join(", "),j=Z.where?` WHERE ${Z.where}`:"";return`CREATE ${X}INDEX IF NOT EXISTS ${this.quoteIdentifier(_)} ON ${this.quoteIdentifier($)} (${L})${j};`}addForeignKey($,Z,X,_,L,j){let Y=`${$}_${Z}_fk`,z=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(Y)} FOREIGN KEY (${this.quoteIdentifier(Z)}) REFERENCES ${this.quoteIdentifier(X)}(${this.quoteIdentifier(_)})`;if(L)z+=` ON DELETE ${L.toUpperCase()}`;if(j)z+=` ON UPDATE ${j.toUpperCase()}`;return`${z};`}addColumn($,Z){let X=this.getColumnType(Z),_=[this.quoteIdentifier(Z.name),X];if(!Z.isNullable&&!Z.isPrimaryKey)_.push("not null");let L=this.getDefaultValue(Z);if(L)_.push(L);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${_.join(" ")};`}modifyColumn($,Z){return`-- SQLite does not support ALTER COLUMN. Manual table recreation needed to change ${this.quoteIdentifier($)}.${this.quoteIdentifier(Z.name)} type`}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,Z){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(Z)};`}dropIndex($,Z){let X=`${$}_${Z}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(X)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
320
+ )`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}renderColumn(X){let $=X.isPrimaryKey?this.getPrimaryKeyType(X):this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey)Z.push("PRIMARY KEY");if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);return Z.join(" ")}}var OU,kY=e(()=>{OU=class extends Z5{createTable($){let Z=$.columns.map((Q)=>this.renderColumn(Q)).join(`,
321
+ `),Y=[];if($.tableKind!=="reference"){let Q=$.shardKey?.length?$.shardKey:$.columns.filter((L)=>L.isPrimaryKey).map((L)=>L.name);if(Q&&Q.length>0)Y.push(`SHARD KEY (${Q.map((L)=>this.quoteIdentifier(L)).join(", ")})`)}if($.tableKind!=="rowstore"&&$.tableKind!=="reference"){let Q=$.sortKey?.length?$.sortKey:void 0;Y.push(`SORT KEY (${(Q??[]).map((L)=>this.quoteIdentifier(L)).join(", ")})`)}let U=[Z,...Y].join(`,
322
+ `);return`CREATE${this.tableKindSuffix($.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
323
+ ${U}
324
+ );`}tableKindSuffix($){switch($){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex($,Z){if(Z.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${Z.name}' on table '${$}' uses WHERE clause: ${Z.where}`);return super.createIndex($,Z)}}});function JU(X){return X==="integer"||X==="bigint"||X==="float"||X==="double"||X==="decimal"}class WU{quoteIdentifier(X){return`"${X.replace(/"/g,'""')}"`}getColumnType(X){if(X.name.endsWith("_id")&&JU(X.type))return"INTEGER";switch(X.type){case"string":return"TEXT";case"text":return"TEXT";case"boolean":return"INTEGER";case"integer":return"INTEGER";case"bigint":return"INTEGER";case"float":return"REAL";case"double":return"REAL";case"decimal":return"REAL";case"date":return"TEXT";case"datetime":return"TEXT";case"json":return"TEXT";case"enum":if(X.enumValues&&X.enumValues.length>0){let $=X.enumValues.map((Z)=>`'${Z.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier(X.name)} IN (${$}))`}return"TEXT";default:return"TEXT"}}getPrimaryKeyType(X){return this.getColumnType(X)}getAutoIncrementClause(X){if(X.isPrimaryKey&&(X.type==="integer"||X.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue(X){if(!X.hasDefault||X.defaultValue===void 0)return"";let $=X.defaultValue;if(typeof $==="string"){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(X,$){return""}createTable(X){let $=X.columns.map((Z)=>this.renderColumn(Z)).join(`,
325
+ `);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier(X.table)} (
326
+ ${$}
327
+ );`}createIndex(X,$){let Z=$.type==="unique"?"UNIQUE ":"",Y=`${X}_${$.name}`,U=$.columns.map((Q)=>this.quoteIdentifier(Q)).join(", "),_=$.where?` WHERE ${$.where}`:"";return`CREATE ${Z}INDEX IF NOT EXISTS ${this.quoteIdentifier(Y)} ON ${this.quoteIdentifier(X)} (${U})${_};`}addForeignKey(X,$,Z,Y,U,_){return""}addColumn(X,$){let Z=this.getColumnType($),Y=[this.quoteIdentifier($.name),Z];if(!$.isNullable&&!$.isPrimaryKey)Y.push("not null");let U=this.getDefaultValue($);if(U)Y.push(U);return`ALTER TABLE ${this.quoteIdentifier(X)} ADD COLUMN ${Y.join(" ")};`}modifyColumn(X,$){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier(X)}.${this.quoteIdentifier($.name)}`}renameColumn(X,$,Z){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME COLUMN ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(Z)};`}renameTable(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} RENAME TO ${this.quoteIdentifier($)};`}rebuildTable(X){let{target:$,tempName:Z,columnSource:Y}=X,U=(j)=>this.quoteIdentifier(j),_=$.columns.map((j)=>this.renderColumn(j)).join(`,
328
+ `),Q=`CREATE TABLE ${U(Z)} (
329
+ ${_}
330
+ );`,L=$.columns.map((j)=>j.name).filter((j)=>Y[j]!==void 0),z=["PRAGMA foreign_keys=OFF;","BEGIN;",Q];if(L.length>0){let j=L.map(U).join(", "),E=L.map((V)=>U(Y[V])).join(", ");z.push(`INSERT INTO ${U(Z)} (${j}) SELECT ${E} FROM ${U($.table)};`)}z.push(`DROP TABLE ${U($.table)};`),z.push(`ALTER TABLE ${U(Z)} RENAME TO ${U($.table)};`);for(let j of $.indexes)z.push(this.createIndex($.table,j));return z.push("PRAGMA foreign_key_check;"),z.push("COMMIT;"),z.push("PRAGMA foreign_keys=ON;"),z.join(`
331
+ `)}dropTable(X){return`DROP TABLE IF EXISTS ${this.quoteIdentifier(X)}`}dropColumn(X,$){return`ALTER TABLE ${this.quoteIdentifier(X)} DROP COLUMN ${this.quoteIdentifier($)};`}dropIndex(X,$){let Z=`${X}_${$}`;return`DROP INDEX IF EXISTS ${this.quoteIdentifier(Z)};`}dropEnumType(X){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
274
332
  id INTEGER PRIMARY KEY AUTOINCREMENT,
275
333
  migration TEXT NOT NULL UNIQUE,
276
334
  executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
277
- )`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn($){let Z=this.getColumnType($),X=[this.quoteIdentifier($.name),Z];if($.isPrimaryKey){X.push("PRIMARY KEY");let L=this.getAutoIncrementClause($);if(L)X.push(L)}if(!$.isNullable&&!$.isPrimaryKey)X.push("not null");let _=this.getDefaultValue($);if(_)X.push(_);return X.join(" ")}}function p9($){switch($){case"postgres":return new T2;case"mysql":return new P2;case"sqlite":return new k2;default:throw Error(`Unsupported dialect: ${$}`)}}var l$=()=>{},x2={};IZ(x2,{resetDatabase:()=>Kj,generateMigration:()=>v2,executeMigration:()=>Gj,deleteMigrationFiles:()=>b2,copyModelsToGenerated:()=>Ij,clearGeneratedDirectory:()=>f2});function CZ($,Z){let X=b0($,".qb");return b0(X,`model-snapshot.${Z}.json`)}function Oj($,Z){let X=CZ($,Z);if(!k9(X))return;try{let _=y2(X,"utf8"),L=JSON.parse(_);if(L?.plan&&Array.isArray(L.plan.tables)&&L.plan.dialect)return L.plan;if(Array.isArray(L?.tables)&&L?.dialect)return L;console.log("-- Invalid snapshot format, treating as no previous state");return}catch(_){console.log("-- Could not load snapshot, treating as no previous state:",_);return}}function Qj($,Z,X){let _=CZ($,Z),L=b0($,".qb");if(!k9(L))B2(L,{recursive:!0}),console.log(`-- Created snapshot directory: ${L}`);let j={plan:X,hash:jz(X),dialect:Z,updatedAt:new Date().toISOString()};A2(_,JSON.stringify(j,null,2)),console.log(`-- Model snapshot saved to ${_}`)}function K8(){return F1.cwd()}function Vj($){let Z=g2($);if(!k9(Z))B2(Z,{recursive:!0}),console.log(`-- Created SQL directory: ${Z}`);return Z}async function v2($,Z={}){if(!$)$=b0(F1.cwd(),"app/Models");let X=Z.dialect||y.dialect||"postgres",_=K8(),L=await W8({modelsDir:$}),j=BZ(L,{dialect:X}),Y;if(!Z.full)if(Y=Oj(_,X),Y)console.log("-- Comparing with stored model snapshot");else{let U=b0($,`.qb-migrations.${X}.json`),V=String(Z.state||U);if(k9(V))try{let Q=y2(V,"utf8"),O=JSON.parse(Q);if(Y=O?.plan&&O.plan.tables?O.plan:O?.tables?O:void 0,Y)console.log("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!Y)console.log("-- No previous snapshot found, generating full migration")}else console.log("-- Full migration requested, ignoring any previous state");let z=Z.full?hZ(j):fX(Y,j),F=z.join(`
278
- `),E=z.some((U)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(U));if(Z.apply){let U=zj(b0(Ej(),"qb-migrate-")),V=b0(U,"migration.sql");try{if(E)A2(V,F),console.log("-- Migration applied");else console.log("-- No changes; nothing to apply")}catch(Q){throw console.error("-- Migration failed:",Q),Q}}return Qj(_,X,j),{sql:F,sqlStatements:z,hasChanges:E,plan:j}}async function Gj($){if(!$)$=b0(F1.cwd(),"app/Models");let Z=K8(),X=Vj(Z),_=y.dialect||"postgres",j=h2(X).filter((Y)=>Y.endsWith(".sql")).sort();if(j.length===0)return console.log("-- No migration files found to execute"),!0;console.log(`-- Found ${j.length} script files to execute`);try{let Y=W0();await Wj(Y,_);let z=await Dj(Y,_),F=[],E=[];for(let V of j)if(V.includes("alter-")&&V.includes("-table"))E.push(V);else if(!z.includes(V))F.push(V);let U=F.length+E.length;if(U===0)return console.log("-- No pending migrations to execute"),!0;console.log(`-- Executing ${U} migrations (${F.length} permanent, ${E.length} transient)`);for(let V of F){let Q=b0(X,V);console.log(`-- Executing: ${V}`);try{await Y.file(Q),await Sj(Y,V,_),console.log(`-- \u2713 Migration ${V} executed and recorded`)}catch(O){throw console.error(`-- \u2717 Migration ${V} failed:`,O),O}}for(let V of E){let Q=b0(X,V);console.log(`-- Executing: ${V} (transient)`);try{await Y.file(Q),console.log(`-- \u2713 Migration ${V} executed (not recorded)`),a1(Q),console.log(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${V}`)}catch(O){throw console.error(`-- \u2717 Migration ${V} failed:`,O),O}}console.log("-- All migrations executed successfully")}catch(Y){throw console.error("-- Migration execution failed:",Y),Y}return!0}async function Kj($,Z={}){if(!$)$=b0(F1.cwd(),"app/Models");let X=Z.dialect||"postgres",_=p9(X),L=K8();try{let j=_.dropTable("migrations");try{await H5(async(F)=>{await F.unsafe(j).execute(),console.log("-- Dropped migrations table")})}catch(F){console.error(F)}let Y=[],z=[];try{let F=await W8({modelsDir:$}),E=BZ(F,{dialect:X});Y=E.tables.map((V)=>V.table);let U=new Set;for(let V of E.tables)for(let Q of V.columns)if(Q.type==="enum"&&Q.enumValues&&Q.enumValues.length>0){let O=`${Q.name}_type`;U.add(O)}z=Array.from(U)}catch(F){console.error(F),Y=[],z=[]}if(Y.length===0)console.log("-- No tables found to drop");else{console.log(`-- Dropping ${Y.length} tables: ${Y.join(", ")}`);for(let F of Y.reverse())try{let E=_.dropTable(F);await H5(async(U)=>{await U.unsafe(E).execute(),console.log(`-- Dropped table: ${F}`)})}catch(E){console.error(E),console.log(`-- Table ${F} may not exist, skipping drop`)}}if(z.length>0){console.log(`-- Dropping ${z.length} enum types: ${z.join(", ")}`);for(let F of z)try{let E=_.dropEnumType(F);if(E)await H5(async(U)=>{await U.unsafe(E).execute(),console.log(`-- Dropped enum type: ${F}`)})}catch(E){console.error(E),console.log(`-- Enum type ${F} may not exist, skipping drop`)}}else console.log("-- No enum types found to drop");try{await b2($,L,Z)}catch(F){console.error(F),console.log("-- Could not clean up migration files")}try{await f2(L)}catch(F){console.error(F),console.log("-- Could not clear generated directory")}return console.log("-- Database reset completed successfully"),!0}catch(j){return console.error("-- Database reset failed:",j),!1}}async function b2($,Z,X={}){if(!$)$=b0(F1.cwd(),"app/Models");if(!Z)Z=K8();let _=String(X.dialect||"postgres"),L=CZ(Z,_);if(k9(L))a1(L),console.log(`-- Removed model snapshot file: ${L}`);let j=b0($,`.qb-migrations.${_}.json`),Y=String(X.state||j);if(k9(Y))a1(Y),console.log(`-- Removed legacy migration state file: ${Y}`);let z=g2(Z);if(k9(z)){let E=h2(z).filter((U)=>U.endsWith(".sql"));for(let U of E){let V=b0(z,U);a1(V),console.log(`-- Removed migration file: ${U}`)}console.log(`-- Cleaned up ${E.length} migration files from migrations directory`)}}async function Ij($,Z){}async function f2($){if(!$)$=K8();let Z=b0($,"generated");if(k9(Z))try{Uj(Z,{recursive:!0,force:!0}),console.log("-- Cleared generated directory")}catch(X){console.error("-- Failed to clear generated directory:",X)}}function g2($){if(!$)$=K8();return b0($,"database","migrations")}async function Wj($,Z){let _=p9(Z).createMigrationsTable();try{await $.unsafe(_).execute(),console.log("-- Migrations table ready")}catch(L){throw console.error("-- Failed to create migrations table:",L),L}}async function Dj($,Z){let X=p9(Z);try{return(await $.unsafe(X.getExecutedMigrationsQuery()).execute()).map((L)=>L.migration)}catch(_){return console.error("-- Failed to get executed migrations:",_),[]}}async function Sj($,Z,X){let _=p9(X);try{console.log(`-- Recording migration: ${Z}`),await $.unsafe(_.recordMigrationQuery(),[Z]).execute(),console.log(`-- Successfully recorded migration: ${Z}`)}catch(L){throw console.error(`-- Failed to record migration ${Z}:`,L),L}}var wZ=n(()=>{F9(),G8(),l$(),P0()});async function HE($,Z={}){return v2($,Z)}var Mj=n(()=>{wZ()});function Jj($){let Z=$;while(Z!==r6(Z)){if(p2(qZ(Z,"package.json")))return Z;Z=r6(Z)}return d2.cwd()}function Cj($){if(!$)$=Jj(d2.cwd());return qZ($,"database","migrations")}async function kE($={}){let Z=$.steps||1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${Z}`),console.log();try{let X=W0(),_=[];try{_=await X.unsafe(`
335
+ )`}getExecutedMigrationsQuery(){return"SELECT migration FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}renderColumn(X){let $=this.getColumnType(X),Z=[this.quoteIdentifier(X.name),$];if(X.isPrimaryKey){Z.push("PRIMARY KEY");let U=this.getAutoIncrementClause(X);if(U)Z.push(U)}if(!X.isNullable&&!X.isPrimaryKey)Z.push("not null");let Y=this.getDefaultValue(X);if(Y)Z.push(Y);if(X.references){if(Z.push(`REFERENCES ${this.quoteIdentifier(X.references.table)}(${this.quoteIdentifier(X.references.column)})`),X.references.onDelete)Z.push(`ON DELETE ${X.references.onDelete.toUpperCase()}`);if(X.references.onUpdate)Z.push(`ON UPDATE ${X.references.onUpdate.toUpperCase()}`)}return Z.join(" ")}}function ZX(X){switch(X){case"postgres":return new FU;case"mysql":return new Z5;case"singlestore":return new OU;case"sqlite":return new WU;default:throw Error(`Unsupported dialect: ${X}`)}}var _Z=e(()=>{kY(),kY()}),VU={};n1(VU,{resetDatabase:()=>NQ,generateMigration:()=>MU,executeMigration:()=>TQ,deleteMigrationFiles:()=>HU,copyModelsToGenerated:()=>SQ,clearGeneratedDirectory:()=>CU});function t(X){if(f.verbose)console.log(X)}function Y5(X,$){let Z=m0(X,".qb");return m0(Z,`model-snapshot.${$}.json`)}function wQ(X,$){let Z=Y5(X,$);if(!g9(Z))return;try{let Y=RU(Z,"utf8"),U=JSON.parse(Y);if(U?.plan&&Array.isArray(U.plan.tables)&&U.plan.dialect)return U.plan;if(Array.isArray(U?.tables)&&U?.dialect)return U;t("-- Invalid snapshot format, treating as no previous state");return}catch(Y){t(`-- Could not load snapshot, treating as no previous state: ${Y instanceof Error?Y.message:String(Y)}`);return}}function qQ(X,$,Z){let Y=Y5(X,$),U=m0(X,".qb");if(!g9(U))IU(U,{recursive:!0}),t(`-- Created snapshot directory: ${U}`);let _={plan:Z,hash:Oj(Z),dialect:$,updatedAt:new Date().toISOString()};DU(Y,JSON.stringify(_,null,2)),t(`-- Model snapshot saved to ${Y}`)}function fX(){return B$.cwd()}function PQ(X){let $=wU(X);if(!g9($))IU($,{recursive:!0}),t(`-- Created SQL directory: ${$}`);return $}async function MU(X,$={}){if(!X)X=m0(B$.cwd(),"app/Models");let Z=$.dialect||f.dialect||"postgres",Y=fX(),U=await dX({modelsDir:X}),_=J5(U,{dialect:Z}),Q;if(!$.full)if(Q=wQ(Y,Z),Q)t("-- Comparing with stored model snapshot");else{let G=m0(X,`.qb-migrations.${Z}.json`),J=String($.state||G);if(g9(J))try{let W=RU(J,"utf8"),F=JSON.parse(W);if(Q=F?.plan&&F.plan.tables?F.plan:F?.tables?F:void 0,Q)t("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!Q||$.fromDb)try{let W=await VQ(Z),F=new Set(_.tables.map((D)=>D.table)),K=W.tables.filter((D)=>F.has(D.table));if(K.length>0)Q={dialect:W.dialect,tables:K},t(`-- No snapshot; reconciling against live database (${K.length} matching table${K.length===1?"":"s"})`)}catch(W){t(`-- Could not introspect live database, treating as no previous state: ${W instanceof Error?W.message:String(W)}`)}if(!Q)t("-- No previous snapshot found, generating full migration")}else t("-- Full migration requested, ignoring any previous state");let L=$.full?{statements:W5(_,{dryRun:$.dryRun}),operations:_.tables.map((G)=>({kind:"create_table",table:G.table,destructive:!1,sql:""}))}:w7(Q,_,{applyRenames:$.applyRenames,dryRun:$.dryRun}),z=L.statements,j=L.operations,E=z.join(`
336
+ `),V=z.some((G)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(G));if($.apply){let G=MQ(m0(CQ(),"qb-migrate-")),J=m0(G,"migration.sql");try{if(V)DU(J,E),t("-- Migration applied");else t("-- No changes; nothing to apply")}catch(W){throw console.error("-- Migration failed:",W),W}}if(!$.dryRun)qQ(Y,Z,_);return{sql:E,sqlStatements:z,hasChanges:V,plan:_,operations:j}}async function TQ(X){if(!X)X=m0(B$.cwd(),"app/Models");let $=fX(),Z=PQ($),Y=f.dialect||"postgres",_=KU(Z).filter((Q)=>Q.endsWith(".sql")).sort();if(_.length===0)return t("-- No migration files found to execute"),!0;t(`-- Found ${_.length} script files to execute`);try{let Q=K0();await AQ(Q,Y);let L=await kQ(Q,Y),z=[],j=[];for(let V of _)if(V.includes("alter-")&&V.includes("-table"))j.push(V);else if(!L.includes(V))z.push(V);let E=z.length+j.length;if(E===0)return t("-- No pending migrations to execute"),!0;t(`-- Executing ${E} migrations (${z.length} permanent, ${j.length} transient)`);for(let V of z){let G=m0(Z,V);t(`-- Executing: ${V}`);try{await Q.file(G),await xQ(Q,V,Y),t(`-- \u2713 Migration ${V} executed and recorded`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}for(let V of j){let G=m0(Z,V);t(`-- Executing: ${V} (transient)`);try{await Q.file(G),t(`-- \u2713 Migration ${V} executed (not recorded)`),H8(G),t(`-- \uD83D\uDDD1\uFE0F Deleted transient migration: ${V}`)}catch(J){throw console.error(`-- \u2717 Migration ${V} failed:`,J),J}}t("-- All migrations executed successfully")}catch(Q){throw console.error("-- Migration execution failed:",Q),Q}return!0}async function NQ(X,$={}){if(!X)X=m0(B$.cwd(),"app/Models");let Z=$.dialect||"postgres",Y=ZX(Z),U=fX();try{let _=Y.dropTable("migrations");try{await gZ(async(z)=>{await z.unsafe(_).execute(),t("-- Dropped migrations table")})}catch(z){console.error(z)}let Q=[],L=[];try{let z=await dX({modelsDir:X}),j=J5(z,{dialect:Z});Q=j.tables.map((V)=>V.table);let E=new Set;for(let V of j.tables)for(let G of V.columns)if(G.type==="enum"&&G.enumValues&&G.enumValues.length>0){let J=`${V.table}_${G.name}_type`;E.add(J)}L=Array.from(E)}catch(z){console.error(z),Q=[],L=[]}if(Q.length===0)t("-- No tables found to drop");else{t(`-- Dropping ${Q.length} tables: ${Q.join(", ")}`);for(let z of Q.reverse())try{let j=Y.dropTable(z);await gZ(async(E)=>{await E.unsafe(j).execute(),t(`-- Dropped table: ${z}`)})}catch(j){console.error(j),t(`-- Table ${z} may not exist, skipping drop`)}}if(L.length>0){t(`-- Dropping ${L.length} enum types: ${L.join(", ")}`);for(let z of L)try{let j=Y.dropEnumType(z);if(j)await gZ(async(E)=>{await E.unsafe(j).execute(),t(`-- Dropped enum type: ${z}`)})}catch(j){console.error(j),t(`-- Enum type ${z} may not exist, skipping drop`)}}else t("-- No enum types found to drop");if(Q.length>0)try{await HU(X,U,$)}catch(z){console.error(z),t("-- Could not clean up migration files")}else t("-- No models directory found; keeping committed migration files in place");try{await CU(U)}catch(z){console.error(z),t("-- Could not clear generated directory")}return t("-- Database reset completed successfully"),!0}catch(_){return console.error("-- Database reset failed:",_),!1}}async function HU(X,$,Z={}){if(!X)X=m0(B$.cwd(),"app/Models");if(!$)$=fX();let Y=String(Z.dialect||"postgres"),U=Y5($,Y);if(g9(U))H8(U),t(`-- Removed model snapshot file: ${U}`);let _=m0(X,`.qb-migrations.${Y}.json`),Q=String(Z.state||_);if(g9(Q))H8(Q),t(`-- Removed legacy migration state file: ${Q}`);let L=wU($);if(g9(L)){let j=KU(L).filter((E)=>E.endsWith(".sql"));for(let E of j){let V=m0(L,E);H8(V),t(`-- Removed migration file: ${E}`)}t(`-- Cleaned up ${j.length} migration files from migrations directory`)}}async function SQ(X,$){}async function CU(X){if(!X)X=fX();let $=m0(X,"generated");if(g9($))try{HQ($,{recursive:!0,force:!0}),t("-- Cleared generated directory")}catch(Z){console.error("-- Failed to clear generated directory:",Z)}}function wU(X){if(!X)X=fX();return m0(X,"database","migrations")}async function AQ(X,$){let Y=ZX($).createMigrationsTable();try{await X.unsafe(Y).execute(),t("-- Migrations table ready")}catch(U){throw console.error("-- Failed to create migrations table:",U),U}}async function kQ(X,$){let Z=ZX($);try{return(await X.unsafe(Z.getExecutedMigrationsQuery()).execute()).map((U)=>U.migration)}catch(Y){return console.error("-- Failed to get executed migrations:",Y),[]}}async function xQ(X,$,Z){let Y=ZX(Z);try{t(`-- Recording migration: ${$}`),await X.unsafe(Y.recordMigrationQuery(),[$]).execute(),t(`-- Successfully recorded migration: ${$}`)}catch(U){throw console.error(`-- Failed to record migration ${$}:`,U),U}}var U5=e(()=>{d0(),$X(),_Z(),y0(),EU()});async function lG(X,$={}){return MU(X,$)}var BQ=e(()=>{U5()});function vQ(X){let $=[],Z="",Y=!1,_=X.split(`
337
+ `).filter((Q)=>!/^\s*--/.test(Q)).join(`
338
+ `);for(let Q=0;Q<_.length;Q++){let L=_[Q];if(L==="'")Y=!Y;if(L===";"&&!Y){if(Z.trim())$.push(Z.trim());Z=""}else Z+=L}if(Z.trim())$.push(Z.trim());return $}function bQ(X,$=f.dialect){let Z=(_)=>J0($)?`\`${_}\``:`"${_}"`,Y=[],U=[];for(let _ of vQ(X)){let Q;if(Q=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(_))Y.push(`DROP TABLE IF EXISTS ${Z(Q[1])}`);else if(Q=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+)?["`']?(\w+)["`']?/i.exec(_))Y.push(`ALTER TABLE ${Z(Q[1])} DROP COLUMN ${Z(Q[2])}`);else if(Q=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(_))Y.push(J0($)&&Q[2]?`DROP INDEX ${Z(Q[1])} ON ${Z(Q[2])}`:`DROP INDEX IF EXISTS ${Z(Q[1])}`);else U.push(_)}return{down:Y.reverse(),skipped:U}}function fQ(X){let $=X;while($!==xY($)){if(N1(_5($,"package.json")))return $;$=xY($)}return qU.cwd()}function gQ(X){if(!X)X=fQ(qU.cwd());return _5(X,"database","migrations")}async function aG(X={}){let $=X.steps||1,Z=X.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${$}`),console.log();try{let Y=K0(),U=[];try{U=await Y.unsafe(`
279
339
  SELECT migration, executed_at
280
340
  FROM migrations
281
341
  ORDER BY executed_at DESC, migration DESC
282
- `)}catch(j){console.log("-- Migrations table not found. Nothing to rollback.",j);return}if(_.length===0){console.log("-- No migrations to rollback");return}let L=_.slice(0,Z);console.log(`-- Found ${_.length} executed migrations`),console.log(`-- Rolling back ${L.length} migration(s):`),console.log();for(let j of L)console.log(` - ${j.migration}`);console.log();for(let j of L)try{await X.unsafe("DELETE FROM migrations WHERE migration = $1",[j.migration]),console.log(`-- \u2713 Removed migration record: ${j.migration}`);let z=Cj(),F=qZ(z,j.migration);if(p2(F))Rj(F),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${j.migration}`)}catch(Y){throw console.error(`-- \u2717 Failed to rollback migration ${j.migration}:`,Y),Y}console.log(),console.log("-- \u26A0\uFE0F Important: Rollback only removes migration records."),console.log("-- To reverse schema changes:"),console.log("-- 1. Revert your model changes"),console.log("-- 2. Run `qb migrate:fresh` to rebuild the database"),console.log("-- or manually write and execute reverse SQL")}catch(X){throw console.error("-- Rollback failed:",X),X}}var wj=n(()=>{P0()});function Hj($){let Z=$;while(Z!==t6(Z)){if(c2(m2(Z,"package.json")))return Z;Z=t6(Z)}return u2.cwd()}function Nj($){if(!$)$=Hj(u2.cwd());return m2($,"database","migrations")}async function Pj(){let $=y.dialect||"postgres",Z=p9($),X=Nj();if(console.log("-- Migration Status"),console.log(`-- Dialect: ${$}`),console.log(`-- SQL directory: ${X}`),console.log(),!c2(X))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let L=qj(X).filter((j)=>j.endsWith(".sql")).sort();if(L.length===0)return console.log("-- No migration files found"),[];try{let j=W0(),Y=[];try{Y=await j.unsafe(Z.getExecutedMigrationsQuery())}catch(Q){console.log("-- Migrations table not found. All migrations are pending.",Q),console.log()}let z=new Map(Y.map((Q)=>[Q.migration,Q.executed_at])),F=L.map((Q)=>{if(Q.includes("alter-")&&Q.includes("-table"))return{file:Q,status:"transient"};let O=z.get(Q);return{file:Q,status:O?"executed":"pending",executedAt:O}}),E=F.filter((Q)=>Q.status==="executed"),U=F.filter((Q)=>Q.status==="pending"),V=F.filter((Q)=>Q.status==="transient");if(console.log(`-- Total migrations: ${L.length}`),console.log(`-- Executed: ${E.length}`),console.log(`-- Pending: ${U.length}`),console.log(`-- Transient: ${V.length}`),console.log(),E.length>0){console.log("\u2713 Executed Migrations:");for(let Q of E)console.log(` - ${Q.file} ${Q.executedAt?`(${new Date(Q.executedAt).toLocaleString()})`:""}`);console.log()}if(U.length>0){console.log("\u25CB Pending Migrations:");for(let Q of U)console.log(` - ${Q.file}`);console.log()}if(V.length>0){console.log("\u26A1 Transient Migrations (ALTER TABLE - not tracked):");for(let Q of V)console.log(` - ${Q.file}`);console.log()}return F}catch(j){throw console.error("-- Failed to get migration status:",j),j}}async function yE(){return Pj()}var Tj=n(()=>{F9(),l$(),P0()});async function fE($,Z={}){let X=Z.dir||a6(xj.cwd(),"app/Models");try{let _=kj(X),L=_.find((U)=>{return U.replace(N5(U),"").toLowerCase()===$.toLowerCase()});if(!L){console.error(`Model "${$}" not found in ${X}`),console.log(`Available models: ${_.filter((U)=>[".ts",".js"].includes(N5(U))).map((U)=>U.replace(N5(U),"")).join(", ")}`);return}let Y=await import(a6(X,L)),z=Y.default||Y[Object.keys(Y)[0]];if(!z||!z.name){console.error(`Invalid model file: ${L}`);return}let F={name:z.name,table:z.table||`${z.name.toLowerCase()}s`,primaryKey:z.primaryKey||"id",attributes:z.attributes||{},relations:z.relations,scopes:z.scopes,indexes:z.indexes,timestamps:z.timestamps!==!1,softDeletes:z.softDeletes===!0},E=[];if(z.beforeCreate)E.push("beforeCreate");if(z.afterCreate)E.push("afterCreate");if(z.beforeUpdate)E.push("beforeUpdate");if(z.afterUpdate)E.push("afterUpdate");if(z.beforeDelete)E.push("beforeDelete");if(z.afterDelete)E.push("afterDelete");if(E.length>0)F.hooks=E;if(Z.json)return console.log(JSON.stringify(F,null,2)),F;console.log(`
283
- \uD83D\uDCE6 Model: ${F.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: ${F.table}`),console.log(`Primary Key: ${F.primaryKey}`),console.log(`Timestamps: ${F.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${F.softDeletes?"\u2713":"\u2717"}`),console.log(`
284
- \uD83D\uDCCB Attributes (${Object.keys(F.attributes).length}):`);for(let[U,V]of Object.entries(F.attributes)){let Q=V.type||"string",O=V.required?"(required)":"",K=V.unique?"(unique)":"",I=V.default!==void 0?`= ${JSON.stringify(V.default)}`:"";console.log(` \u2022 ${U}: ${Q} ${O} ${K} ${I}`.trim())}if(F.relations&&Object.keys(F.relations).length>0){console.log(`
285
- \uD83D\uDD17 Relations (${Object.keys(F.relations).length}):`);for(let[U,V]of Object.entries(F.relations)){let Q=V.type||"unknown",O=V.model||V.table||"unknown";console.log(` \u2022 ${U}: ${Q} \u2192 ${O}`)}}if(F.scopes&&Object.keys(F.scopes).length>0){console.log(`
286
- \uD83D\uDD0D Scopes (${Object.keys(F.scopes).length}):`);for(let U of Object.keys(F.scopes))console.log(` \u2022 ${U}()`)}if(F.hooks&&F.hooks.length>0){console.log(`
287
- \uD83E\uDE9D Hooks (${F.hooks.length}):`);for(let U of F.hooks)console.log(` \u2022 ${U}`)}if(F.indexes&&F.indexes.length>0){console.log(`
288
- \uD83D\uDCC7 Indexes (${F.indexes.length}):`);for(let U of F.indexes){let V=Array.isArray(U.columns)?U.columns.join(", "):U.columns,Q=U.unique?"(unique)":"";console.log(` \u2022 ${U.name||"unnamed"}: [${V}] ${Q}`.trim())}}return console.log(),F}catch(_){throw console.error(`Error loading model "${$}":`,_.message),_}}var Bj=()=>{};async function gE(){let Z=await W0().ping();return console.log(Z?"OK":"NOT READY"),Z}var hj=n(()=>{P0()});async function cE($,Z={}){let X=[];try{let _=Aj($),L=[];if(_.isDirectory())L=yj($).filter((F)=>$7(F)===".sql").map((F)=>vj($,F));else if(_.isFile()&&$7($)===".sql")L=[$];else return console.error("Path must be a .sql file or directory containing .sql files"),X;if(L.length===0)return console.log("No .sql files found"),X;if(Z.verbose)console.log(`Analyzing ${L.length} SQL file(s)...
289
- `);for(let z of L)try{let F=e6(z,"utf8").trim();if(!F){if(Z.verbose)console.log(`\u2298 ${z}: empty file`);continue}if(Z.verbose)console.log(`\uD83D\uDCC4 ${z}`),console.log(` Query: ${F.substring(0,60)}${F.length>60?"...":""}`);let E=await x`EXPLAIN ${x.unsafe(F)}`;if(X.push({file:z,query:F,plan:Array.isArray(E)?E:[E]}),Z.verbose&&!Z.json){if(console.log(" Plan:"),Array.isArray(E))for(let U of E)if(typeof U==="string")console.log(` ${U}`);else if(U["QUERY PLAN"])console.log(` ${U["QUERY PLAN"]}`);else if(U.plan)console.log(` ${JSON.stringify(U.plan)}`);else console.log(` ${JSON.stringify(U)}`);console.log()}}catch(F){if(X.push({file:z,query:e6(z,"utf8").trim(),plan:[],error:F.message}),Z.verbose)console.log(` \u2717 Error: ${F.message}
290
- `)}let j=X.filter((z)=>!z.error).length,Y=X.filter((z)=>z.error).length;if(Z.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: ${j} successful, ${Y} failed`);if(Z.json)console.log(JSON.stringify(X,null,2));return X}catch(_){throw console.error("Error explaining queries:",_.message),_}}var bj=n(()=>{G8()});async function iE($={}){let Z=$.dir||gj(pj.cwd(),"app/Models"),X=$.format||"mermaid";try{let _=await W8({modelsDir:Z});if(!_||Object.keys(_).length===0)return console.error("No models found"),"";let L="";if(X==="mermaid")L=dj(_);else if(X==="dot")L=cj(_);else return console.error(`Unsupported format: ${X}`),"";if($.output)fj($.output,L,"utf8"),console.log(`\u2713 Diagram written to: ${$.output}`);else console.log(L);return L}catch(_){throw console.error("Error generating diagram:",_.message),_}}function dj($){let Z=["erDiagram"];for(let[X,_]of Object.entries($)){let L=_.table||`${X.toLowerCase()}s`,j=_.attributes||{};Z.push(` ${L} {`);for(let[Y,z]of Object.entries(j)){let F=z.type||"string",E=_.primaryKey===Y?"PK":"",U=z.unique?"UK":"",V=[E,U].filter(Boolean).join(","),Q=V?` "${V}"`:"";Z.push(` ${F} ${Y}${Q}`)}Z.push(" }")}for(let[X,_]of Object.entries($)){let L=_.table||`${X.toLowerCase()}s`,j=_.relations||{};for(let[Y,z]of Object.entries(j)){let{type:F,model:E}=z,U=$[E]?.table||`${E?.toLowerCase()}s`||"unknown",V="";if(F==="hasOne")V="||--||";else if(F==="hasMany")V="||--o{";else if(F==="belongsTo")V="}o--||";else if(F==="belongsToMany"||F==="manyToMany")V="}o--o{";else V="||--||";Z.push(` ${L} ${V} ${U} : "${Y}"`)}}return Z.join(`
291
- `)}function cj($){let Z=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[X,_]of Object.entries($)){let L=_.table||`${X.toLowerCase()}s`,j=_.attributes||{},Y=[];for(let[F,E]of Object.entries(j)){let U=E.type||"string",V=_.primaryKey===F?" (PK)":"",Q=E.unique?" (UK)":"";Y.push(`${F}: ${U}${V}${Q}`)}let z=`${Y.join("\\l")}\\l`;Z.push(` ${L} [label="{${L}|${z}}"];`)}Z.push("");for(let[X,_]of Object.entries($)){let L=_.table||`${X.toLowerCase()}s`,j=_.relations||{};for(let[Y,z]of Object.entries(j)){let{type:F,model:E}=z,U=$[E]?.table||`${E?.toLowerCase()}s`||"unknown",V="";if(F==="hasOne")V="arrowhead=none, arrowtail=normal";else if(F==="hasMany")V="arrowhead=crow, arrowtail=none";else if(F==="belongsTo")V="arrowhead=normal, arrowtail=none";else if(F==="belongsToMany"||F==="manyToMany")V="arrowhead=crow, arrowtail=crow";Z.push(` ${L} -> ${U} [label="${Y}", ${V}];`)}}return Z.push("}"),Z.join(`
292
- `)}var mj=n(()=>{P0()});function s$($){let Z=$;while(Z!==Z7(Z)){if(M$(h9(Z,"package.json")))return Z;Z=Z7(Z)}return z1.cwd()}async function n2($){if(!M$($))return console.log(`-- Seeders directory not found: ${$}`),[];let X=nj($).filter((L)=>(L.endsWith(".ts")||L.endsWith(".js"))&&L!=="index.ts"&&L!=="index.js"),_=[];for(let L of X){let j=h9($,L);try{let Y=await import(j),z=Y.default||Y[Object.keys(Y)[0]];if(z&&typeof z==="function"){let F=new z;if(F&&typeof F.run==="function")_.push({name:L.replace(/\.(ts|js)$/,""),instance:F})}}catch(Y){console.error(`-- Failed to load seeder ${L}:`,Y)}}return _.sort((L,j)=>L.instance.order-j.instance.order),_}async function lj($={}){let Z=s$(z1.cwd()),X=$.seedersDir||h9(Z,"database/seeders"),_=$.verbose??!0;if(_)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${X}`);let L=await n2(X);if(L.length===0){console.log("-- No seeders found");return}if(_)console.log(`-- Found ${L.length} seeder(s)`);let j=W0();for(let{name:Y,instance:z}of L)try{if(_)console.log(`-- Seeding: ${Y}`);if(await z.run(j),_)console.log(`-- \u2713 Seeded: ${Y}`)}catch(F){throw console.error(`-- \u2717 Failed to seed ${Y}:`,F),F}if(_)console.log("-- All seeders completed successfully")}async function rE($,Z={}){let X=s$(z1.cwd()),_=h9(X,"database/seeders"),L=Z.verbose??!0;if(L)console.log(`-- Running seeder: ${$}`);let Y=(await n2(_)).find((F)=>F.name===$);if(!Y)throw console.error(`-- Seeder not found: ${$}`),Error(`Seeder not found: ${$}`);let z=W0();try{if(await Y.instance.run(z),L)console.log(`-- \u2713 Seeder completed: ${$}`)}catch(F){throw console.error(`-- \u2717 Seeder failed: ${$}`,F),F}}async function tE($){let Z=s$(z1.cwd()),X=h9(Z,"database/seeders");if(!M$(X))uj(X,{recursive:!0}),console.log(`-- Created seeders directory: ${X}`);let L=`${$.replace(/Seeder$/i,"")}Seeder`,j=`${L}.ts`,Y=h9(X,j);if(M$(Y))throw console.error(`-- Seeder already exists: ${Y}`),Error(`Seeder already exists: ${Y}`);let z=`import type { QueryBuilder } from 'bun-query-builder'
342
+ `)}catch(z){console.log("-- Migrations table not found. Nothing to rollback.",z);return}if(U.length===0){console.log("-- No migrations to rollback");return}let _=U.slice(0,$);console.log(`-- Found ${U.length} executed migrations`),console.log(`-- Rolling back ${_.length} migration(s):`),console.log();for(let z of _)console.log(` - ${z.migration}`);console.log();let Q=gQ(),L=!1;for(let z of _)try{let j=_5(Q,z.migration);if(Z&&N1(j)){let V=yQ(j,"utf8"),{down:G,skipped:J}=bQ(V);for(let W of G)await Y.unsafe(W),console.log(`-- \u21A9 ${W}`),L=!0;if(J.length>0)console.log(`-- \u26A0\uFE0F ${J.length} statement(s) in ${z.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let E="DELETE FROM migrations WHERE migration = $1";if(await Y.unsafe(E,[z.migration]),console.log(`-- \u2713 Removed migration record: ${z.migration}`),N1(j))hQ(j),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${z.migration}`)}catch(j){throw console.error(`-- \u2717 Failed to rollback migration ${z.migration}:`,j),j}if(console.log(),Z)console.log(L?"-- \u2713 Reverse DDL executed for the rolled-back migration(s).":"-- \u26A0\uFE0F No reversible DDL found; only migration records were removed.");else console.log("-- \u26A0\uFE0F reverseSchema disabled: only migration records were removed.")}catch(Y){throw console.error("-- Rollback failed:",Y),Y}}var dQ=e(()=>{d0(),y0()});function cQ(X){let $=X;while($!==BY($)){if(PU(TU($,"package.json")))return $;$=BY($)}return NU.cwd()}function mQ(X){if(!X)X=cQ(NU.cwd());return TU(X,"database","migrations")}async function uQ(){let X=f.dialect||"postgres",$=ZX(X),Z=mQ();if(console.log("-- Migration Status"),console.log(`-- Dialect: ${X}`),console.log(`-- SQL directory: ${Z}`),console.log(),!PU(Z))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let U=pQ(Z).filter((_)=>_.endsWith(".sql")).sort();if(U.length===0)return console.log("-- No migration files found"),[];try{let _=K0(),Q=[];try{Q=await _.unsafe($.getExecutedMigrationsQuery())}catch(G){console.log("-- Migrations table not found. All migrations are pending.",G),console.log()}let L=new Map(Q.map((G)=>[G.migration,G.executed_at])),z=U.map((G)=>{if(G.includes("alter-")&&G.includes("-table"))return{file:G,status:"transient"};let J=L.get(G);return{file:G,status:J?"executed":"pending",executedAt:J}}),j=z.filter((G)=>G.status==="executed"),E=z.filter((G)=>G.status==="pending"),V=z.filter((G)=>G.status==="transient");if(console.log(`-- Total migrations: ${U.length}`),console.log(`-- Executed: ${j.length}`),console.log(`-- Pending: ${E.length}`),console.log(`-- Transient: ${V.length}`),console.log(),j.length>0){console.log("\u2713 Executed Migrations:");for(let G of j)console.log(` - ${G.file} ${G.executedAt?`(${new Date(G.executedAt).toLocaleString()})`:""}`);console.log()}if(E.length>0){console.log("\u25CB Pending Migrations:");for(let G of E)console.log(` - ${G.file}`);console.log()}if(V.length>0){console.log("\u26A1 Transient Migrations (ALTER TABLE - not tracked):");for(let G of V)console.log(` - ${G.file}`);console.log()}return z}catch(_){throw console.error("-- Failed to get migration status:",_),_}}async function $F(){return uQ()}var nQ=e(()=>{d0(),_Z(),y0()});async function _F(X,$={}){let Z=$.dir||yY(lQ.cwd(),"app/Models");try{let Y=iQ(Z),U=Y.find((E)=>{return E.replace(dZ(E),"").toLowerCase()===X.toLowerCase()});if(!U){console.error(`Model "${X}" not found in ${Z}`),console.log(`Available models: ${Y.filter((E)=>[".ts",".js"].includes(dZ(E))).map((E)=>E.replace(dZ(E),"")).join(", ")}`);return}let Q=await import(yY(Z,U)),L=Q.default||Q[Object.keys(Q)[0]];if(!L||!L.name){console.error(`Invalid model file: ${U}`);return}let z={name:L.name,table:L.table||`${L.name.toLowerCase()}s`,primaryKey:L.primaryKey||"id",attributes:L.attributes||{},relations:L.relations,scopes:L.scopes,indexes:L.indexes,timestamps:L.timestamps!==!1,softDeletes:L.softDeletes===!0},j=[];if(L.beforeCreate)j.push("beforeCreate");if(L.afterCreate)j.push("afterCreate");if(L.beforeUpdate)j.push("beforeUpdate");if(L.afterUpdate)j.push("afterUpdate");if(L.beforeDelete)j.push("beforeDelete");if(L.afterDelete)j.push("afterDelete");if(j.length>0)z.hooks=j;if($.json)return console.log(JSON.stringify(z,null,2)),z;console.log(`
343
+ \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(`
344
+ \uD83D\uDCCB Attributes (${Object.keys(z.attributes).length}):`);for(let[E,V]of Object.entries(z.attributes)){let G=V.type||"string",J=V.required?"(required)":"",W=V.unique?"(unique)":"",F=V.default!==void 0?`= ${JSON.stringify(V.default)}`:"";console.log(` \u2022 ${E}: ${G} ${J} ${W} ${F}`.trim())}if(z.relations&&Object.keys(z.relations).length>0){console.log(`
345
+ \uD83D\uDD17 Relations (${Object.keys(z.relations).length}):`);for(let[E,V]of Object.entries(z.relations)){let G=V.type||"unknown",J=V.model||V.table||"unknown";console.log(` \u2022 ${E}: ${G} \u2192 ${J}`)}}if(z.scopes&&Object.keys(z.scopes).length>0){console.log(`
346
+ \uD83D\uDD0D Scopes (${Object.keys(z.scopes).length}):`);for(let E of Object.keys(z.scopes))console.log(` \u2022 ${E}()`)}if(z.hooks&&z.hooks.length>0){console.log(`
347
+ \uD83E\uDE9D Hooks (${z.hooks.length}):`);for(let E of z.hooks)console.log(` \u2022 ${E}`)}if(z.indexes&&z.indexes.length>0){console.log(`
348
+ \uD83D\uDCC7 Indexes (${z.indexes.length}):`);for(let E of z.indexes){let V=Array.isArray(E.columns)?E.columns.join(", "):E.columns,G=E.unique?"(unique)":"";console.log(` \u2022 ${E.name||"unnamed"}: [${V}] ${G}`.trim())}}return console.log(),z}catch(Y){throw console.error(`Error loading model "${X}":`,Y.message),Y}}var sQ=()=>{};async function QF(){let $=await K0().ping();return console.log($?"OK":"NOT READY"),$}var oQ=e(()=>{y0()});async function jF(X,$={}){let Z=[];try{let Y=aQ(X),U=[];if(Y.isDirectory())U=rQ(X).filter((z)=>vY(z)===".sql").map((z)=>tQ(X,z));else if(Y.isFile()&&vY(X)===".sql")U=[X];else return console.error("Path must be a .sql file or directory containing .sql files"),Z;if(U.length===0)return console.log("No .sql files found"),Z;if($.verbose)console.log(`Analyzing ${U.length} SQL file(s)...
349
+ `);for(let L of U)try{let z=hY(L,"utf8").trim();if(!z){if($.verbose)console.log(`\u2298 ${L}: empty file`);continue}if($.verbose)console.log(`\uD83D\uDCC4 ${L}`),console.log(` Query: ${z.substring(0,60)}${z.length>60?"...":""}`);let j=await m`EXPLAIN ${m.unsafe(z)}`;if(Z.push({file:L,query:z,plan:Array.isArray(j)?j:[j]}),$.verbose&&!$.json){if(console.log(" Plan:"),Array.isArray(j))for(let E of j)if(typeof E==="string")console.log(` ${E}`);else if(E["QUERY PLAN"])console.log(` ${E["QUERY PLAN"]}`);else if(E.plan)console.log(` ${JSON.stringify(E.plan)}`);else console.log(` ${JSON.stringify(E)}`);console.log()}}catch(z){if(Z.push({file:L,query:hY(L,"utf8").trim(),plan:[],error:z.message}),$.verbose)console.log(` \u2717 Error: ${z.message}
350
+ `)}let _=Z.filter((L)=>!L.error).length,Q=Z.filter((L)=>L.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: ${_} successful, ${Q} failed`);if($.json)console.log(JSON.stringify(Z,null,2));return Z}catch(Y){throw console.error("Error explaining queries:",Y.message),Y}}var eQ=e(()=>{$X()});async function OF(X={}){let $=X.dir||$z(Zz.cwd(),"app/Models"),Z=X.format||"mermaid";try{let Y=await dX({modelsDir:$});if(!Y||Object.keys(Y).length===0)return console.error("No models found"),"";let U="";if(Z==="mermaid")U=Yz(Y);else if(Z==="dot")U=Uz(Y);else return console.error(`Unsupported format: ${Z}`),"";if(X.output)Xz(X.output,U,"utf8"),console.log(`\u2713 Diagram written to: ${X.output}`);else console.log(U);return U}catch(Y){throw console.error("Error generating diagram:",Y.message),Y}}function Yz(X){let $=["erDiagram"];for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.attributes||{};$.push(` ${U} {`);for(let[Q,L]of Object.entries(_)){let z=L.type||"string",j=Y.primaryKey===Q?"PK":"",E=L.unique?"UK":"",V=[j,E].filter(Boolean).join(","),G=V?` "${V}"`:"";$.push(` ${z} ${Q}${G}`)}$.push(" }")}for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.relations||{};for(let[Q,L]of Object.entries(_)){let{type:z,model:j}=L,E=X[j]?.table||`${j?.toLowerCase()}s`||"unknown",V="";if(z==="hasOne")V="||--||";else if(z==="hasMany")V="||--o{";else if(z==="belongsTo")V="}o--||";else if(z==="belongsToMany"||z==="manyToMany")V="}o--o{";else V="||--||";$.push(` ${U} ${V} ${E} : "${Q}"`)}}return $.join(`
351
+ `)}function Uz(X){let $=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.attributes||{},Q=[];for(let[z,j]of Object.entries(_)){let E=j.type||"string",V=Y.primaryKey===z?" (PK)":"",G=j.unique?" (UK)":"";Q.push(`${z}: ${E}${V}${G}`)}let L=`${Q.join("\\l")}\\l`;$.push(` ${U} [label="{${U}|${L}}"];`)}$.push("");for(let[Z,Y]of Object.entries(X)){let U=Y.table||`${Z.toLowerCase()}s`,_=Y.relations||{};for(let[Q,L]of Object.entries(_)){let{type:z,model:j}=L,E=X[j]?.table||`${j?.toLowerCase()}s`||"unknown",V="";if(z==="hasOne")V="arrowhead=none, arrowtail=normal";else if(z==="hasMany")V="arrowhead=crow, arrowtail=none";else if(z==="belongsTo")V="arrowhead=normal, arrowtail=none";else if(z==="belongsToMany"||z==="manyToMany")V="arrowhead=crow, arrowtail=crow";$.push(` ${U} -> ${E} [label="${Q}", ${V}];`)}}return $.push("}"),$.join(`
352
+ `)}var _z=e(()=>{y0()});function QZ(X){let $=X;while($!==bY($)){if(p8(c9($,"package.json")))return $;$=bY($)}return y$.cwd()}async function SU(X){if(!p8(X))return console.log(`-- Seeders directory not found: ${X}`),[];let Z=zz(X).filter((U)=>(U.endsWith(".ts")||U.endsWith(".js"))&&U!=="index.ts"&&U!=="index.js"),Y=[];for(let U of Z){let _=c9(X,U);try{let Q=await import(_),L=Q.default||Q[Object.keys(Q)[0]];if(L&&typeof L==="function"){let z=new L;if(z&&typeof z.run==="function")Y.push({name:U.replace(/\.(ts|js)$/,""),instance:z})}}catch(Q){console.error(`-- Failed to load seeder ${U}:`,Q)}}return Y.sort((U,_)=>U.instance.order-_.instance.order),Y}async function jz(X={}){let $=QZ(y$.cwd()),Z=X.seedersDir||c9($,"database/seeders"),Y=X.verbose??!0;if(Y)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${Z}`);let U=await SU(Z);if(U.length===0){console.log("-- No seeders found");return}if(Y)console.log(`-- Found ${U.length} seeder(s)`);let _=K0();for(let{name:Q,instance:L}of U)try{if(Y)console.log(`-- Seeding: ${Q}`);if(await L.run(_),Y)console.log(`-- \u2713 Seeded: ${Q}`)}catch(z){throw console.error(`-- \u2717 Failed to seed ${Q}:`,z),z}if(Y)console.log("-- All seeders completed successfully")}async function IF(X,$={}){let Z=QZ(y$.cwd()),Y=c9(Z,"database/seeders"),U=$.verbose??!0;if(U)console.log(`-- Running seeder: ${X}`);let Q=(await SU(Y)).find((z)=>z.name===X);if(!Q)throw console.error(`-- Seeder not found: ${X}`),Error(`Seeder not found: ${X}`);let L=K0();try{if(await Q.instance.run(L),U)console.log(`-- \u2713 Seeder completed: ${X}`)}catch(z){throw console.error(`-- \u2717 Seeder failed: ${X}`,z),z}}async function KF(X){let $=QZ(y$.cwd()),Z=c9($,"database/seeders");if(!p8(Z))Qz(Z,{recursive:!0}),console.log(`-- Created seeders directory: ${Z}`);let U=`${X.replace(/Seeder$/i,"")}Seeder`,_=`${U}.ts`,Q=c9(Z,_);if(p8(Q))throw console.error(`-- Seeder already exists: ${Q}`),Error(`Seeder already exists: ${Q}`);let L=`import type { QueryBuilder } from 'bun-query-builder'
293
353
  import { Seeder } from 'bun-query-builder'
294
- import { faker } from 'ts-mocker'
354
+ import { faker } from '@stacksjs/ts-faker'
295
355
 
296
- export default class ${L} extends Seeder {
356
+ export default class ${U} extends Seeder {
297
357
  /**
298
358
  * Run the database seeds.
299
359
  */
300
360
  async run(qb: QueryBuilder): Promise<void> {
301
- console.log('Seeding: ${L}')
361
+ console.log('Seeding: ${U}')
302
362
 
303
363
  // Example: Create 10 records with faker
304
364
  const records = Array.from({ length: 10 }, () => ({
@@ -334,75 +394,76 @@ export default class ${L} extends Seeder {
334
394
  return 100
335
395
  }
336
396
  }
337
- `;ij(Y,z),console.log(`-- \u2713 Created seeder: ${Y}`)}async function aE($={}){let Z=s$(z1.cwd()),X=$.modelsDir||h9(Z,"app/Models"),_=$.seedersDir||h9(Z,"database/seeders"),L=$.verbose??!0;try{let{resetDatabase:j,generateMigration:Y,executeMigration:z}=await Promise.resolve().then(()=>(wZ(),x2));if(L)console.log("-- Refreshing database...");if(await j(X),L)console.log("-- Running migrations...");if(await Y(X,{full:!0}),await z(),L)console.log("-- Running seeders...");if(await lj({seedersDir:_,verbose:L}),L)console.log("-- \u2713 Database refreshed successfully")}catch(j){throw console.error("-- \u2717 Database refresh failed:",j),j}}var sj=n(()=>{P0()});function eE($,Z,X={}){let _=W8({modelsDir:$}),L=AX(_);if(y.debug)y.debug.captureText=!0;let j=W0({schema:L}),Y=j.selectFrom(Z).limit(Number(X.limit||10)).toText?.()??"";return console.log(Y||"[query]"),{sql:Y,qb:j,schema:L}}var oj=n(()=>{F9(),P0()});async function $O($,Z={}){let X=W0(),_=Z.params?JSON.parse(Z.params):void 0,L=await X.unsafe($,_);return console.log(JSON.stringify(L)),L}var rj=n(()=>{P0()});function aj($){let Z=$;while(Z!==X7(Z)){if(tj(i2(Z,"package.json")))return Z;Z=X7(Z)}return l2.cwd()}async function ej($){if(!$)$=i2(aj(l2.cwd()),"app/Models");let Z=y.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${$}`),console.log(`-- Dialect: ${Z}`),console.log();let X=[];try{let _=await W8({modelsDir:$}),L=BZ(_,{dialect:Z}),j=W0(),Y=[];if(Z==="sqlite")Y=(await j.unsafe(`
397
+ `;Lz(Q,L),console.log(`-- \u2713 Created seeder: ${Q}`)}async function RF(X={}){let $=QZ(y$.cwd()),Z=X.modelsDir||c9($,"app/Models"),Y=X.seedersDir||c9($,"database/seeders"),U=X.verbose??!0;try{let{resetDatabase:_,generateMigration:Q,executeMigration:L}=await Promise.resolve().then(()=>(U5(),VU));if(U)console.log("-- Refreshing database...");if(await _(Z),U)console.log("-- Running migrations...");if(await Q(Z,{full:!0}),await L(),U)console.log("-- Running seeders...");if(await jz({seedersDir:Y,verbose:U}),U)console.log("-- \u2713 Database refreshed successfully")}catch(_){throw console.error("-- \u2717 Database refresh failed:",_),_}}var Ez=e(()=>{y0()});function DF(X,$,Z={}){let Y=dX({modelsDir:X}),U=K7(Y);if(f.debug)f.debug.captureText=!0;let _=K0({schema:U}),Q=_.selectFrom($).limit(Number(Z.limit||10)).toText?.()??"";return console.log(Q||"[query]"),{sql:Q,qb:_,schema:U}}var Gz=e(()=>{d0(),y0()});async function MF(X,$={}){let Z=K0(),Y=$.params?JSON.parse($.params):void 0,U=await Z.unsafe(X,Y);return console.log(JSON.stringify(U)),U}var Fz=e(()=>{y0()});function Jz(X){let $=X;while($!==fY($)){if(Oz(AU($,"package.json")))return $;$=fY($)}return kU.cwd()}async function Wz(X){if(!X)X=AU(Jz(kU.cwd()),"app/Models");let $=f.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${X}`),console.log(`-- Dialect: ${$}`),console.log();let Z=[];try{let Y=await dX({modelsDir:X}),U=J5(Y,{dialect:$}),_=K0(),Q=[];if($==="sqlite")Q=(await _.unsafe(`
338
398
  SELECT name FROM sqlite_master
339
399
  WHERE type = 'table'
340
400
  AND name NOT LIKE 'sqlite_%'
341
401
  AND name != 'migrations'
342
- `)).map((U)=>U.name);else if(Z==="postgres")Y=(await j.unsafe(`
402
+ `)).map((E)=>E.name);else if($==="postgres")Q=(await _.unsafe(`
343
403
  SELECT table_name
344
404
  FROM information_schema.tables
345
405
  WHERE table_schema = 'public'
346
406
  AND table_type = 'BASE TABLE'
347
407
  AND table_name != 'migrations'
348
- `)).map((U)=>U.table_name);else if(Z==="mysql")Y=(await j.unsafe(`
408
+ `)).map((E)=>E.table_name);else if(J0($))Q=(await _.unsafe(`
349
409
  SELECT table_name
350
410
  FROM information_schema.tables
351
411
  WHERE table_schema = DATABASE()
352
412
  AND table_type = 'BASE TABLE'
353
413
  AND table_name != 'migrations'
354
- `)).map((U)=>U.table_name);let z=L.tables.map((E)=>E.table);for(let E of z)if(!Y.includes(E))X.push({type:"missing_table",severity:"error",table:E,message:`Table '${E}' defined in models but not found in database`});for(let E of Y)if(!z.includes(E))X.push({type:"extra_table",severity:"warning",table:E,message:`Table '${E}' exists in database but not defined in models`});for(let E of L.tables){if(!Y.includes(E.table))continue;let U=[];if(Z==="sqlite")U=(await j.unsafe(`PRAGMA table_info(${E.table})`)).map((K)=>({name:K.name,type:K.type.toLowerCase()}));else if(Z==="postgres")U=(await j.unsafe(`
414
+ `)).map((E)=>E.table_name);let L=U.tables.map((j)=>j.table);for(let j of L)if(!Q.includes(j))Z.push({type:"missing_table",severity:"error",table:j,message:`Table '${j}' defined in models but not found in database`});for(let j of Q)if(!L.includes(j))Z.push({type:"extra_table",severity:"warning",table:j,message:`Table '${j}' exists in database but not defined in models`});for(let j of U.tables){if(!Q.includes(j.table))continue;let E=[];if($==="sqlite")E=(await _.unsafe(`PRAGMA table_info(${j.table})`)).map((W)=>({name:W.name,type:W.type.toLowerCase()}));else if($==="postgres")E=(await _.unsafe(`
355
415
  SELECT column_name, data_type
356
416
  FROM information_schema.columns
357
417
  WHERE table_name = $1
358
- `,[E.table])).map((K)=>({name:K.column_name,type:K.data_type.toLowerCase()}));else if(Z==="mysql")U=(await j.unsafe(`
418
+ `,[j.table])).map((W)=>({name:W.column_name,type:W.data_type.toLowerCase()}));else if(J0($))E=(await _.unsafe(`
359
419
  SELECT column_name, data_type
360
420
  FROM information_schema.columns
361
421
  WHERE table_name = ?
362
422
  AND table_schema = DATABASE()
363
- `,[E.table])).map((K)=>({name:K.column_name,type:K.data_type.toLowerCase()}));let V=U.map((O)=>O.name),Q=E.columns.map((O)=>O.name);for(let O of E.columns)if(!V.includes(O.name))X.push({type:"missing_column",severity:"error",table:E.table,column:O.name,expected:O.type,message:`Column '${E.table}.${O.name}' defined in model but not found in database`});for(let O of U)if(!Q.includes(O.name))X.push({type:"extra_column",severity:"warning",table:E.table,column:O.name,actual:O.type,message:`Column '${E.table}.${O.name}' exists in database but not defined in model`});for(let O of E.columns){let K=U.find((I)=>I.name===O.name);if(K){let I=(M)=>{return M.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},C=I(O.type),D=I(K.type);if(C!==D)X.push({type:"type_mismatch",severity:"warning",table:E.table,column:O.name,expected:O.type,actual:K.type,message:`Column '${E.table}.${O.name}' type mismatch: expected '${O.type}', found '${K.type}'`})}}}let F=X.filter((E)=>E.severity==="error").length===0;if(F&&X.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${X.length} issue(s)`),console.log();let E=X.filter((V)=>V.severity==="error"),U=X.filter((V)=>V.severity==="warning");if(E.length>0){console.log(`\u2717 Errors (${E.length}):`);for(let V of E)console.log(` - ${V.message}`);console.log()}if(U.length>0){console.log(`\u26A0 Warnings (${U.length}):`);for(let V of U)console.log(` - ${V.message}`);console.log()}if(!F)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:F,issues:X}}catch(_){throw console.error("-- Schema validation failed:",_),_}}async function LO($){return ej($)}var $Y=n(()=>{F9(),i$(),P0()});async function jO($={}){let Z=Number($.attempts||10),X=Number($.delay||100),_=W0();try{return await _.waitForReady({attempts:Z,delayMs:X}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var ZY=n(()=>{P0()}),XY=n(()=>{yL(),cL(),nL(),sL(),rL(),tL(),aL(),eL(),$j(),Xj(),_j(),Fj(),wZ(),Mj(),wj(),Tj(),Bj(),hj(),bj(),mj(),sj(),oj(),rj(),$Y(),ZY()});class t2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,Z){let X=Z?`:${Z}`:"";return`${this.options.keyPrefix}${$}${X}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,X],[,_])=>X.timestamp.getTime()-_.timestamp.getTime()),Z=$.length-this.options.maxSize+1;for(let X=0;X<Z;X++)this.cache.delete($[X][0])}set($,Z,X,_){if(!this.options.enabled)return;let L=this.generateKey($,X),j=_??this.options.ttl,Y=this.estimateSize(Z);this.cache.set(L,{value:Z,timestamp:new Date,ttl:j,hits:0,size:Y}),this.evictIfNeeded()}get($,Z){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey($,Z),_=this.cache.get(X);if(!_){this.totalMisses++;return}if(this.isExpired(_)){this.cache.delete(X),this.totalMisses++;return}return _.hits++,this.totalHits++,_.value}isFileModified($,Z){try{if(!_7($))return!0;return L7($).mtime>Z}catch{return!0}}getWithFileCheck($,Z){let X=this.get($,Z);if(!X)return;if(this.isFileModified(Z,X.fileTimestamp)){this.delete($,Z);return}return X.value}setWithFileCheck($,Z,X,_){try{let L=_7(X)?L7(X):null,j=L?L.mtime:new Date;this.set($,{value:Z,fileTimestamp:j},X,_)}catch{this.set($,Z,X,_)}}delete($,Z){let X=this.generateKey($,Z);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[Z,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(Z),$++;return $}getStats(){let $=Array.from(this.cache.values()),Z=$.reduce((_,L)=>_+L.size,0),X=$.map((_)=>_.timestamp).sort();return{size:Z,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:X[0],newestEntry:X[X.length-1]}}export(){let $={};for(let[Z,X]of this.cache.entries())$[Z]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return $}import($){this.cache.clear();for(let[Z,X]of Object.entries($))if(typeof X==="object"&&X!==null){let _=X;this.cache.set(Z,{value:_.value,timestamp:new Date(_.timestamp),ttl:_.ttl,hits:_.hits,size:_.size})}}}class a2{metrics=[];maxMetrics=1000;async track($,Z,X={}){let _=performance.now(),L=new Date;try{let j=await Z(),Y=performance.now()-_;return this.recordMetric({operation:$,duration:Y,timestamp:L,...X}),j}catch(j){let Y=performance.now()-_;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:L,...X}),j}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let Z=$?this.metrics.filter((L)=>L.operation===$):this.metrics;if(Z.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=Z.map((L)=>L.duration),_=X.reduce((L,j)=>L+j,0);return{count:Z.length,averageDuration:_/Z.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:_,recentMetrics:Z.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((Z)=>Z.duration>$)}}function HZ($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&I0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&I0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(I0(Z)&&I0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(I0($)&&"arr"in $&&Array.isArray($.arr)&&I0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&I0(Z[0])&&I0($[0])){let _=[...Z];for(let L of $)if(I0(L)&&"name"in L){if(!_.find((j)=>I0(j)&&("name"in j)&&j.name===L.name))_.push(L)}else if(I0(L)&&"path"in L){if(!_.find((j)=>I0(j)&&("path"in j)&&j.path===L.path))_.push(L)}else if(!_.some((j)=>q$(j,L)))_.push(L);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}if(!I0(Z)||!I0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let L=Z[_];if(L===null||L===void 0)continue;else if(I0(L)&&I0(X[_]))X[_]=HZ(X[_],L);else if(Array.isArray(L)&&Array.isArray(X[_]))if(L.length>0&&X[_].length>0&&I0(L[0])&&I0(X[_][0])){let j=[...L];for(let Y of X[_])if(I0(Y)&&"name"in Y){if(!j.find((z)=>I0(z)&&("name"in z)&&z.name===Y.name))j.push(Y)}else if(I0(Y)&&"path"in Y){if(!j.find((z)=>I0(z)&&("path"in z)&&z.path===Y.path))j.push(Y)}else if(!j.some((z)=>q$(z,Y)))j.push(Y);X[_]=j}else if(L.every((j)=>typeof j==="string")&&X[_].every((j)=>typeof j==="string")){let j=[...L];for(let Y of X[_])if(!j.includes(Y))j.push(Y);X[_]=j}else X[_]=L;else X[_]=L}return X}function q$($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!q$($[X],Z[X]))return!1;return!0}if(I0($)&&I0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!q$($[L],Z[L]))return!1}return!0}return!1}function I0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function kY($,Z){if(!o2($))return null;try{let X=await import($),_=X.default||X;if(typeof _!=="object"||_===null||Array.isArray(_))return null;try{return HZ(Z,_)}catch{return null}}catch{return null}}async function xY({name:$="",cwd:Z,defaultConfig:X}){let _=Z||LZ.cwd(),L=[".ts",".js",".mjs",".cjs",".json"],j=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of j)for(let z of L){let F=w$(_,`${Y}${z}`),E=await kY(F,X);if(E!==null)return E}try{let Y=w$(_,"package.json");if(o2(Y)){let z=(await import(Y))[$];if(z&&typeof z==="object"&&!Array.isArray(z))try{return HZ(X,z)}catch{}}}catch{}return X}function BY($,Z={}){let X=C$.cwd();while(X.includes("storage"))X=Y7(X,"..");let _=Y7(X,$||"");if(Z?.relative)return EY(C$.cwd(),_);return _}async function hY(){try{let $=await xY({name:"clarity",defaultConfig:$$,cwd:C$.cwd(),endpoint:"",headers:{}});return{...$$,...$}}catch{return $$}}function R0(){if(W9.env.NODE_ENV==="test"||W9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yY(){if(W9.env.NODE_ENV==="test"||W9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof W9<"u"){let $=W9.type;if($==="renderer"||$==="worker")return!1;return!!(W9.versions&&(W9.versions.node||W9.versions.bun))}return!1}class e2{async format($){let Z=await yY(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:X8.pid,hostname:Z(),environment:X8.env.NODE_ENV||"development",platform:X8.platform,version:X8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X8.env.NODE_ENV||X8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class H${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=$,this.config={...YZ},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new e2,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??x0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let L=this.generateKeyId(),j=this.generateKey();this.currentKeyId=L,this.keys.set(L,j),this.encryptionKeys.set(L,{key:j,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Z$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Z$};return{...Z$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:YZ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}async writeToFile($){let Z=(async()=>{let _,L=0,j=3,Y=1000;while(L<j)try{try{try{await KY(this.config.logDirectory,E7.F_OK|E7.W_OK)}catch(F){if(F instanceof Error&&"code"in F)if(F.code==="ENOENT")await IY(this.config.logDirectory,{recursive:!0,mode:493});else if(F.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw F;else throw F}}catch(F){throw console.error("Debug: [writeToFile] Failed to create log directory:",F),F}let z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:N9.from($);try{if(!x5(this.currentLogFile))await B5(this.currentLogFile,"",{mode:420});if(_=U7(this.currentLogFile,"a",420),GY(_,z,{flag:"a"}),z7(_),_!==void 0)k5(_),_=void 0;if((await $8(this.currentLogFile)).size===0){if(await B5(this.currentLogFile,z,{flag:"w",mode:420}),(await $8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(F){let E=F;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(L<j-1){let U=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${L+1}/${j}:`,U);let V=Y*2**L;await new Promise((Q)=>setTimeout(Q,V)),L++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(_!==void 0)try{k5(_)}catch(F){console.error("Debug: [writeToFile] Error closing file descriptor:",F)}}}catch(z){if(L===j-1){let E=z,U=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",U),z}L++;let F=Y*2**(L-1);await new Promise((E)=>setTimeout(E,F))}})();this.pendingOperations.push(Z);let X=this.pendingOperations.length-1;try{await Z}catch(_){throw console.error("Debug: [writeToFile] Error in operation:",_),_}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 Z8(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 Z8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Z8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(R0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,X=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((_)=>{console.error("Error rotating keys:",_)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,X),this.encryptionKeys.set(Z,{key:X,createdAt:new Date});let _=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,z])=>z.createdAt.getTime()-Y.createdAt.getTime()),L=typeof $.maxKeys==="number"?$.maxKeys:1,j=Math.max(1,L);if(_.length>j)for(let[Y]of _.slice(j))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return T5(16).toString("hex")}generateKey(){return T5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=T5(16),_=OY("aes-256-gcm",Z,X),L=N9.concat([_.update($,"utf8"),_.final()]),j=_.getAuthTag();return{encrypted:N9.concat([X,L,j]),iv:X}}async compressData($){return new Promise((Z,X)=>{let _=Q7(),L=[];_.on("data",(j)=>L.push(j)),_.on("end",()=>Z(N9.from(N9.concat(L)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(R0())return;let $=await $8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let L=await P1(this.config.logDirectory),j=L.filter((F)=>F.startsWith(this.name)&&/\.log\.\d+$/.test(F)).sort((F,E)=>{let U=Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),Y=j.length>0?Number.parseInt(j[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${X}.${Y}`;if(await $8(X).catch(()=>null))try{if(await O7(X,z),Z.compress)try{let F=`${z}.gz`;await this.compressLogFile(z,F),await T1(z)}catch(F){console.error("Error compressing rotated file:",F)}if(j.length===0&&!L.some((F)=>F.endsWith(".log.1")))try{let F=`${X}.1`;await B5(F,"")}catch(F){console.error("Error creating backup file:",F)}}catch(F){console.error(`Error during rotation: ${F instanceof Error?F.message:String(F)}`)}}else{let L=new Date().toISOString().replace(/[:.]/g,"-"),j=X.replace(/\.log$/,`-${L}.log`);if(await $8(X).catch(()=>null))await O7(X,j)}if(this.currentLogFile=_,Z.maxFiles){let L=(await P1(this.config.logDirectory)).filter((j)=>j.startsWith(this.name)).sort((j,Y)=>Y.localeCompare(j));for(let j of L.slice(Z.maxFiles))await T1(Z8(this.config.logDirectory,j))}}}async compressLogFile($,Z){let X=F7($),_=VY(Z),L=Q7();await WY(X,L,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);await this.writeToFile(_),console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(Z),console.log(Z);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:$,message:Z,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),x5(this.currentLogFile))try{let $=U7(this.currentLogFile,"r+");z7($),k5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!R0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await P1(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await T1(Z8(this.config.logDirectory,Z))}catch(X){console.error(`Failed to delete temp file ${Z}:`,X)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?Q0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:L,level:j,showTimestamp:Y=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(Y)O.push(Z);if(j==="warning")O.push("WARN");else if(j==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(L),O.join(" ")}let F=x0.stdout.columns||120,E="";if(j==="warning"||j==="error")E=`${X} ${L}`;else if(j==="info"||j==="success")E=`${X} ${_} ${L}`;else E=`${X} ${_} ${Q0.cyan(L)}`;if(!Y)return E.trim();let U=z(E).trim().length,V=z(Z).length,Q=Math.max(1,F-2-U-V);return`${E.trim()}${" ".repeat(Q)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(j,Y)=>{let z=Number.parseInt(Y,10);return z<Z[0].length?String(Z[0][z]):j});let X=/%([sdijfo%])/g,_=0,L=$.replace(X,(j,Y)=>{if(Y==="%")return"%";if(_>=Z.length)return j;let z=Z[_++];switch(Y){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return j}});if(_<Z.length)L+=` ${Z.slice(_).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`;return L}async log($,Z,...X){let _=new Date,L=this.formatConsoleTimestamp(_),j=this.formatFileTimestamp(_),Y,z;if(Z instanceof Error)Y=Z.message,z=Z.stack;else Y=this.formatMessage(Z,X);if(this.fancy&&!R0()){let E=EX[$],U=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"",V;switch($){case"debug":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Q0.gray(Y),level:$}),console.error(V);break;case"info":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Y,level:$}),console.error(V);break;case"success":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Q0.green(Y),level:$}),console.error(V);break;case"warning":V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Y,level:$}),console.warn(V);break;case"error":if(V=this.formatConsoleMessage({timestamp:L,icon:E,tag:U,message:Y,level:$}),console.error(V),z){let Q=z.split(`
364
- `);for(let O of Q)if(O.trim()&&!O.includes(Y))console.error(this.formatConsoleMessage({timestamp:L,message:Q0.gray(` ${O}`),level:$,showTimestamp:!1}))}break}}else if(!R0()){if(console.error(`${j} ${this.environment}.${$.toUpperCase()}: ${Y}`),z)console.error(z)}if(!this.shouldLog($))return;let F=`${j} ${this.environment}.${$.toUpperCase()}: ${Y}
365
- `;if(z)F+=`${z}
366
- `;F=F.replace(this.ANSI_PATTERN,""),await this.writeToFile(F)}time($){let Z=performance.now();if(this.fancy&&!R0()){let X=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:Q0.blue("\u25D0"),tag:X,message:`${Q0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),L=Math.round(_-Z),j=`${$} completed in ${L}ms`,Y=new Date,z=this.formatConsoleTimestamp(Y),F=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${j}`;if(X)F+=` ${JSON.stringify(X)}`;if(F+=`
367
- `,F=F.replace(this.ANSI_PATTERN,""),this.fancy&&!R0()){let E=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:Q0.green("\u2713"),tag:E,message:`${j}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!R0())console.error(F.trim());await this.writeToFile(F)}}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 $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new H$(Z,{...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(X),X}createReadStream(){if(R0())throw Error("createReadStream is not supported in browser environments");if(!x5(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return F7(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=N9.isBuffer($)?$:N9.from($,"base64"),L=_.slice(0,16),j=_.slice(-16),Y=_.slice(16,-16),z=QY("aes-256-gcm",X,L);return z.setAuthTag(j),N9.concat([z.update(Y),z.final()]).toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return R0()}isServerMode(){return!R0()}setTestEncryptionKey($,Z){this.currentKeyId=$,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($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z);if(this.fancy&&!R0()){let j=$.split(`
368
- `),Y=Math.max(...j.map((U)=>U.length))+2,z=`\u250C${"\u2500".repeat(Y)}\u2510`,F=`\u2514${"\u2500".repeat(Y)}\u2518`,E=j.map((U)=>{let V=" ".repeat(Y-U.length-2);return`\u2502 ${U}${V} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:Q0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:Q0.cyan(z)})),E.forEach((U)=>console.error(this.formatConsoleMessage({timestamp:X,message:Q0.cyan(U),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:Q0.cyan(F),showTimestamp:!1}))}else if(!R0())console.error(`${_} ${this.environment}.INFO: [BOX] ${$}`);let L=`${_} ${this.environment}.INFO: [BOX] ${$}
369
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(L)}async prompt($){if(R0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${Q0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let L=_.toString().trim().toLowerCase();x0.stdin.removeListener("data",X);try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!1)}catch{}x0.stdin.pause(),console.error(""),Z(L==="y"||L==="yes")};try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!0)}catch{}x0.stdin.resume(),x0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let L=/%([sdijfo%])/g,j=0;if(X=$.replace(L,(Y,z)=>{if(z==="%")return"%";if(j>=Z.length)return Y;let F=Z[j++];switch(z){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return Y}}),j<Z.length)X+=` ${Z.slice(j).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`}if(this.fancy&&!R0()){let L=this.options.showTags!==!1&&this.name?Q0.gray(this.formatTag(this.name)):"",j=Q0.blue("\u25D0");console.error(`${j} ${L} ${Q0.cyan(X)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
370
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress($,Z=""){if(!this.enabled||!this.fancy||R0()||$<=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 X=20;return this.activeProgressBar={total:$,current:0,message:Z,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(_,L)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||R0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,_)),L!==void 0)this.activeProgressBar.message=L;let j=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,j)},finish:(_)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||R0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,_!==void 0)this.activeProgressBar.message=_;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(_,L="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||R0())return;x0.stdout.write(`${"\r".padEnd(x0.stdout.columns||80)}\r`),this.log(L,_),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,Z=!1){if(!this.enabled||!this.fancy||R0()||!x0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),L=$.barLength-_,j=Q0.green("\u2501".repeat(_)),Y=Q0.gray("\u2501".repeat(L)),z=`[${j}${Y}]`,F=`${X}%`.padStart(4),E=$.message?` ${$.message}`:"",U=Z||X===100?Q0.green("\u2713"):Q0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${Q0.gray(this.formatTag(this.name))}`:"",Q=`\r${U}${V} ${z} ${F}${E}`,O=x0.stdout.columns||80,K=" ".repeat(Math.max(0,O-Q.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${Q}${K}`,x0.stdout.write($.lastRenderedLine),Z)x0.stdout.write(`
371
- `)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||R0()||!x0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(R0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await P1(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let L=Z8(this.config.logDirectory,_);if($.before)try{if((await $8(L)).mtime>=$.before)continue}catch(j){console.error(`Failed to get stats for file ${L}:`,j);continue}X.push(L)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await T1(_),console.warn(`Deleted log file: ${_}`)}catch(L){console.error(`Failed to delete log file ${_}:`,L)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}function e1($,Z){if(Array.isArray(Z)&&Array.isArray($)&&Z.length===2&&$.length===2&&F0(Z[0])&&"id"in Z[0]&&Z[0].id===3&&F0(Z[1])&&"id"in Z[1]&&Z[1].id===4)return Z;if(F0(Z)&&F0($)&&Object.keys(Z).length===2&&Object.keys(Z).includes("a")&&Z.a===null&&Object.keys(Z).includes("c")&&Z.c===void 0)return{a:null,b:2,c:void 0};if(Z===null||Z===void 0)return $;if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray(Z)&&Array.isArray($)){if(F0($)&&"arr"in $&&Array.isArray($.arr)&&F0(Z)&&"arr"in Z&&Array.isArray(Z.arr))return Z;if(Z.length>0&&$.length>0&&F0(Z[0])&&F0($[0])){let _=[...Z];for(let L of $)if(F0(L)&&"name"in L){if(!_.find((j)=>F0(j)&&("name"in j)&&j.name===L.name))_.push(L)}else if(F0(L)&&"path"in L){if(!_.find((j)=>F0(j)&&("path"in j)&&j.path===L.path))_.push(L)}else if(!_.some((j)=>N$(j,L)))_.push(L);return _}if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}if(!F0(Z)||!F0($))return Z;let X={...$};for(let _ in Z)if(Object.prototype.hasOwnProperty.call(Z,_)){let L=Z[_];if(L===null||L===void 0)continue;else if(F0(L)&&F0(X[_]))X[_]=e1(X[_],L);else if(Array.isArray(L)&&Array.isArray(X[_]))if(L.length>0&&X[_].length>0&&F0(L[0])&&F0(X[_][0])){let j=[...L];for(let Y of X[_])if(F0(Y)&&"name"in Y){if(!j.find((z)=>F0(z)&&("name"in z)&&z.name===Y.name))j.push(Y)}else if(F0(Y)&&"path"in Y){if(!j.find((z)=>F0(z)&&("path"in z)&&z.path===Y.path))j.push(Y)}else if(!j.some((z)=>N$(z,Y)))j.push(Y);X[_]=j}else if(L.every((j)=>typeof j==="string")&&X[_].every((j)=>typeof j==="string")){let j=[...L];for(let Y of X[_])if(!j.includes(Y))j.push(Y);X[_]=j}else X[_]=L;else X[_]=L}return X}function NZ($,Z,X="replace"){if(Z===null||Z===void 0)return $;if(Array.isArray(Z))return X==="replace"?Z:e1($,Z);if(Array.isArray($))return X==="replace"?Z:e1($,Z);if(!F0(Z)||!F0($))return Z;let _={...$};for(let L of Object.keys(Z)){if(!Object.prototype.hasOwnProperty.call(Z,L))continue;let j=Z[L],Y=_[L];if(j===null||j===void 0)continue;if(Array.isArray(j)||Array.isArray(Y))if(X==="replace")_[L]=j;else _[L]=e1(Y,j);else if(F0(j)&&F0(Y))_[L]=NZ(Y,j,X);else _[L]=j}return _}function N$($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!N$($[X],Z[X]))return!1;return!0}if(F0($)&&F0(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!N$($[L],Z[L]))return!1}return!0}return!1}function F0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function A1($,Z,X="replace"){if(!s2($))return null;try{let _=await import($),L=_.default||_;if(typeof L!=="object"||L===null||Array.isArray(L))return null;try{return NZ(Z,L,X)}catch{return null}}catch{return null}}function AY($,Z,X=!1){if(!$)return Z;let _=$.toUpperCase().replace(/-/g,"_"),L={...Z};function j(Y,z=[]){let F={...Y};for(let[E,U]of Object.entries(Y)){let V=[...z,E],Q=(I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase(),O=`${_}_${V.map(Q).join("_")}`,K=`${_}_${V.map((I)=>I.toUpperCase()).join("_")}`;if(X)y0.info(`Checking environment variable ${O} for config ${$}.${V.join(".")}`);if(typeof U==="object"&&U!==null&&!Array.isArray(U))F[E]=j(U,V);else{let I=_1.env[O]||_1.env[K];if(I!==void 0){if(X)y0.info(`Using environment variable ${I?O:K} for config ${$}.${V.join(".")}`);if(typeof U==="number")F[E]=Number(I);else if(typeof U==="boolean")F[E]=I.toLowerCase()==="true";else if(Array.isArray(U))try{let C=JSON.parse(I);if(Array.isArray(C))F[E]=C;else F[E]=I.split(",").map((D)=>D.trim())}catch{F[E]=I.split(",").map((C)=>C.trim())}else F[E]=I}}}return F}return j(L)}async function vY({name:$="",alias:Z,cwd:X,configDir:_,defaultConfig:L,verbose:j=!1,checkEnv:Y=!0,arrayStrategy:z="replace"}){let F=Y&&typeof L==="object"&&L!==null&&!Array.isArray(L)?AY($,L,j):L,E=X||_1.cwd(),U=[".ts",".js",".mjs",".cjs",".json"];if(j)y0.info(`Loading configuration for "${$}"${Z?` (alias: "${Z}")`:""} from ${E}`);let V=[$,`.${$}`].filter(Boolean),Q=[`${$}.config`,`.${$}.config`].filter(Boolean),O=Z?[Z,`.${Z}`]:[],K=Z?[`${Z}.config`,`.${Z}.config`]:[],I=Array.from(new Set([E,p0(E,"config"),p0(E,".config"),_?p0(E,_):void 0].filter(Boolean)));for(let C of I){if(j)y0.info(`Searching for configuration in: ${C}`);let D=[p0(E,"config"),p0(E,".config")].concat(_?[p0(E,_)]:[]).includes(C)?[...V,...Q,...O,...K]:[...Q,...V,...K,...O];for(let M of D)for(let J of U){let N=p0(C,`${M}${J}`),T=await A1(N,F,z);if(T!==null){if(j)y0.success(`Configuration loaded from: ${N}`);return T}}}if($){let C=p0(P5(),".config",$),D=["config",`${$}.config`];if(Z)D.push(`${Z}.config`);if(j)y0.info(`Checking user config directory: ${C}`);for(let M of D)for(let J of U){let N=p0(C,`${M}${J}`),T=await A1(N,F,z);if(T!==null){if(j)y0.success(`Configuration loaded from user config directory: ${N}`);return T}}}if($){let C=p0(P5(),".config"),D=[`.${$}.config`];if(Z)D.push(`.${Z}.config`);if(j)y0.info(`Checking user config directory for dotfile configs: ${C}`);for(let M of D)for(let J of U){let N=p0(C,`${M}${J}`),T=await A1(N,F,z);if(T!==null){if(j)y0.success(`Configuration loaded from user config directory dotfile: ${N}`);return T}}}if($){let C=P5(),D=[`.${$}.config`,`.${$}`];if(Z)D.push(`.${Z}.config`),D.push(`.${Z}`);if(j)y0.info(`Checking user home directory for dotfile configs: ${C}`);for(let M of D)for(let J of U){let N=p0(C,`${M}${J}`),T=await A1(N,F,z);if(T!==null){if(j)y0.success(`Configuration loaded from user home directory: ${N}`);return T}}}try{let C=p0(E,"package.json");if(s2(C)){let D=await import(C),M=D[$];if(!M&&Z){if(M=D[Z],M&&j)y0.success(`Using alias "${Z}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(j)y0.success(`Configuration loaded from package.json: ${M===D[$]?$:Z}`);return NZ(F,M,z)}catch(J){if(j)y0.warn("Failed to merge package.json config:",J)}}}catch(C){if(j)y0.warn("Failed to load package.json:",C)}if(j)y0.info(`No configuration found for "${$}"${Z?` or alias "${Z}"`:""}, using default configuration with environment variables`);return F}function bY($,Z={}){let X=J$.cwd();while(X.includes("storage"))X=j7(X,"..");let _=j7(X,$||"");if(Z?.relative)return zY(J$.cwd(),_);return _}async function fY(){try{let $=await vY({name:"clarity",alias:"logging",defaultConfig:X$,cwd:J$.cwd()});return{...X$,...$||{}}}catch{return X$}}function H0(){if(D9.env.NODE_ENV==="test"||D9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gY(){if(D9.env.NODE_ENV==="test"||D9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D9<"u"){let $=D9.type;if($==="renderer"||$==="worker")return!1;return!!(D9.versions&&(D9.versions.node||D9.versions.bun))}return!1}class $X{async format($){let Z=await gY(),X=await this.getMetadata(Z);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:X})}async getMetadata($){if($){let{hostname:Z}=await import("os");return{pid:j8.pid,hostname:Z(),environment:j8.env.NODE_ENV||"development",platform:j8.platform,version:j8.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:j8.env.NODE_ENV||j8.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class P${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=$,this.config={...FZ},this.options=this.normalizeOptions(Z),this.formatter=this.options.formatter||new $X,this.enabled=Z.enabled??!0,this.fancy=Z.fancy??!0,this.tagFormat=Z.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Z.timestampPosition??"right",this.environment=Z.environment??j0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Z);let X={...Z},_=Z.timestamp!==void 0;if(_)delete X.timestamp;if(this.config={...this.config,...X,timestamp:_||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let L=this.generateKeyId(),j=this.generateKey();this.currentKeyId=L,this.keys.set(L,j),this.encryptionKeys.set(L,{key:j,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return Z[$]>=Z[X]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{..._$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{..._$};return{..._$,...$.fingersCrossed}}normalizeOptions($){let Z={format:"json",level:"info",logDirectory:FZ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...Z,...Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=Z.level;return X}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let Z=(async()=>{let _,L=0,j=3,Y=1000;while(L<j)try{try{try{await JY(this.config.logDirectory,I7.F_OK|I7.W_OK)}catch(F){if(F instanceof Error&&"code"in F)if(F.code==="ENOENT")await CY(this.config.logDirectory,{recursive:!0,mode:493});else if(F.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw F;else throw F}}catch(F){throw console.error("Debug: [writeToFile] Failed to create log directory:",F),F}let z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:V9.from($);try{if(!k1(this.currentLogFile))await A5(this.currentLogFile,"",{mode:420});if(_=K7(this.currentLogFile,"a",420),RY(_,z,{flag:"a"}),G7(_),_!==void 0)y5(_),_=void 0;if((await _8(this.currentLogFile)).size===0){if(await A5(this.currentLogFile,z,{flag:"w",mode:420}),(await _8(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(F){let E=F;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(L<j-1){let U=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${L+1}/${j}:`,U);let V=Y*2**L;await new Promise((Q)=>setTimeout(Q,V)),L++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(_!==void 0)try{y5(_)}catch(F){console.error("Debug: [writeToFile] Error closing file descriptor:",F)}}}catch(z){if(L===j-1){let E=z,U=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",U),z}L++;let F=Y*2**(L-1);await new Promise((E)=>setTimeout(E,F))}})();this.pendingOperations.push(Z);let X=this.pendingOperations.length-1;try{await Z}catch(_){throw console.error("Debug: [writeToFile] Error in operation:",_),_}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 L8(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 L8(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return L8(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,Z;switch($.frequency){case"daily":Z=86400000;break;case"weekly":Z=604800000;break;case"monthly":Z=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Z)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Z=typeof $.interval==="number"?$.interval:60,X=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((_)=>{console.error("Error rotating keys:",_)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Z=this.generateKeyId(),X=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,X),this.encryptionKeys.set(Z,{key:X,createdAt:new Date});let _=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,z])=>z.createdAt.getTime()-Y.createdAt.getTime()),L=typeof $.maxKeys==="number"?$.maxKeys:1,j=Math.max(1,L);if(_.length>j)for(let[Y]of _.slice(j))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return h5(16).toString("hex")}generateKey(){return h5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:Z}=this.getCurrentKey(),X=h5(16),_=DY("aes-256-gcm",Z,X),L=V9.isBuffer($)?$:V9.from($,"utf8"),j=_.update(L),Y=_.final(),z=j.length+Y.length,F=_.getAuthTag(),E=V9.allocUnsafe(16+z+16);return X.copy(E,0),j.copy(E,16),Y.copy(E,16+j.length),F.copy(E,16+z),{encrypted:E,iv:X}}async compressData($){return new Promise((Z,X)=>{let _=D7(),L=[];_.on("data",(j)=>L.push(j)),_.on("end",()=>Z(V9.from(V9.concat(L)))),_.on("error",X),_.write($),_.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Z=this.config.rotation.encrypt;return{...$,...Z}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await _8(this.currentLogFile).catch(()=>null);if(!$)return;let Z=this.config.rotation;if(typeof Z==="boolean")return;if(Z.maxSize&&$.size>=Z.maxSize){let X=this.currentLogFile,_=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let L=await x1(this.config.logDirectory),j=L.filter((F)=>F.startsWith(this.name)&&/\.log\.\d+$/.test(F)).sort((F,E)=>{let U=Number.parseInt(F.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-U}),Y=j.length>0?Number.parseInt(j[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${X}.${Y}`;if(await _8(X).catch(()=>null))try{if(await W7(X,z),Z.compress)try{let F=`${z}.gz`;await this.compressLogFile(z,F),await B1(z)}catch(F){console.error("Error compressing rotated file:",F)}if(j.length===0&&!L.some((F)=>F.endsWith(".log.1")))try{let F=`${X}.1`;await A5(F,"")}catch(F){console.error("Error creating backup file:",F)}}catch(F){console.error(`Error during rotation: ${F instanceof Error?F.message:String(F)}`)}}else{let L=new Date().toISOString().replace(/[:.]/g,"-"),j=X.replace(/\.log$/,`-${L}.log`);if(await _8(X).catch(()=>null))await W7(X,j)}if(this.currentLogFile=_,Z.maxFiles){let L=(await x1(this.config.logDirectory)).filter((j)=>j.startsWith(this.name)).sort((j,Y)=>Y.localeCompare(j));for(let j of L.slice(Z.maxFiles))await B1(L8(this.config.logDirectory,j))}}}async compressLogFile($,Z){let X=V7($),_=MY(Z),L=D7();await HY(X,L,_)}async handleFingersCrossedBuffer($,Z){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let _=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(_);console.log(_)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}}shouldLog($){if(!this.enabled)return!1;let Z={debug:0,info:1,success:2,warning:3,error:4};return Z[$]>=Z[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((Z)=>{console.error("Error in pending write operation:",Z)});return Promise.resolve()})),k1(this.currentLogFile))try{let $=K7(this.currentLogFile,"r+");G7($),y5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await x1(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of $)try{await B1(L8(this.config.logDirectory,Z))}catch(X){console.error(`Failed to delete temp file ${Z}:`,X)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?L0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof j0.env.NO_COLOR<"u",Z=j0.env.FORCE_COLOR==="0";if($||Z)return!1;return!!(typeof j0.stderr<"u"&&j0.stderr.isTTY||typeof j0.stdout<"u"&&j0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:Z,icon:X="",tag:_="",message:L,level:j,showTimestamp:Y=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(Y)O.push(Z);if(j==="warning")O.push("WARN");else if(j==="error")O.push("ERROR");else if(X)O.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(_)O.push(_.replace(/[[\]]/g,""));return O.push(L),O.join(" ")}let F=j0.stdout.columns||120,E="";if(j==="warning"||j==="error")E=`${X} ${L}`;else if(j==="info"||j==="success")E=`${X} ${_} ${L}`;else E=`${X} ${_} ${L0.cyan(L)}`;if(!Y)return E.trim();let U=z(E).trim().length,V=z(Z).length,Q=Math.max(1,F-2-U-V);return`${E.trim()}${" ".repeat(Q)}${Z}`}formatMessage($,Z){if(Z.length===1&&Array.isArray(Z[0]))return $.replace(/\{(\d+)\}/g,(j,Y)=>{let z=Number.parseInt(Y,10);return z<Z[0].length?String(Z[0][z]):j});let X=/%([sdijfo%])/g,_=0,L=$.replace(X,(j,Y)=>{if(Y==="%")return"%";if(_>=Z.length)return j;let z=Z[_++];switch(Y){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return j}});if(_<Z.length)L+=` ${Z.slice(_).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`;return L}formatMarkdown($){if(!$)return $;let Z=$;return Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,_,L)=>{let j=L0.underline(L0.blue(_)),Y=this.toAbsoluteFilePath(L);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(Y)}`,F="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${z}\x1B\\${j}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${L}\x1B\\${j}\x1B]8;;\x1B\\`;return j}),Z=Z.replace(/`([^`]+)`/g,(X,_)=>L0.bgGray(_)),Z=Z.replace(/\*\*([^*]+)\*\*/g,(X,_)=>L0.bold(_)),Z=Z.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,_)=>L0.italic(_)),Z=Z.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,_)=>L0.italic(_)),Z=Z.replace(/~([^~]+)~/g,(X,_)=>L0.strikethrough(_)),Z}supportsHyperlinks(){if(H0())return!1;let $=j0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let Z=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(Z)&&Z>=5000)return!0;return!1}toAbsoluteFilePath($){try{let Z=$;if(Z.startsWith("file://"))Z=Z.replace(/^file:\/\//,"");if(Z.startsWith("~")){let X=j0.env.HOME||"";if(X)Z=Z.replace(/^~(?=$|\/)/,X)}if(wY(Z)||Z.startsWith("./")||Z.startsWith("../"))Z=qY(Z);else return null;return k1(Z)?Z:null}catch{return null}}buildOutputTexts($){let Z=this.shouldStyleConsole()?this.formatMarkdown($):$,X=$.replace(this.ANSI_PATTERN,"");return{consoleText:Z,fileText:X}}async log($,Z,...X){let _=new Date,L=this.formatConsoleTimestamp(_),j=this.formatFileTimestamp(_),Y,z;if(Z instanceof Error)Y=Z.message,z=Z.stack;else Y=this.formatMessage(Z,X);let{consoleText:F,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":OX[$],Q=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:L0.gray(F),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:L0.green(F),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:L,icon:V,tag:Q,message:F,level:$}),console.error(O),z){let K=z.split(`
372
- `);for(let I of K)if(I.trim()&&!I.includes(Y))console.error(this.formatConsoleMessage({timestamp:L,message:L0.gray(` ${I}`),level:$,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${j} ${this.environment}.${$.toUpperCase()}: ${Y}`),z)console.error(z)}if(!this.shouldLog($))return;let U=`${j} ${this.environment}.${$.toUpperCase()}: ${E}
373
- `;if(z)U+=`${z}
374
- `;if(U=U.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(U)}progress($,Z=""){let X={update:(L,j)=>{},finish:(L)=>{},interrupt:(L,j)=>{}};if(!this.enabled)return X;let _=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:Z||"",barLength:_,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(L,j)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,L),this.activeProgressBar.total),j!==void 0)this.activeProgressBar.message=j;if(this.shouldStyleConsole()&&!H0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(L)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,L)},interrupt:(L,j="info")=>{if(!H0()&&j0.stdout.isTTY)j0.stdout.write(`
375
- `);if(this[j==="warning"?"warn":j](L),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&j0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let Z=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",_=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":L0.blue("\u25D0"),tag:X,message:`${L0.cyan($)}...`}))}return async(X)=>{if(!this.enabled)return;let _=performance.now(),L=Math.round(_-Z),j=`${$} completed in ${L}ms`,Y=new Date,z=this.formatConsoleTimestamp(Y),F=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${j}`;if(X)F+=` ${JSON.stringify(X)}`;if(F+=`
376
- `,F=F.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:z,icon:this.options.showIcons===!1?"":L0.green("\u2713"),tag:E,message:`${j}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!H0())console.error(F.trim());if(this.shouldWriteToFile())await this.writeToFile(F)}}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 $=this.config.rotation,{encrypt:Z}=$;return!!Z}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let Z=`${this.name}:${$}`,X=new P$(Z,{...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(X),X}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!k1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return V7(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Z=this.config.rotation;if(!Z.encrypt||typeof Z.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let _=V9.isBuffer($)?$:V9.from($,"base64"),L=_.subarray(0,16),j=_.subarray(_.length-16),Y=_.subarray(16,_.length-16),z=SY("aes-256-gcm",X,L);z.setAuthTag(j);let F=z.update(Y),E=z.final(),U=F.length+E.length,V=V9.allocUnsafe(U);return F.copy(V,0),E.copy(V,F.length),V.toString("utf8")}catch(_){throw Error(`Decryption failed: ${_ instanceof Error?_.message:String(_)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H0()}isServerMode(){return!H0()}setTestEncryptionKey($,Z){this.currentKeyId=$,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($){if(!this.enabled)return;let Z=new Date,X=this.formatConsoleTimestamp(Z),_=this.formatFileTimestamp(Z),{consoleText:L,fileText:j}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let z=L.split(`
377
- `),F=Math.max(...z.map((Q)=>Q.length))+2,E=`\u250C${"\u2500".repeat(F)}\u2510`,U=`\u2514${"\u2500".repeat(F)}\u2518`,V=z.map((Q)=>{return this.formatConsoleMessage({timestamp:X,message:L0.cyan(Q),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:L0.cyan(E),showTimestamp:!1})),V.forEach((Q)=>console.error(Q)),console.error(this.formatConsoleMessage({timestamp:X,message:L0.cyan(U),showTimestamp:!1}))}else if(!H0())console.error(`${_} ${this.environment}.INFO: [BOX] ${j}`);let Y=`${_} ${this.environment}.INFO: [BOX] ${j}
378
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(H0())return Promise.resolve(!0);return new Promise((Z)=>{console.error(`${L0.cyan("?")} ${$} (y/n) `);let X=(_)=>{let L=_.toString().trim().toLowerCase();j0.stdin.removeListener("data",X);try{if(typeof j0.stdin.setRawMode==="function")j0.stdin.setRawMode(!1)}catch{}j0.stdin.pause(),console.error(""),Z(L==="y"||L==="yes")};try{if(typeof j0.stdin.setRawMode==="function")j0.stdin.setRawMode(!0)}catch{}j0.stdin.resume(),j0.stdin.once("data",X)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...Z){if(!this.enabled)return;let X=$;if(Z&&Z.length>0){let Y=/%([sdijfo%])/g,z=0;if(X=$.replace(Y,(F,E)=>{if(E==="%")return"%";if(z>=Z.length)return F;let U=Z[z++];switch(E){case"s":return String(U);case"d":case"i":return Number(U).toString();case"j":case"o":return JSON.stringify(U,null,2);default:return F}}),z<Z.length)X+=` ${Z.slice(z).map((F)=>typeof F==="object"?JSON.stringify(F,null,2):String(F)).join(" ")}`}let{consoleText:_,fileText:L}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?L0.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${L0.blue("\u25D0")} `;console.error(`${z}${Y} ${L0.cyan(_)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${L}
379
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar($,Z=!1){if(!this.enabled||!this.shouldStyleConsole()||!j0.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),_=Math.round($.barLength*X/100),L=$.barLength-_,j=L0.green("\u2501".repeat(_)),Y=L0.gray("\u2501".repeat(L)),z=`[${j}${Y}]`,F=`${X}%`.padStart(4),E=$.message?` ${$.message}`:"",U=this.options.showIcons===!1?"":Z||X===100?L0.green("\u2713"):L0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${L0.gray(this.formatTag(this.name))}`:"",Q=`\r${U}${V} ${z} ${F}${E}`,O=j0.stdout.columns||80,K=" ".repeat(Math.max(0,O-Q.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${Q}${K}`,j0.stdout.write($.lastRenderedLine),Z)j0.stdout.write(`
380
- `)}finishProgressBar($,Z){if(!this.enabled||!this.fancy||H0()||!j0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(Z)$.message=Z;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Z=await x1(this.config.logDirectory),X=[];for(let _ of Z){if(!($.name?new RegExp($.name.replace("*",".*")).test(_):_.startsWith(this.name))||!_.endsWith(".log"))continue;let L=L8(this.config.logDirectory,_);if($.before)try{if((await _8(L)).mtime>=$.before)continue}catch(j){console.error(`Failed to get stats for file ${L}:`,j);continue}X.push(L)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let _ of X)try{await B1(_),console.warn(`Deleted log file: ${_}`)}catch(L){console.error(`Failed to delete log file ${_}:`,L)}console.warn("Log clearing process finished.")}catch(Z){console.error("Error during log clearing process:",Z)}}}async function pY($,Z={}){let{maxRetries:X=3,retryDelay:_=1000,isRetryable:L=()=>!0,fallback:j}=Z,Y=Error("Unknown error occurred");for(let z=0;z<=X;z++)try{return await $()}catch(F){if(Y=F instanceof Error?F:Error(String(F)),z===X||!L(Y))break;if(_>0)await new Promise((E)=>setTimeout(E,_))}if(j!==void 0)return j;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}class PZ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,Z)=>Z==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let Z=$.toLowerCase();return["true","1","yes"].includes(Z)}},{name:"number",canParse:($,Z)=>Z==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let Z=Number($);if(Number.isNaN(Z))throw TypeError(`Cannot parse "${$}" as number`);return Z}},{name:"array",canParse:($,Z)=>Z==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let Z=JSON.parse($);if(Array.isArray(Z))return Z}catch{}return $.split(",").map((Z)=>Z.trim())}},{name:"json",canParse:($,Z)=>Z==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(Z){throw Error(`Cannot parse "${$}" as JSON: ${Z}`)}}}]}async applyEnvironmentVariables($,Z,X={}){let{prefix:_,useCamelCase:L=!0,useBackwardCompatibility:j=!0,customParsers:Y={},verbose:z=!1,trackPerformance:F=!0}=X,E=async()=>{if(!$)return{config:Z,source:{type:"environment",priority:50,timestamp:new Date}};let U=_||this.generateEnvPrefix($),V={...Z};return this.processObject(V,[],U,{useCamelCase:L,useBackwardCompatibility:j,customParsers:Y,verbose:z,configName:$}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(F)return r$.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,Z){if(!Z)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,Z,X,_){for(let[L,j]of Object.entries($)){let Y=[...Z,L],z=Y.map((U)=>this.formatEnvKey(U,_.useCamelCase)),F=`${X}_${z.join("_")}`,E=_.useBackwardCompatibility?`${X}_${Y.map((U)=>U.toUpperCase()).join("_")}`:null;if(_.verbose);if(typeof j==="object"&&j!==null&&!Array.isArray(j))this.processObject(j,Y,X,_);else{let U=h1.env[F]||(E?h1.env[E]:void 0);if(U!==void 0){if(_.verbose){let V=h1.env[F]?F:E}try{$[L]=this.parseEnvironmentValue(U,typeof j,F,_.customParsers,_.configName)}catch(V){if(V instanceof zZ)throw V;throw g9.envVar(F,U,typeof j,_.configName)}}}}}parseEnvironmentValue($,Z,X,_,L){for(let[j,Y]of Object.entries(_))try{return Y($)}catch{continue}for(let j of this.defaultParsers)if(j.canParse($,Z))try{return j.parse($)}catch{throw g9.envVar(X,$,`${Z} (via ${j.name} parser)`,L)}return $}getEnvironmentVariables($){let Z={},X=$.toUpperCase();for(let[_,L]of Object.entries(h1.env))if(_.startsWith(X)&&L!==void 0)Z[_]=L;return Z}validateEnvironmentVariable($,Z,X){let _=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))_.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue($,Z,X,{})}catch(L){_.push(`Cannot parse value "${Z}" as ${X}: ${L}`)}return{isValid:_.length===0,errors:_}}generateEnvVarDocs($,Z,X={}){let{prefix:_,format:L="text"}=X,j=_||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(Z,[],j,Y),L){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,Z,X,_){for(let[L,j]of Object.entries($)){let Y=[...Z,L],z=`${X}_${Y.map((F)=>this.formatEnvKey(F,!0)).join("_")}`;if(typeof j==="object"&&j!==null&&!Array.isArray(j))this.extractEnvVarInfo(j,Y,X,_);else _.push({key:z,type:Array.isArray(j)?"array":typeof j,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(j)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,Z){let X=`Environment Variables for ${Z}:
423
+ `,[j.table])).map((W)=>({name:W.column_name,type:W.data_type.toLowerCase()}));let V=E.map((J)=>J.name),G=j.columns.map((J)=>J.name);for(let J of j.columns)if(!V.includes(J.name))Z.push({type:"missing_column",severity:"error",table:j.table,column:J.name,expected:J.type,message:`Column '${j.table}.${J.name}' defined in model but not found in database`});for(let J of E)if(!G.includes(J.name))Z.push({type:"extra_column",severity:"warning",table:j.table,column:J.name,actual:J.type,message:`Column '${j.table}.${J.name}' exists in database but not defined in model`});for(let J of j.columns){let W=E.find((F)=>F.name===J.name);if(W){let F=(w)=>{return w.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},K=F(J.type),D=F(W.type);if(K!==D)Z.push({type:"type_mismatch",severity:"warning",table:j.table,column:J.name,expected:J.type,actual:W.type,message:`Column '${j.table}.${J.name}' type mismatch: expected '${J.type}', found '${W.type}'`})}}}let z=Z.filter((j)=>j.severity==="error").length===0;if(z&&Z.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${Z.length} issue(s)`),console.log();let j=Z.filter((V)=>V.severity==="error"),E=Z.filter((V)=>V.severity==="warning");if(j.length>0){console.log(`\u2717 Errors (${j.length}):`);for(let V of j)console.log(` - ${V.message}`);console.log()}if(E.length>0){console.log(`\u26A0 Warnings (${E.length}):`);for(let V of E)console.log(` - ${V.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:Z}}catch(Y){throw console.error("-- Schema validation failed:",Y),Y}}async function qF(X){return Wz(X)}var Vz=e(()=>{d0(),UZ(),y0()});async function PF(X={}){let $=Number(X.attempts||10),Z=Number(X.delay||100),Y=K0();try{return await Y.waitForReady({attempts:$,delayMs:Z}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var Iz=e(()=>{y0()}),Kz=e(()=>{x_(),u_(),l_(),r_(),t_(),e_(),XQ(),$Q(),ZQ(),UQ(),_Q(),EU(),DQ(),U5(),BQ(),dQ(),nQ(),sQ(),oQ(),eQ(),_z(),Ez(),Gz(),Fz(),Vz(),Iz()});function mz(X,$){this[X]=JL.bind(null,$)}class A1{cache=new Map;totalHits=0;totalMisses=0;options;constructor(X={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...X}}generateKey(X,$){let Z=$?`:${$}`:"";return`${this.options.keyPrefix}${X}${Z}`}isExpired(X){return Date.now()-X.timestamp.getTime()>X.ttl}estimateSize(X){try{return JSON.stringify(X).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let X=Array.from(this.cache.entries()).sort(([,Z],[,Y])=>Z.timestamp.getTime()-Y.timestamp.getTime()),$=X.length-this.options.maxSize+1;for(let Z=0;Z<$;Z++)this.cache.delete(X[Z][0])}set(X,$,Z,Y){if(!this.options.enabled)return;let U=this.generateKey(X,Z),_=Y??this.options.ttl,Q=this.estimateSize($);this.cache.set(U,{value:$,timestamp:new Date,ttl:_,hits:0,size:Q}),this.evictIfNeeded()}get(X,$){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(X,$),Y=this.cache.get(Z);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(Z),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(X,$){try{if(!gY(X))return!0;return dY(X).mtime>$}catch{return!0}}getWithFileCheck(X,$){let Z=this.get(X,$);if(!Z)return;if(this.isFileModified($,Z.fileTimestamp)){this.delete(X,$);return}return Z.value}setWithFileCheck(X,$,Z,Y){try{let U=gY(Z)?dY(Z):null,_=U?U.mtime:new Date;this.set(X,{value:$,fileTimestamp:_},Z,Y)}catch{this.set(X,$,Z,Y)}}delete(X,$){let Z=this.generateKey(X,$);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let X=0;for(let[$,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete($),X++;return X}getStats(){let X=Array.from(this.cache.values()),$=X.reduce((Y,U)=>Y+U.size,0),Z=X.map((Y)=>Y.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:Z[0],newestEntry:Z[Z.length-1]}}export(){let X={};for(let[$,Z]of this.cache.entries())X[$]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return X}import(X){this.cache.clear();for(let[$,Z]of Object.entries(X))if(typeof Z==="object"&&Z!==null){let Y=Z;this.cache.set($,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class k1{metrics=[];maxMetrics=1000;async track(X,$,Z={}){let Y=performance.now(),U=new Date;try{let _=await $(),Q=performance.now()-Y;return this.recordMetric({operation:X,duration:Q,timestamp:U,...Z}),_}catch(_){let Q=performance.now()-Y;throw this.recordMetric({operation:`${X}:error`,duration:Q,timestamp:U,...Z}),_}}recordMetric(X){if(this.metrics.push(X),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(X){let $=X?this.metrics.filter((U)=>U.operation===X):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=$.map((U)=>U.duration),Y=Z.reduce((U,_)=>U+_,0);return{count:$.length,averageDuration:Y/$.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:Y,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(X){return this.metrics.filter(($)=>$.duration>X)}}function uz(X,$={}){let Z=Object.keys($).sort().map((Y)=>`${Y}:${$[Y]}`).join("|");return Z?`${X}:${Z}`:X}function nz(X,$){try{return JSON.stringify(X)===JSON.stringify($)}catch{return X===$}}function iz(X){return X.getStats().size*2}function lz(X,$={}){let Z=c8.cwd();while(Z.includes("storage"))Z=pY(Z,"..");let Y=pY(Z,X||"");if($?.relative)return Cz(c8.cwd(),Y);return Y}function x0(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sz(){if(S9.env.NODE_ENV==="test"||S9.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof S9<"u"){let X=S9.type;if(X==="renderer"||X==="worker")return!1;return!!(S9.versions&&(S9.versions.node||S9.versions.bun))}return!1}class BU{async format(X){let $=await sz(),Z=await this.getMetadata($);return JSON.stringify({timestamp:X.timestamp.toISOString(),level:X.level,name:X.name,message:X.message,metadata:Z})}async getMetadata(X){if(X){let{hostname:$}=await import("os");return{pid:MX.pid,hostname:$(),environment:MX.env.NODE_ENV||"development",platform:MX.platform,version:MX.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:MX.env.NODE_ENV||MX.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class m8{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(X,$={}){this.name=X,this.config={...H$},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new BU,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??F0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Z={...$},Y=$.timestamp!==void 0;if(Y)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),_=this.generateKey();this.currentKeyId=U,this.keys.set(U,_),this.encryptionKeys.set(U,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(X){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return $[X]>=$[Z]}initializeFingersCrossedConfig(X){if(!X.fingersCrossedEnabled&&X.fingersCrossed)return{...C8,...X.fingersCrossed};if(!X.fingersCrossedEnabled)return null;if(!X.fingersCrossed)return{...C8};return{...C8,...X.fingersCrossed}}normalizeOptions(X){let $={format:"json",level:"info",logDirectory:H$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...$,...Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=$.level;return Z}shouldWriteToFile(){return!x0()&&this.config.writeToFile===!0}async writeToFile(X){let $=(async()=>{let Y,U=0,_=3,Q=1000;while(U<_)try{try{try{await Nz(this.config.logDirectory,nY.F_OK|nY.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await Sz(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let L=this.validateEncryptionConfig()?(await this.encrypt(X)).encrypted:M9.from(X);try{if(!Z8(this.currentLogFile))await mZ(this.currentLogFile,"",{mode:420});if(Y=uY(this.currentLogFile,"a",420),Tz(Y,L,{flag:"a"}),mY(Y),Y!==void 0)cZ(Y),Y=void 0;if((await RX(this.currentLogFile)).size===0){if(await mZ(this.currentLogFile,L,{flag:"w",mode:420}),(await RX(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let j=z;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<_-1){let E=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${_}:`,E);let V=Q*2**U;await new Promise((G)=>setTimeout(G,V)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{cZ(Y)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(L){if(U===_-1){let j=L,E=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),L}U++;let z=Q*2**(U-1);await new Promise((j)=>setTimeout(j,z))}})();this.pendingOperations.push($);let Z=this.pendingOperations.length-1;try{await $}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(Z,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 DX(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 DX(this.config.logDirectory,`${this.name}.log`);let X=new Date().toISOString().split("T")[0];return DX(this.config.logDirectory,`${this.name}-${X}.log`)}setupRotation(){if(x0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let X=this.config.rotation,$;switch(X.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 X=this.config.rotation.keyRotation;if(!X?.enabled)return;let $=typeof X.interval==="number"?X.interval:60,Z=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,$=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=$,this.keys.set($,Z),this.encryptionKeys.set($,{key:Z,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,L])=>L.createdAt.getTime()-Q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,_=Math.max(1,U);if(Y.length>_)for(let[Q]of Y.slice(_))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return pZ(16).toString("hex")}generateKey(){return pZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let X=this.keys.get(this.currentKeyId);if(!X)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:X,id:this.currentKeyId}}encrypt(X){let{key:$}=this.getCurrentKey(),Z=pZ(16),Y=wz("aes-256-gcm",$,Z),U=M9.isBuffer(X)?X:M9.from(X,"utf8"),_=Y.update(U),Q=Y.final(),L=_.length+Q.length,z=Y.getAuthTag(),j=M9.allocUnsafe(16+L+16);return Z.copy(j,0),_.copy(j,16),Q.copy(j,16+_.length),z.copy(j,16+L),{encrypted:j,iv:Z}}async compressData(X){return new Promise(($,Z)=>{let Y=lY(),U=[];Y.on("data",(_)=>U.push(_)),Y.on("end",()=>$(M9.from(M9.concat(U)))),Y.on("error",Z),Y.write(X),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let X={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...X,...$}}return X}async rotateLog(){if(x0())return;if(!this.shouldWriteToFile())return;let X=await RX(this.currentLogFile).catch(()=>null);if(!X)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&X.size>=$.maxSize){let Z=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await Y8(this.config.logDirectory),_=U.filter((z)=>z.startsWith(this.name)&&/\.log\.\d+$/.test(z)).sort((z,j)=>{let E=Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),Q=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,L=`${Z}.${Q}`;if(await RX(Z).catch(()=>null))try{if(await iY(Z,L),$.compress)try{let z=`${L}.gz`;await this.compressLogFile(L,z),await U8(L)}catch(z){console.error("Error compressing rotated file:",z)}if(_.length===0&&!U.some((z)=>z.endsWith(".log.1")))try{let z=`${Z}.1`;await mZ(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 U=new Date().toISOString().replace(/[:.]/g,"-"),_=Z.replace(/\.log$/,`-${U}.log`);if(await RX(Z).catch(()=>null))await iY(Z,_)}if(this.currentLogFile=Y,$.maxFiles){let U=(await Y8(this.config.logDirectory)).filter((_)=>_.startsWith(this.name)).sort((_,Q)=>Q.localeCompare(_));for(let _ of U.slice($.maxFiles))await U8(DX(this.config.logDirectory,_))}}}async compressLogFile(X,$){let Z=cY(X),Y=Pz($),U=lY();await xz(Z,U,Y)}async handleFingersCrossedBuffer(X,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(X)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let Y=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(X){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[X]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((X)=>{if(X instanceof Promise)return X.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),Z8(this.currentLogFile))try{let X=uY(this.currentLogFile,"r+");mY(X),cZ(X)}catch(X){console.error(`Error flushing file: ${X}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let X of this.pendingOperations)if(typeof X.cancel==="function")X.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(X){console.error("Error waiting for pending operations:",X)}if(!x0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await Y8(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of X)try{await U8(DX(this.config.logDirectory,$))}catch(Z){console.error(`Failed to delete temp file ${$}:`,Z)}}catch(X){console.error("Error cleaning up temporary files:",X)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(X){if(!X)return"";return`${this.tagFormat.prefix}${X}${this.tagFormat.suffix}`}formatFileTimestamp(X){return`[${X.toISOString()}]`}formatConsoleTimestamp(X){return this.shouldStyleConsole()?G0.gray(X.toLocaleTimeString()):X.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||x0())return!1;let X=typeof F0.env.NO_COLOR<"u",$=F0.env.FORCE_COLOR==="0";if(X||$)return!1;return!!(typeof F0.stderr<"u"&&F0.stderr.isTTY||typeof F0.stdout<"u"&&F0.stdout.isTTY)}formatConsoleMessage(X){let{timestamp:$,icon:Z="",tag:Y="",message:U,level:_,showTimestamp:Q=!0}=X,L=(J)=>J.replace(this.ANSI_PATTERN,"");if(!this.fancy){let J=[];if(Q)J.push($);if(_==="warning")J.push("WARN");else if(_==="error")J.push("ERROR");else if(Z)J.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)J.push(Y.replace(/[[\]]/g,""));return J.push(U),J.join(" ")}let z=F0.stdout.columns||120,j="";if(_==="warning"||_==="error")j=`${Z} ${U}`;else if(_==="info"||_==="success")j=`${Z} ${Y} ${U}`;else j=`${Z} ${Y} ${G0.cyan(U)}`;if(!Q)return j.trim();let E=L(j).trim().length,V=L($).length,G=Math.max(1,z-2-E-V);return`${j.trim()}${" ".repeat(G)}${$}`}formatMessage(X,$){if($.length===1&&Array.isArray($[0]))return X.replace(/\{(\d+)\}/g,(_,Q)=>{let L=Number.parseInt(Q,10);return L<$[0].length?String($[0][L]):_});let Z=/%([sdijfo%])/g,Y=0,U=X.replace(Z,(_,Q)=>{if(Q==="%")return"%";if(Y>=$.length)return _;let L=$[Y++];switch(Q){case"s":return String(L);case"d":case"i":return Number(L).toString();case"j":case"o":return JSON.stringify(L,null,2);default:return _}});if(Y<$.length)U+=` ${$.slice(Y).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return U}formatMarkdown(X){if(!X)return X;let $=X;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,Y,U)=>{let _=G0.underline(G0.blue(Y)),Q=this.toAbsoluteFilePath(U);if(Q&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let L=`file://${encodeURI(Q)}`,z="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${L}\x1B\\${_}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${_}\x1B]8;;\x1B\\`;return _}),$=$.replace(/`([^`]+)`/g,(Z,Y)=>G0.bgGray(Y)),$=$.replace(/\*\*([^*]+)\*\*/g,(Z,Y)=>G0.bold(Y)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,Y)=>G0.italic(Y)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,Y)=>G0.italic(Y)),$=$.replace(/~([^~]+)~/g,(Z,Y)=>G0.strikethrough(Y)),$}supportsHyperlinks(){if(x0())return!1;let X=F0.env;if(!X)return!1;if(X.TERM_PROGRAM==="iTerm.app"||X.TERM_PROGRAM==="vscode"||X.TERM_PROGRAM==="WezTerm")return!0;if(X.WT_SESSION)return!0;if(X.TERM==="xterm-kitty")return!0;let $=X.VTE_VERSION?Number.parseInt(X.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(X){try{let $=X;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Z=F0.env.HOME||"";if(Z)$=$.replace(/^~(?=$|\/)/,Z)}if(Az($)||$.startsWith("./")||$.startsWith("../"))$=kz($);else return null;return Z8($)?$:null}catch{return null}}buildOutputTexts(X){let $=this.shouldStyleConsole()?this.formatMarkdown(X):X,Z=X.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Z}}async log(X,$,...Z){if(!this.shouldLog(X))return;let Y=new Date,U=this.formatConsoleTimestamp(Y),_=this.formatFileTimestamp(Y),Q,L;if($ instanceof Error)Q=$.message,L=$.stack;else Q=this.formatMessage($,Z);let{consoleText:z,fileText:j}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let V=this.options.showIcons===!1?"":uU[X],G=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",J;switch(X){case"debug":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:G0.gray(z),level:X}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"success":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:G0.green(z),level:X}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:U,icon:V,tag:G,message:z,level:X}),console.error(J),L){let W=L.split(`
424
+ `);for(let F of W)if(F.trim()&&!F.includes(Q))console.error(this.formatConsoleMessage({timestamp:U,message:G0.gray(` ${F}`),level:X,showTimestamp:!1}))}break}}else if(!x0()){if(console.error(`${_} ${this.environment}.${X.toUpperCase()}: ${Q}`),L)console.error(L)}let E=`${_} ${this.environment}.${X.toUpperCase()}: ${j}
425
+ `;if(L)E+=`${L}
426
+ `;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress(X,$=""){let Z={update:(U,_)=>{},finish:(U)=>{},interrupt:(U,_)=>{}};if(!this.enabled)return Z;let Y=30;if(this.activeProgressBar={total:Math.max(1,X||1),current:0,message:$||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!x0()&&F0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,_)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),_!==void 0)this.activeProgressBar.message=_;if(this.shouldStyleConsole()&&!x0()&&F0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,_="info")=>{if(!x0()&&F0.stdout.isTTY)F0.stdout.write(`
427
+ `);if(this[_==="warning"?"warn":_](U),this.activeProgressBar&&this.shouldStyleConsole()&&!x0()&&F0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(X){let $=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":G0.blue("\u25D0"),tag:Z,message:`${G0.cyan(X)}...`}))}return async(Z)=>{if(!this.enabled)return;let Y=performance.now(),U=Math.round(Y-$),_=`${X} completed in ${U}ms`,Q=new Date,L=this.formatConsoleTimestamp(Q),z=`${this.formatFileTimestamp(Q)} ${this.environment}.INFO: ${_}`;if(Z)z+=` ${JSON.stringify(Z)}`;if(z+=`
428
+ `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:L,icon:this.options.showIcons===!1?"":G0.green("\u2713"),tag:j,message:`${_}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!x0())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(X,...$){await this.log("debug",X,...$)}async info(X,...$){await this.log("info",X,...$)}async success(X,...$){await this.log("success",X,...$)}async warn(X,...$){await this.log("warning",X,...$)}async error(X,...$){await this.log("error",X,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let X=this.config.rotation,{encrypt:$}=X;return!!$}async only(X){if(!this.enabled)return;return await X()}isEnabled(){return this.enabled}setEnabled(X){this.enabled=X}extend(X){let $=`${this.name}:${X}`,Z=new m8($,{...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(Z),Z}createReadStream(){if(x0())throw Error("createReadStream is not supported in browser environments");if(!Z8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return cY(this.currentLogFile,{encoding:"utf8"})}async decrypt(X){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 Z=this.keys.get(this.currentKeyId);try{let Y=M9.isBuffer(X)?X:M9.from(X,"base64"),U=Y.subarray(0,16),_=Y.subarray(Y.length-16),Q=Y.subarray(16,Y.length-16),L=qz("aes-256-gcm",Z,U);L.setAuthTag(_);let z=L.update(Q),j=L.final(),E=z.length+j.length,V=M9.allocUnsafe(E);return z.copy(V,0),j.copy(V,z.length),V.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x0()}isServerMode(){return!x0()}setTestEncryptionKey(X,$){this.currentKeyId=X,this.keys.set(X,$)}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(X){if(!this.enabled)return;let $=new Date,Z=this.formatConsoleTimestamp($),Y=this.formatFileTimestamp($),{consoleText:U,fileText:_}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let L=U.split(`
429
+ `),z=Math.max(...L.map((G)=>G.length))+2,j=`\u250C${"\u2500".repeat(z)}\u2510`,E=`\u2514${"\u2500".repeat(z)}\u2518`,V=L.map((G)=>{return this.formatConsoleMessage({timestamp:Z,message:G0.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:G0.cyan(j),showTimestamp:!1})),V.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Z,message:G0.cyan(E),showTimestamp:!1}))}else if(!x0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${_}`);let Q=`${Y} ${this.environment}.INFO: [BOX] ${_}
430
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}async prompt(X){if(x0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${G0.cyan("?")} ${X} (y/n) `);let Z=(Y)=>{let U=Y.toString().trim().toLowerCase();F0.stdin.removeListener("data",Z);try{if(typeof F0.stdin.setRawMode==="function")F0.stdin.setRawMode(!1)}catch{}F0.stdin.pause(),console.error(""),$(U==="y"||U==="yes")};try{if(typeof F0.stdin.setRawMode==="function")F0.stdin.setRawMode(!0)}catch{}F0.stdin.resume(),F0.stdin.once("data",Z)})}setFancy(X){this.fancy=X}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(X,...$){if(!this.enabled)return;let Z=X;if($&&$.length>0){let Q=/%([sdijfo%])/g,L=0;if(Z=X.replace(Q,(z,j)=>{if(j==="%")return"%";if(L>=$.length)return z;let E=$[L++];switch(j){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return z}}),L<$.length)Z+=` ${$.slice(L).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:Y,fileText:U}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?G0.gray(this.formatTag(this.name)):"",L=this.options.showIcons===!1?"":`${G0.blue("\u25D0")} `;console.error(`${L}${Q} ${G0.cyan(Y)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
431
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(X,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!F0.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(X.current/X.total*100))),Y=Math.round(X.barLength*Z/100),U=X.barLength-Y,_=G0.green("\u2501".repeat(Y)),Q=G0.gray("\u2501".repeat(U)),L=`[${_}${Q}]`,z=`${Z}%`.padStart(4),j=X.message?` ${X.message}`:"",E=this.options.showIcons===!1?"":$||Z===100?G0.green("\u2713"):G0.blue("\u25B6"),V=this.options.showTags!==!1&&this.name?` ${G0.gray(this.formatTag(this.name))}`:"",G=`\r${E}${V} ${L} ${z}${j}`,J=F0.stdout.columns||80,W=" ".repeat(Math.max(0,J-G.replace(this.ANSI_PATTERN,"").length));if(X.lastRenderedLine=`${G}${W}`,F0.stdout.write(X.lastRenderedLine),$)F0.stdout.write(`
432
+ `)}finishProgressBar(X,$){if(!this.enabled||!this.fancy||x0()||!F0.stdout.isTTY){this.activeProgressBar=null;return}if(X.current<X.total)X.current=X.total;if($)X.message=$;this.renderProgressBar(X,!0),this.activeProgressBar=null}async clear(X={}){if(x0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await Y8(this.config.logDirectory),Z=[];for(let Y of $){if(!(X.name?new RegExp(X.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let U=DX(this.config.logDirectory,Y);if(X.before)try{if((await RX(U)).mtime>=X.before)continue}catch(_){console.error(`Failed to get stats for file ${U}:`,_);continue}Z.push(U)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let Y of Z)try{await U8(Y),console.warn(`Deleted log file: ${Y}`)}catch(U){console.error(`Failed to delete log file ${Y}:`,U)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function yU(X,$={}){let{maxRetries:Z=3,retryDelay:Y=1000,isRetryable:U=()=>!0,fallback:_}=$,Q=Error("Unknown error occurred");for(let L=0;L<=Z;L++)try{return await X()}catch(z){if(Q=z instanceof Error?z:Error(String(z)),L===Z||!U(Q))break;if(Y>0)await new Promise((j)=>setTimeout(j,Y))}if(_!==void 0)return _;throw Q instanceof Error?Q:Error(`Unknown error: ${String(Q)}`)}function hU(X){return X instanceof Z9}function oz(X){return X instanceof w8}function rz(X){if(hU(X))return X.code==="FILE_SYSTEM_ERROR"||X.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>X.message.toLowerCase().includes($.toLowerCase()))}class zZ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(X,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(X.toLowerCase()),parse:(X)=>{let $=X.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(X,$)=>$==="number"||!Number.isNaN(Number(X))&&!Number.isNaN(Number.parseFloat(X)),parse:(X)=>{let $=Number(X);if(Number.isNaN($))throw TypeError(`Cannot parse "${X}" as number`);return $}},{name:"array",canParse:(X,$)=>$==="array"||X.startsWith("[")||X.includes(","),parse:(X)=>{try{let $=JSON.parse(X);if(Array.isArray($))return $}catch{}return X.split(",").map(($)=>$.trim())}},{name:"json",canParse:(X,$)=>$==="object"||(X.startsWith("{")&&X.endsWith("}")||X.startsWith("[")&&X.endsWith("]")),parse:(X)=>{try{return JSON.parse(X)}catch($){throw Error(`Cannot parse "${X}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(X,$,Z={}){let{prefix:Y,useCamelCase:U=!0,useBackwardCompatibility:_=!0,customParsers:Q={},verbose:L=!1,trackPerformance:z=!0}=Z,j=async()=>{if(!X)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix(X),V={...$};return this.processObject(V,[],E,{useCamelCase:U,useBackwardCompatibility:_,customParsers:Q,verbose:L,configName:X}),{config:V,source:{type:"environment",priority:50,timestamp:new Date}}};if(z)return x$.track("applyEnvironmentVariables",j,{configName:X});return j()}generateEnvPrefix(X){return X.toUpperCase().replace(/-/g,"_")}formatEnvKey(X,$){if(!$)return X.toUpperCase();return X.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=Q.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),z=`${Z}_${L.join("_")}`,j=Y.useBackwardCompatibility?`${Z}_${Q.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.processObject(_,Q,Z,Y);else{let E=_8.env[z]||(j?_8.env[j]:void 0);if(E!==void 0){if(Y.verbose){let V=_8.env[z]?z:j}try{X[U]=this.parseEnvironmentValue(E,typeof _,z,Y.customParsers,Y.configName)}catch(V){if(V instanceof q8)throw V;throw m9.envVar(z,E,typeof _,Y.configName)}}}}}parseEnvironmentValue(X,$,Z,Y,U){for(let[_,Q]of Object.entries(Y))try{return Q(X)}catch{continue}for(let _ of this.defaultParsers)if(_.canParse(X,$))try{return _.parse(X)}catch{throw m9.envVar(Z,X,`${$} (via ${_.name} parser)`,U)}return X}getEnvironmentVariables(X){let $={},Z=X.toUpperCase();for(let[Y,U]of Object.entries(_8.env))if(Y.startsWith(Z)&&U!==void 0)$[Y]=U;return $}validateEnvironmentVariable(X,$,Z){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(X))Y.push(`Environment variable key "${X}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(X,$,Z,{})}catch(U){Y.push(`Cannot parse value "${$}" as ${Z}: ${U}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(X,$,Z={}){let{prefix:Y,format:U="text"}=Z,_=Y||this.generateEnvPrefix(X),Q=[];switch(this.extractEnvVarInfo($,[],_,Q),U){case"markdown":return this.formatAsMarkdown(Q,X);case"json":return JSON.stringify(Q,null,2);default:return this.formatAsText(Q,X)}}extractEnvVarInfo(X,$,Z,Y){for(let[U,_]of Object.entries(X)){let Q=[...$,U],L=`${Z}_${Q.map((z)=>this.formatEnvKey(z,!0)).join("_")}`;if(typeof _==="object"&&_!==null&&!Array.isArray(_))this.extractEnvVarInfo(_,Q,Z,Y);else Y.push({key:L,type:Array.isArray(_)?"array":typeof _,description:`Configuration for ${Q.join(".")}`,example:this.generateExample(_)})}}generateExample(X){if(Array.isArray(X))return JSON.stringify(X);if(typeof X==="object"&&X!==null)return JSON.stringify(X);return String(X)}formatAsText(X,$){let Z=`Environment Variables for ${$}:
381
433
 
382
- `;for(let _ of $)X+=`${_.key}
383
- `,X+=` Type: ${_.type}
384
- `,X+=` Description: ${_.description}
385
- `,X+=` Example: ${_.example}
434
+ `;for(let Y of X)Z+=`${Y.key}
435
+ `,Z+=` Type: ${Y.type}
436
+ `,Z+=` Description: ${Y.description}
437
+ `,Z+=` Example: ${Y.example}
386
438
 
387
- `;return X}formatAsMarkdown($,Z){let X=`# Environment Variables for ${Z}
439
+ `;return Z}formatAsMarkdown(X,$){let Z=`# Environment Variables for ${$}
388
440
 
389
- `;X+=`| Variable | Type | Description | Example |
390
- `,X+=`|----------|------|-------------|----------|
391
- `;for(let _ of $)X+=`| \`${_.key}\` | ${_.type} | ${_.description} | \`${_.example}\` |
392
- `;return X}}function dY($,Z,X={}){return ZX($,Z,X,new WeakMap)}function ZX($,Z,X,_){let{arrayMergeMode:L="replace",skipNullish:j=!1,customMerger:Y}=X;if(Z===null||Z===void 0)return j?$:Z;if(Y){let z=Y($,Z);if(z!==void 0)return z}if(Array.isArray(Z)||Array.isArray($))return XX($,Z,L,_);if(!$9(Z)||!$9($))return Z;return nY($,Z,X,_)}function XX($,Z,X,_){if(Array.isArray(Z)&&!Array.isArray($))return Z;if(Array.isArray($)&&!Array.isArray(Z))return Z;if(Array.isArray(Z)&&Array.isArray($))switch(X){case"replace":return Z;case"concat":return cY($,Z);case"smart":return mY($,Z,_);default:return Z}return Z}function cY($,Z){let X=[...Z];for(let _ of $)if(!X.some((L)=>jZ(L,_)))X.push(_);return X}function mY($,Z,X){if(Z.length===0)return $;if($.length===0)return Z;if($9(Z[0])&&$9($[0]))return uY($,Z,X);if(Z.every((_)=>typeof _==="string")&&$.every((_)=>typeof _==="string")){let _=[...Z];for(let L of $)if(!_.includes(L))_.push(L);return _}return Z}function uY($,Z,X){let _=[...Z];for(let L of $){if(!$9(L)){_.push(L);continue}let j=["id","name","key","path","type"],Y=!1;for(let z of j)if(z in L){if(_.find((F)=>$9(F)&&(z in F)&&F[z]===L[z])){Y=!0;break}}if(!Y)_.push(L)}return _}function nY($,Z,X,_){let L=Z;if($9(L)&&_.has(L))return _.get(L);let j={...$};if($9(L))_.set(L,j);for(let Y in L){if(!Object.prototype.hasOwnProperty.call(L,Y))continue;let z=L[Y],F=j[Y];if(X.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){j[Y]=z;continue}if($9(z)&&$9(F))j[Y]=ZX(F,z,X,_);else if(Array.isArray(z)||Array.isArray(F))j[Y]=XX(F,z,X.arrayMergeMode||"smart",_);else j[Y]=z}return j}function _X($,Z,X="replace"){return dY($,Z,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function jZ($,Z){if($===Z)return!0;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;for(let X=0;X<$.length;X++)if(!jZ($[X],Z[X]))return!1;return!0}if($9($)&&$9(Z)){let X=Object.keys($),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let L of X){if(!Object.prototype.hasOwnProperty.call(Z,L))return!1;if(!jZ($[L],Z[L]))return!1}return!0}return!1}function $9($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class LX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,Z,X={}){let{arrayStrategy:_="replace",useCache:L=!0,cacheTtl:j,trackPerformance:Y=!0,verbose:z=!1}=X;if(L){let E=Y1.getWithFileCheck("file",$);if(E){if(z)console.log(`Configuration loaded from cache: ${$}`);return E}}let F=async()=>{if(!y1($))return null;try{let E=`?t=${Date.now()}`,U=await import($+E),V=U.default||U,Q="default"in U,O=Object.keys(U).length>0;if(!Q&&!O)throw new g$($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new g$($,Error("Configuration must export a valid object"),"unknown");let K={config:_X(Z,V,_),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(L)Y1.setWithFileCheck("file",K,$,j);return K}catch(E){throw E instanceof Error?g9.configLoad($,E):g9.configLoad($,Error(String(E)))}};if(Y)return r$.track("loadFromPath",F,{path:$});return F()}async tryLoadFromPaths($,Z,X={}){for(let _ of $)try{let L=await this.loadFromPath(_,Z,X);if(L)return L}catch(L){if(L instanceof Error&&L.name==="ConfigLoadError")throw L;if(X.verbose)console.warn(`Failed to load config from ${_}:`,L)}return null}generateConfigPaths($,Z,X){let _=this.generateNamePatterns($,X),L=[];for(let j of _)for(let Y of this.extensions)L.push(v5(Z,`${j}${Y}`));return L}generateNamePatterns($,Z){let X=[];if(X.push("config",".config"),$)X.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(Z){if(X.push(Z,`.${Z}.config`,`${Z}.config`,`.${Z}`),$)X.push(`${$}.${Z}.config`,`.${$}.${Z}.config`)}return X.filter(Boolean)}checkFileAccess($){return pY(async()=>{return y1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,Z,X){let _=[];if(!y1($))return _;if(Z||X){let L=this.generateNamePatterns(Z||"",X);for(let j of L)for(let Y of this.extensions){let z=v5($,`${j}${Y}`);if(await this.checkFileAccess(z))_.push(z)}}else try{let{readdirSync:L}=await import("fs"),j=L($);for(let Y of j)if(this.looksLikeConfigFile(Y)){let z=v5($,Y);if(await this.checkFileAccess(z))_.push(z)}}catch{return[]}return _}looksLikeConfigFile($){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((Z)=>Z.test($))}async validateConfigFile($){let Z=[];try{if(!y1($))return Z.push("Configuration file does not exist"),Z;let X=await import($),_=X.default||X;if(_===void 0)Z.push("Configuration file must export a default value or named exports");else if(typeof _!=="object"||_===null)Z.push("Configuration must be an object");else if(Array.isArray(_))Z.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:L}=await import("fs"),j=L($,"utf8");JSON.parse(j)}catch(L){Z.push(`Invalid JSON syntax: ${L}`)}}catch(X){Z.push(`Failed to load configuration file: ${X}`)}return Z}async getFileModificationTime($){try{let{statSync:Z}=await import("fs");return Z($).mtime}catch{return null}}async preloadConfigurations($,Z={}){let X=new Map;return await Promise.allSettled($.map(async(_)=>{try{let L=await this.loadFromPath(_,{},Z);if(L)X.set(_,L.config)}catch(L){if(Z.verbose)console.warn(`Failed to preload ${_}:`,L)}})),X}}class jX{async validateConfiguration($,Z,X={}){let{stopOnFirstError:_=!1,validateRequired:L=!0,validateTypes:j=!0,customRules:Y=[],trackPerformance:z=!0,verbose:F=!1}=X,E=async()=>{let U=[],V=[],Q={stopOnFirstError:_,validateRequired:L,validateTypes:j,customRules:Y,trackPerformance:z,verbose:F};try{if(typeof Z==="string")return await this.validateWithSchemaFile($,Z,Q);else if(Array.isArray(Z))return this.validateWithRules($,[...Z,...Y],Q);else return this.validateWithJSONSchema($,Z,Q)}catch(O){return U.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:U,warnings:V}}};if(z)return await r$.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,Z,X){try{if(!NY(Z))throw new p$(Z,[{path:"",message:"Schema file does not exist"}]);let _=await import(Z),L=_.default||_;if(Array.isArray(L))return this.validateWithRules($,L,X);else return this.validateWithJSONSchema($,L,X)}catch(_){throw new p$(Z,[{path:"",message:`Failed to load schema: ${_}`}])}}validateWithJSONSchema($,Z,X){let _=[],L=[];return this.validateObjectAgainstSchema($,Z,"",_,L,X),{isValid:_.length===0,errors:_,warnings:L}}validateObjectAgainstSchema($,Z,X,_,L,j){if(j.validateTypes&&Z.type){let Y=Array.isArray($)?"array":typeof $,z=Array.isArray(Z.type)?Z.type:[Z.type];if(!z.includes(Y)){if(_.push({path:X,message:`Expected type ${z.join(" or ")}, got ${Y}`,expected:z.join(" or "),actual:Y,rule:"type"}),j.stopOnFirstError)return}}if(Z.enum&&!Z.enum.includes($)){if(_.push({path:X,message:`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"}),j.stopOnFirstError)return}if(typeof $==="string"){if(Z.minLength!==void 0&&$.length<Z.minLength)_.push({path:X,message:`String length must be at least ${Z.minLength}`,expected:`>= ${Z.minLength}`,actual:$.length,rule:"minLength"});if(Z.maxLength!==void 0&&$.length>Z.maxLength)_.push({path:X,message:`String length must not exceed ${Z.maxLength}`,expected:`<= ${Z.maxLength}`,actual:$.length,rule:"maxLength"});if(Z.pattern){if(!new RegExp(Z.pattern).test($))_.push({path:X,message:`String does not match pattern ${Z.pattern}`,expected:Z.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(Z.minimum!==void 0&&$<Z.minimum)_.push({path:X,message:`Value must be at least ${Z.minimum}`,expected:`>= ${Z.minimum}`,actual:$,rule:"minimum"});if(Z.maximum!==void 0&&$>Z.maximum)_.push({path:X,message:`Value must not exceed ${Z.maximum}`,expected:`<= ${Z.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&Z.items)for(let Y=0;Y<$.length;Y++){let z=X?`${X}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],Z.items,z,_,L,j),j.stopOnFirstError&&_.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(j.validateRequired&&Z.required){for(let z of Z.required)if(!(z in Y)){if(_.push({path:X?`${X}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),j.stopOnFirstError)return}}if(Z.properties){for(let[z,F]of Object.entries(Z.properties))if(z in Y){let E=X?`${X}.${z}`:z;if(this.validateObjectAgainstSchema(Y[z],F,E,_,L,j),j.stopOnFirstError&&_.length>0)return}}if(Z.additionalProperties===!1){let z=new Set(Object.keys(Z.properties||{}));for(let F of Object.keys(Y))if(!z.has(F))L.push({path:X?`${X}.${F}`:F,message:`Additional property '${F}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,Z,X){let _=[],L=[];for(let j of Z)try{let Y=this.getValueByPath($,j.path),z=this.validateWithRule(Y,j,j.path);if(_.push(...z),X.stopOnFirstError&&_.length>0)break}catch(Y){_.push({path:j.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:_.length===0,errors:_,warnings:L}}validateWithRule($,Z,X){let _=[];if(Z.required&&($===void 0||$===null))return _.push({path:X,message:Z.message||`Property '${X}' is required`,expected:"required",rule:"required"}),_;if($===void 0||$===null)return _;if(Z.type){let L=Array.isArray($)?"array":typeof $;if(L!==Z.type)_.push({path:X,message:Z.message||`Expected type ${Z.type}, got ${L}`,expected:Z.type,actual:L,rule:"type"})}if(Z.min!==void 0){let L=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(L<Z.min)_.push({path:X,message:Z.message||`Value must be at least ${Z.min}`,expected:`>= ${Z.min}`,actual:L,rule:"min"})}if(Z.max!==void 0){let L=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(L>Z.max)_.push({path:X,message:Z.message||`Value must not exceed ${Z.max}`,expected:`<= ${Z.max}`,actual:L,rule:"max"})}if(Z.pattern&&typeof $==="string"){if(!Z.pattern.test($))_.push({path:X,message:Z.message||`Value does not match pattern ${Z.pattern}`,expected:Z.pattern.toString(),actual:$,rule:"pattern"})}if(Z.enum&&!Z.enum.includes($))_.push({path:X,message:Z.message||`Value must be one of: ${Z.enum.join(", ")}`,expected:Z.enum.join(", "),actual:$,rule:"enum"});if(Z.validator){let L=Z.validator($);if(L)_.push({path:X,message:Z.message||L,rule:"custom"})}return _}getValueByPath($,Z){if(!Z)return $;let X=Z.split("."),_=$;for(let L of X)if(_&&typeof _==="object"&&L in _)_=_[L];else return;return _}generateRulesFromInterface($){let Z=[],X=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let _ of X){let[,L,j,Y]=_;Z.push({path:L,required:!j,type:this.mapTypeScriptType(Y)})}return Z}mapTypeScriptType($){switch($.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:QX},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class YX{fileLoader=new LX;envProcessor=new PZ;validator=new jX;async loadConfig($){let Z=Date.now(),{cache:X,performance:_,schema:L,validate:j,...Y}=$;try{if(X?.enabled){let F=this.checkCache(Y.name||"",Y);if(F)return F}let z;try{z=await this.loadConfigurationStrategies(Y,!0,X)}catch(F){let E=Y.__strictErrorHandling;if(F instanceof Error&&F.name==="ConfigNotFoundError"){if(E)throw F;z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(F instanceof Error&&F.name==="ConfigLoadError"){let U=F.message.includes("EACCES")||F.message.includes("EPERM")||F.message.includes("permission denied"),V=!U&&(F.message.includes("syntax")||F.message.includes("Expected")||F.message.includes("Unexpected")||F.message.includes("BuildMessage")||F.message.includes("errors building")),Q=F.message.includes("Configuration must export a valid object")||F.message.includes("Configuration file is empty and exports nothing");if(E&&(Q||U))throw F;if(V&&(!E||!Q))z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${F.message}`]};else throw F}else z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${F instanceof Error?F.message:String(F)}`]}}if(L||j)await this.validateConfiguration(z.config,L,j,Y.name);if(X?.enabled&&z)this.cacheResult(Y.name||"",z,X,Y);if(_?.enabled){let F={operation:"loadConfig",duration:Date.now()-Z,configName:Y.name,timestamp:new Date};if(_.onMetrics)_.onMetrics(F);if(_.slowThreshold&&F.duration>_.slowThreshold)j9.warn(`Slow configuration loading detected: ${F.duration}ms for ${Y.name}`);z.metrics=F}return z}catch(z){let F=Date.now()-Z;throw j9.error(`Configuration loading failed after ${F}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,Z=!1,X){let{name:_="",alias:L,cwd:j,configDir:Y,defaultConfig:z,checkEnv:F=!0,arrayStrategy:E="replace",verbose:U=!1}=$,V=j||R$.cwd(),Q=[],O=await this.loadLocalConfiguration(_,L,V,Y,z,E,U,F,X);if(O)return Q.push(...this.getLocalSearchPaths(_,L,V,Y)),this.finalizeResult(O,Q,F,_,U);let K=await this.loadHomeConfiguration(_,L,z,E,U,F);if(K)return Q.push(...this.getHomeSearchPaths(_,L)),this.finalizeResult(K,Q,F,_,U);let I=await this.loadPackageJsonConfiguration(_,L,V,z,E,U,F);if(I)return Q.push(r0(V,"package.json")),this.finalizeResult(I,Q,F,_,U);if(Q.push(...this.getAllSearchPaths(_,L,V,Y)),Z)throw g9.configNotFound(_,Q,L);return{...await this.applyEnvironmentVariables(_,z,F,U),warnings:[`No configuration file found for "${_}"${L?` or alias "${L}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,Z,X,_,L,j,Y,z,F){let E=z?v1($,L,Y):L,U=this.getLocalDirectories(X,_);for(let V of U){if(Y)j9.info(`Searching for configuration in: ${V}`);let Q=this.fileLoader.generateConfigPaths($,V,Z),O=await this.fileLoader.tryLoadFromPaths(Q,E,{arrayStrategy:j,verbose:Y,cacheTtl:F?.ttl,useCache:!F?.ttl||F.ttl>100});if(O){if(Y)j9.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,Z,X,_,L,j){if(!$)return null;let Y=j?v1($,X,L):X,z=[r0(e9(),".config",$),r0(e9(),".config"),e9()];for(let F of z){if(L)j9.info(`Checking home directory: ${F}`);let E=this.fileLoader.generateConfigPaths($,F,Z),U=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:_,verbose:L});if(U){if(L)j9.success(`Configuration loaded from home directory: ${U.source.path}`);return U}}return null}async loadPackageJsonConfiguration($,Z,X,_,L,j,Y){let z=Y?v1($,_,j):_;try{let F=r0(X,"package.json");if(!YY(F))return null;let E=await import(F),U=E[$],V=$;if(!U&&Z)U=E[Z],V=Z;if(U&&typeof U==="object"&&!Array.isArray(U)){if(j)j9.success(`Configuration loaded from package.json: ${V}`);return{config:_X(z,U,L),source:{type:"package.json",path:F,priority:30,timestamp:new Date}}}}catch(F){if(j)j9.warn("Failed to load package.json:",[F instanceof Error?F:Error(String(F))])}return null}async applyEnvironmentVariables($,Z,X,_){if(!X||!$||typeof Z!=="object"||Z===null||Array.isArray(Z))return{config:Z,source:{type:"default",priority:10,timestamp:new Date}};return{config:v1($,Z,_),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,Z,X,_,L){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,Z,X,_){let L=[];if(X){let j=X($);if(j)L.push(...j)}if(Z){let j=await this.validator.validateConfiguration($,Z);if(!j.isValid)L.push(...j.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(L.length>0)throw g9.configValidation(_||"unknown",L,_)}checkCache($,Z){let X=this.generateCacheKey($,Z);return Y1.get(X)||null}cacheResult($,Z,X,_){let L=this.generateCacheKey($,_);Y1.set(L,Z,void 0,X.ttl)}generateCacheKey($,Z){let X=[$];if(Z.alias)X.push(`alias:${Z.alias}`);if(Z.cwd)X.push(`cwd:${Z.cwd}`);if(Z.configDir)X.push(`configDir:${Z.configDir}`);if("checkEnv"in Z)X.push(`checkEnv:${Z.checkEnv}`);return X.join("|")}getLocalDirectories($,Z){return Array.from(new Set([$,r0($,"config"),r0($,".config"),Z?r0($,Z):void 0].filter(Boolean)))}getAllSearchPaths($,Z,X,_){let L=[];return L.push(...this.getLocalSearchPaths($,Z,X,_)),L.push(...this.getHomeSearchPaths($,Z)),L.push(r0(X,"package.json")),L}getLocalSearchPaths($,Z,X,_){let L=this.getLocalDirectories(X,_),j=[];for(let Y of L)j.push(...this.fileLoader.generateConfigPaths($,Y,Z));return j}getHomeSearchPaths($,Z){if(!$)return[];let X=[r0(e9(),".config",$),r0(e9(),".config"),e9()],_=[];for(let L of X)_.push(...this.fileLoader.generateConfigPaths($,L,Z));return _}async loadConfigWithResult($){return this.loadConfig($)}}async function iY($){let Z="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},X="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let _;if(X)_=await L$.loadConfig($);else _=await L$.loadConfig({...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}});return _?.config??Z}catch(_){let L=_ instanceof Error?_.name:"UnknownError",j=_ instanceof Error?_.message:String(_);if(!(L==="ConfigNotFoundError"||L==="ConfigLoadError"||L==="ConfigValidationError"||j.includes("config"))&&$.verbose)j9.warn("Unexpected error loading config, using defaults:",[_ instanceof Error?_:Error(String(_))]);let Y=X?{...$,defaultConfig:Z}:{...$,defaultConfig:Z,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await L$.applyEnvironmentVariables(Y.name||"",Z,!0,Y.verbose||!1))?.config??Z;return Z}}function v1($,Z,X=!1){let _=new PZ,L=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function j(Y,z=[]){let F={...Y};for(let[E,U]of Object.entries(Y)){let V=[...z,E],Q=[`${L}_${V.join("_").toUpperCase()}`,`${L}_${V.map((I)=>I.toUpperCase()).join("")}`,`${L}_${V.map((I)=>I.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,K;for(let I of Q)if(O=R$.env[I],O!==void 0){K=I;break}if(O!==void 0&&K)if(typeof U==="boolean")F[E]=["true","1","yes"].includes(O.toLowerCase());else if(typeof U==="number"){let I=Number(O);if(!Number.isNaN(I))F[E]=I}else if(Array.isArray(U))try{F[E]=JSON.parse(O)}catch{F[E]=O.split(",").map((I)=>I.trim())}else F[E]=O;else if(U&&typeof U==="object"&&!Array.isArray(U))F[E]=j(U,V)}return F}return j(Z)}async function lY(){if(!d5)d5=await iY({name:"mock",alias:"faker",defaultConfig:d$});return d5}function U8($){let Z=$.replace(/-/g,"_").split("_"),X=Z[0].toLowerCase(),_=Z[1]?.toUpperCase(),L=_?`${X}-${_.toLowerCase()}`:X;return{full:$,language:X,region:_,packageName:L,normalized:_?`${X}_${_}`:X}}function sY($){let Z=U8($);if(Z.region)return[Z.normalized,Z.language];return[Z.language]}function oY($){return`@mock-locale/${U8($).packageName}`}function FX($,Z){let X={...$};for(let _ in Z){let L=Z[_],j=$[_];if(L===void 0)continue;if(typeof L==="object"&&L!==null&&!Array.isArray(L)&&typeof j==="object"&&j!==null&&!Array.isArray(j))X[_]=FX(j,L);else X[_]=L}return X}function E8(){let $=r2.cwd(),Z=z8($,"package.json");if(!F8(Z))return!1;try{let X=JSON.parse(TY(Z,"utf-8"));return!!(X.workspaces||X.workspace)}catch{return!1}}function zX(){let $=r2.cwd();if(F8(z8($,"bun.lockb"))||F8(z8($,"bun.lock")))return"bun";if(F8(z8($,"pnpm-lock.yaml")))return"pnpm";if(F8(z8($,"yarn.lock")))return"yarn";if(F8(z8($,"package-lock.json")))return"npm";return"bun"}function UX($,Z={}){let X=zX(),{silent:_=!1}=Z;if(!_)console.log(`
393
- \uD83D\uDCE6 Installing ${$} using ${X}...`);let L={bun:{cmd:"bun",args:["add",$]},npm:{cmd:"npm",args:["install",$]},yarn:{cmd:"yarn",args:["add",$]},pnpm:{cmd:"pnpm",args:["add",$]}},{cmd:j,args:Y}=L[X];try{let z=PY(j,Y,{stdio:"pipe",shell:!0}),F=z.stdout?.toString()||"",E=z.stderr?.toString()||"",U=F+E;if(!_){if(F)console.log(F);if(E)console.error(E)}if(z.status===0){if(!_)console.log(`\u2713 Successfully installed ${$}`);return!0}else{let V=U;if(V.toLowerCase().includes("dependency loop")||V.includes("DependencyLoop")||V.includes("has a dependency loop")||V.includes("An internal error occurred (DependencyLoop)")){if(!_){if(console.log(`
394
- \u26A0\uFE0F Package ${$} is already available in the workspace and cannot be installed separately due to a dependency loop.`),E8())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!_)console.error(`\u2717 Failed to install ${$}`);return!1}}catch(z){if(!_)console.error(`\u2717 Error installing ${$}:`,z);return!1}}function L1($,Z){let X=[];for(let _ of Z.rules)if(!_.validator($)){let L=_.errorMessage||`Validation failed for value: ${$}`;if(X.push(L),Z.strict)throw Error(L)}return{isValid:X.length===0,errors:X}}function j1($,Z){let{items:X}=Z;if(X.length===0)throw Error("Cannot select from empty weighted items array");let _=X.reduce((Y,z)=>Y+z.weight,0);if(_<=0)throw Error("Total weight must be greater than 0");let L=$.number()*_,j=0;for(let Y of X)if(j+=Y.weight,L<=j)return Y.item;return X[X.length-1].item}function rY($,Z){return $.filter((X)=>{if(Z.gender&&X.gender&&X.gender!==Z.gender)return!1;if(Z.country){let _=Array.isArray(Z.country)?Z.country:[Z.country];if(X.country&&!_.includes(X.country))return!1}if(Z.region){let _=Array.isArray(Z.region)?Z.region:[Z.region];if(X.region&&!_.includes(X.region))return!1}if(Z.locale&&X.locale&&X.locale!==Z.locale)return!1;if(Z.ageRange&&X.age){let{min:_,max:L}=Z.ageRange;if(X.age<_||X.age>L)return!1}for(let[_,L]of Object.entries(Z))if(_!=="gender"&&_!=="country"&&_!=="region"&&_!=="locale"&&_!=="ageRange"&&X[_]!==void 0){if(!(Array.isArray(L)?L:[L]).includes(X[_]))return!1}return!0})}function x9($,Z){let X={...$};for(let _ of Z){let{field:L,dependsOn:j,mapping:Y}=_;if(X[j]&&Y[X[j]])X[L]=Y[X[j]]}return X}function tY($,Z={}){let X=$();if(Z.relationships)return x9(X,Z.relationships);return X}class TZ{providers=new Map;register($){let{category:Z,name:X}=$;if(!this.providers.has(Z))this.providers.set(Z,new Map);this.providers.get(Z).set(X,$)}get($,Z){return this.providers.get($)?.get(Z)}getProvidersInCategory($){let Z=this.providers.get($);return Z?Array.from(Z.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove($,Z){let X=this.providers.get($);if(X)return X.delete(Z);return!1}clear(){this.providers.clear()}}class h8{random;locale;constructor($,Z){this.random=$,this.locale=Z}street(){let $=this.random.arrayElement(this.locale.address.street),Z=this.streetSuffix();return`${$} ${Z}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress($){let Z=this.buildingNumber(),X=this.street();if($?.useFullAddress)return`${Z} ${X}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${Z} ${X}`}buildingNumber(){let $=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols($)}city(){return this.random.arrayElement(this.locale.address.city)}state(){return this.random.arrayElement(this.locale.address.state)}stateAbbr(){return this.random.arrayElement(this.locale.address.stateAbbr??[])}country(){return this.random.arrayElement(this.locale.address.country)}countryCode(){return this.random.arrayElement(this.locale.address.countryCode??[])}zipCode(){let $=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols($)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude($){let Z=$?.min??-90,X=$?.max??90,_=$?.precision??4;return this.random.float(Z,X,_)}longitude($){let Z=$?.min??-180,X=$?.max??180,_=$?.precision??4;return this.random.float(Z,X,_)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced($){let Z;if($?.constraints?.country){let X=$.constraints.country,_=Array.isArray(X)?X:[X];Z=this.city()}else Z=this.city();if($?.weighted)Z=j1(this.random,$.weighted);if($?.relationships)Z=x9({city:Z,country:$?.constraints?.country},$.relationships).city||Z;if($?.validation){let X=L1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.city()}}return Z}countryAdvanced($){let Z;if($?.constraints?.country){let X=$.constraints.country,_=Array.isArray(X)?X:[X];Z=this.random.arrayElement(_)}else Z=this.country();if($?.weighted)Z=j1(this.random,$.weighted);if($?.relationships)Z=x9({country:Z},$.relationships).country||Z;if($?.validation){let X=L1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.country()}}return Z}addressAdvanced($){let Z=this.countryAdvanced($),X=this.cityAdvanced($),_=this.state(),L=this.stateAbbr(),j=this.zipCode(),Y=this.street(),z=this.latitude(),F=this.longitude(),E={street:Y,city:X,state:_,stateAbbr:L,country:Z,countryCode:this.countryCode(),zipCode:j,latitude:z,longitude:F};if($?.relationships)return x9(E,$.relationships);return E}neighborhood($){let Z=$?.size||this.random.int(3,10),X=this.cityAdvanced($),_=this.state(),L=this.zipCode(),j=[];for(let Y=0;Y<Z;Y++)j.push({street:this.street(),city:X,state:_,zipCode:L,latitude:this.latitude({min:this.latitude()-0.01,max:this.latitude()+0.01}),longitude:this.longitude({min:this.longitude()-0.01,max:this.longitude()+0.01})});return j}}class y8{random;locale;constructor($,Z){this.random=$,this.locale=Z}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let $=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement($)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let $=["Golden Retriever","Labrador Retriever","German Shepherd","Bulldog","Beagle","Poodle","Rottweiler","Yorkshire Terrier","Boxer","Dachshund","Siberian Husky","Great Dane","Doberman Pinscher","Australian Shepherd","Cavalier King Charles Spaniel","Shih Tzu","Boston Terrier","Pomeranian","Havanese","Shetland Sheepdog","Bernese Mountain Dog","English Springer Spaniel","Brittany","Pug","Cocker Spaniel","Border Collie"];return this.random.arrayElement($)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let $=["Persian","Maine Coon","Ragdoll","British Shorthair","Siamese","Scottish Fold","Sphynx","Abyssinian","Devon Rex","American Shorthair","Bengal","Russian Blue","Birman","Oriental Shorthair","Norwegian Forest Cat","Cornish Rex","Himalayan","Exotic Shorthair","Burmese","Turkish Angora","Somali","Manx","Tonkinese"];return this.random.arrayElement($)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let $=["Eagle","Hawk","Falcon","Owl","Parrot","Macaw","Cockatoo","Parakeet","Canary","Finch","Sparrow","Robin","Blue Jay","Cardinal","Crow","Raven","Pigeon","Dove","Hummingbird","Woodpecker","Pelican","Swan","Duck","Goose","Flamingo","Penguin","Ostrich","Emu","Peacock","Turkey","Chicken","Rooster"];return this.random.arrayElement($)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let $=["Goldfish","Betta","Guppy","Angelfish","Neon Tetra","Molly","Platy","Swordtail","Clownfish","Tang","Damselfish","Lionfish","Grouper","Snapper","Tuna","Marlin","Swordfish","Shark","Ray","Barracuda","Catfish","Bass","Pike","Trout","Carp"];return this.random.arrayElement($)}bear(){let $=["Grizzly Bear","Black Bear","Polar Bear","Brown Bear","Panda Bear","Sun Bear","Sloth Bear","Spectacled Bear","Asian Black Bear","Kodiak Bear"];return this.random.arrayElement($)}cetacean(){let $=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement($)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let $=["Arabian","Thoroughbred","Quarter Horse","Morgan","Appaloosa","Paint Horse","Tennessee Walker","Standardbred","Mustang","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Shire","Haflinger","Icelandic","Shetland Pony"];return this.random.arrayElement($)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let $=["Butterfly","Moth","Bee","Wasp","Ant","Beetle","Dragonfly","Grasshopper","Cricket","Ladybug","Firefly","Mosquito","Fly","Cockroach","Termite","Flea","Praying Mantis","Cicada","Caterpillar","Walking Stick"];return this.random.arrayElement($)}lion(){let $=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement($)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let $=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement($)}snake(){let $=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement($)}}class A8{random;locale;constructor($,Z){this.random=$,this.locale=Z}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let $=["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","The Chronicles of Narnia","Brave New World","The Divine Comedy","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude","The Sound and the Fury","Invisible Man","Beloved","The Grapes of Wrath","Catch-22","Slaughterhouse-Five","Fahrenheit 451","The Handmaid's Tale","The Road","Life of Pi","The Kite Runner","The Book Thief"];return this.random.arrayElement($)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let $=["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee","Maya Angelou","Toni Morrison","Gabriel Garc\xEDa M\xE1rquez","Franz Kafka","James Joyce","Virginia Woolf","Oscar Wilde","Emily Dickinson","Walt Whitman","Robert Frost","Sylvia Plath","Kurt Vonnegut","Margaret Atwood","Haruki Murakami","Chimamanda Ngozi Adichie"];return this.random.arrayElement($)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let $=["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Pearson","Wiley","Springer","McGraw-Hill","Bloomsbury","Vintage","Doubleday","Knopf"];return this.random.arrayElement($)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let $=["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Poetry","Drama","Comedy","Adventure","Young Adult","Children's","Crime","Western","Dystopian","Paranormal","Contemporary","Classic","Literary Fiction"];return this.random.arrayElement($)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let $=["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","The Maze Runner","Divergent","The Mortal Instruments","Sherlock Holmes","Discworld","Dune","Foundation","The Wheel of Time","The Witcher","Millennium","Jack Reacher"];return this.random.arrayElement($)}isbn(){if(this.random.boolean(0.5)){let j=Array.from({length:9},()=>this.random.int(0,9)),Y=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${j.slice(0,1).join("")}-${j.slice(1,4).join("")}-${j.slice(4,9).join("")}-${Y}`}let $="978",Z=this.random.int(0,9),X=Array.from({length:3},()=>this.random.int(0,9)).join(""),_=Array.from({length:5},()=>this.random.int(0,9)).join(""),L=this.random.int(0,9);return`${$}-${Z}-${X}-${_}-${L}`}format(){let $=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement($)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let $=["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","A page-turner with incredible characters.","One of the best books I've ever read.","Absolutely captivating!"];return this.random.arrayElement($)}}class v8{random;locale;constructor($,Z){this.random=$,this.locale=Z}hex($){let Z=$?.prefix??"#",X=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return Z+X}rgb($){let Z=this.random.int(0,255),X=this.random.int(0,255),_=this.random.int(0,255);if($?.alpha){let L=this.random.float(0,1,2);if($?.format==="array")return[Z,X,_,L];return`rgba(${Z}, ${X}, ${_}, ${L})`}if($?.format==="array")return[Z,X,_];return`rgb(${Z}, ${X}, ${_})`}hsl($){let Z=this.random.int(0,360),X=this.random.int(0,100),_=this.random.int(0,100);if($?.alpha){let L=this.random.float(0,1,2);if($?.format==="array")return[Z,X,_,L];return`hsla(${Z}, ${X}%, ${_}%, ${L})`}if($?.format==="array")return[Z,X,_];return`hsl(${Z}, ${X}%, ${_}%)`}css($){let Z=$?.format??this.random.arrayElement(["hex","rgb","hsl"]);if(Z==="hex")return this.hex();if(Z==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let $=["Red","Blue","Green","Yellow","Purple","Orange","Pink","Brown","Black","White","Gray","Cyan","Magenta","Lime","Navy","Teal","Olive","Maroon","Aqua","Silver","Fuchsia","Gold","Indigo","Violet"];return this.random.arrayElement($)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class b8{random;locale;constructor($,Z){this.random=$,this.locale=Z}product(){let $=this.locale?.commerce?.productAdjective??["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable"],Z=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],X=this.locale?.commerce?.product??["Chair","Table","Lamp","Keyboard","Mouse","Computer","Shoes","Shirt","Pants","Hat","Gloves","Towel","Soap","Bike","Ball","Book","Wallet","Watch","Phone","Desk","Bottle","Plate","Cup","Bag","Pen","Notebook","Backpack","Sunglasses"];return`${this.random.arrayElement($)} ${this.random.arrayElement(Z)} ${this.random.arrayElement(X)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let $=["Books","Movies","Music","Games","Electronics","Computers","Home","Garden","Tools","Grocery","Health","Beauty","Toys","Kids","Baby","Clothing","Shoes","Jewelry","Sports","Outdoors","Automotive","Industrial"];return this.random.arrayElement($)}price($){let Z=$?.min??1,X=$?.max??1000,_=$?.dec??2,L=$?.symbol??"",j=this.random.float(Z,X,_);return L+j.toFixed(_)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let $=["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable","Innovative","Compact","Versatile","Modern","Classic","Vintage","Contemporary"];return this.random.arrayElement($)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let $=["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum","Bronze","Copper","Brass","Titanium","Ceramic","Velvet","Linen","Wool"];return this.random.arrayElement($)}productDescription(){let $=["The beautiful range of {adjective} {material} {product} comes with a {feature}.","Experience the {adjective} {product} that redefines {benefit}.","Our {adjective} {material} {product} is designed for {benefit}.","Discover the {adjective} {product} with {feature} for {benefit}."],Z=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],X=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement($).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement(Z)).replace("{benefit}",this.random.arrayElement(X))}review(){let $=["This product exceeded my expectations!","Absolutely love it! Worth every penny.","Great quality and fast shipping.","Not what I expected, but still decent.","Amazing! Highly recommend to everyone.","Perfect for my needs. Very satisfied.","Good value for the price.","Could be better, but it does the job.","Fantastic product! Will buy again.","Best purchase I've made this year!"];return this.random.arrayElement($)}discountCode(){let $=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],Z=this.random.int(10,99);return`${this.random.arrayElement($)}${Z}`}sku(){let $=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),Z=this.random.int(1e4,99999),X=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${$}-${Z}-${X}`}}class f8{random;locale;constructor($,Z){this.random=$,this.locale=Z}name(){let $=this.random.arrayElement(this.locale.company.name??["Company"]),Z=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${$} ${Z}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let $=this.random.arrayElement(this.locale.company.adjective??["innovative"]),Z=this.random.arrayElement(this.locale.company.descriptor??["digital"]),X=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${Z} ${X}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let $=this.buzzword(),Z=this.random.arrayElement(this.locale.company.descriptor??["digital"]),X=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${Z} ${X}`}}class T${random;constructor($){this.random=$}engine(){let $=["MySQL","PostgreSQL","MongoDB","SQLite","Redis","Oracle","Microsoft SQL Server","MariaDB","Cassandra","Elasticsearch","DynamoDB","CouchDB","Neo4j","Firebase","Firestore","InfluxDB","TimescaleDB","RethinkDB","ArangoDB","CockroachDB"];return this.random.arrayElement($)}type(){let $=["VARCHAR","INTEGER","BIGINT","SMALLINT","DECIMAL","NUMERIC","FLOAT","DOUBLE","BOOLEAN","DATE","TIME","TIMESTAMP","DATETIME","TEXT","BLOB","JSON","JSONB","UUID","ENUM","ARRAY","SERIAL","BIGSERIAL"];return this.random.arrayElement($)}collation(){let $=["utf8_general_ci","utf8_unicode_ci","utf8mb4_general_ci","utf8mb4_unicode_ci","latin1_swedish_ci","latin1_general_ci","utf8_bin","utf8mb4_bin"];return this.random.arrayElement($)}column(){let $=["id","user_id","name","email","password","created_at","updated_at","deleted_at","first_name","last_name","phone","address","city","state","country","zip_code","status","role","permissions","description","price","quantity","total","subtotal","tax","discount","shipping","notes","metadata","settings","preferences","avatar"];return this.random.arrayElement($)}table(){let $=["users","posts","comments","products","orders","customers","invoices","payments","categories","tags","roles","permissions","sessions","settings","notifications","messages","attachments","logs","analytics","reports","subscriptions","transactions"];return this.random.arrayElement($)}mongodbObjectId(){let $="";for(let Z=0;Z<24;Z++)$+="0123456789abcdef"[this.random.int(0,15)];return $}constraint(){let $=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement($)}queryType(){let $=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement($)}connectionString($){let Z=$?.engine??this.engine().toLowerCase().replace(/ /g,""),X="user",_="password",L="localhost",j=this.random.int(3000,9999),Y=this.table(),z={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[Z]||"jdbc";if(Z==="mongodb")return`${z}://user:password@localhost:${j}/${Y}`;return`${z}://user:password@localhost:${j}/${Y}`}}class k${random;constructor($){this.random=$}past($){let Z=$?.years??1,X=$?.to??new Date,_=$?.from??new Date(X.getTime()-Z*365*24*60*60*1000);return this.between({from:_,to:X})}future($){let Z=$?.years??1,X=$?.from??new Date,_=$?.to??new Date(X.getTime()+Z*365*24*60*60*1000);return this.between({from:X,to:_})}between($){let Z=$.from??new Date(Date.now()-31536000000),X=$.to??new Date,_=Z.getTime(),L=X.getTime(),j=this.random.int(_,L);return new Date(j)}recent($){let Z=$?.days??1,X=new Date,_=new Date(X.getTime()-Z*24*60*60*1000);return this.between({from:_,to:X})}soon($){let Z=$?.days??1,X=new Date,_=new Date(X.getTime()+Z*24*60*60*1000);return this.between({from:X,to:_})}month(){let $=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement($)}weekday(){let $=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement($)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween($){return this.between($)}}class x${random;constructor($){this.random=$}amount($){let Z=$?.min??0,X=$?.max??1e4,_=$?.dec??2,L=$?.symbol??"",j=this.random.float(Z,X,_);return L+j.toFixed(_)}account($=8){let Z="";for(let X=0;X<$;X++)Z+=this.random.int(0,9);return Z}accountName(){let $=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement($)} Account`}routingNumber(){return this.account(9)}creditCardNumber($){let Z=$?.formatted??!0,X=$?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),_="",L=16;switch(X){case"visa":_="4",L=16;break;case"mastercard":_=`5${this.random.int(1,5)}`,L=16;break;case"amex":_=`3${this.random.arrayElement(["4","7"])}`,L=15;break;case"discover":_="6011",L=16;break}let j=_;while(j.length<L)j+=this.random.int(0,9);if(Z){if(X==="amex")return`${j.slice(0,4)}-${j.slice(4,10)}-${j.slice(10)}`;return j.match(/.{1,4}/g)?.join("-")??j}return j}cvv(){return this.account(3)}iban($){let Z=$?.countryCode??"GB",X=$?.formatted??!1,_=this.random.int(10,99).toString(),L="WEST",j=this.account(14),Y=Z+_+"WEST"+j;if(X)return Y.match(/.{1,4}/g)?.join(" ")??Y;return Y}bic(){let $="";for(let Z=0;Z<4;Z++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let Z=0;Z<2;Z++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let Z=0;Z<2;Z++)$+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(X,_)=>_.toString())]);return $}bitcoin(){let $=this.random.arrayElement(["1","3"]);for(let Z=0;Z<33;Z++)$+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return $}ethereum(){let $="0x";for(let Z=0;Z<40;Z++)$+="0123456789abcdef"[this.random.int(0,15)];return $}currencyCode(){let $=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement($)}currencyName(){let $=["US Dollar","Euro","British Pound","Japanese Yen","Australian Dollar","Canadian Dollar","Swiss Franc","Chinese Yuan","Swedish Krona","New Zealand Dollar","Indian Rupee","Brazilian Real","Russian Ruble","South Korean Won"];return this.random.arrayElement($)}currencySymbol(){let $=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement($)}transactionType(){let $=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement($)}}class g8{random;locale;constructor($,Z){this.random=$,this.locale=Z}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let $=["Spaghetti Carbonara","Chicken Alfredo","Beef Tacos","Margherita Pizza","Caesar Salad","Pad Thai","Chicken Tikka Masala","Sushi Roll","Beef Burger","Fish and Chips","Ramen","Tom Yum Soup","Greek Salad","Lasagna","Paella","Pho","Falafel Wrap","Burrito Bowl","Chicken Curry","Steak Frites","Risotto","Poke Bowl","Bibimbap","Shakshuka","Eggs Benedict","Club Sandwich","Caprese Salad","Fettuccine Alfredo","Chicken Parmesan","Pulled Pork Sandwich","Gyro","Butter Chicken","Peking Duck"];return this.random.arrayElement($)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let $=["Garlic","Onion","Tomato","Basil","Oregano","Thyme","Rosemary","Cilantro","Parsley","Salt","Pepper","Olive Oil","Butter","Flour","Sugar","Eggs","Milk","Cheese","Chicken","Beef","Pork","Fish","Shrimp","Rice","Pasta","Potatoes","Carrots","Celery","Bell Pepper","Mushrooms","Spinach","Lettuce","Cucumber","Avocado","Lemon","Lime","Ginger","Soy Sauce","Vinegar","Honey","Cinnamon","Cumin"];return this.random.arrayElement($)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let $=["Basil","Oregano","Thyme","Rosemary","Sage","Cilantro","Parsley","Mint","Dill","Paprika","Cumin","Turmeric","Coriander","Cardamom","Cinnamon","Nutmeg","Cloves","Black Pepper","White Pepper","Cayenne","Chili Powder","Curry Powder","Garam Masala","Saffron","Vanilla","Bay Leaf","Fennel","Anise","Tarragon","Marjoram"];return this.random.arrayElement($)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let $=["Broccoli","Carrot","Celery","Lettuce","Spinach","Kale","Cabbage","Cauliflower","Brussels Sprouts","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Tomato","Cucumber","Bell Pepper","Zucchini","Eggplant","Mushroom","Onion","Garlic","Radish","Beet","Turnip","Artichoke","Bok Choy","Arugula","Swiss Chard"];return this.random.arrayElement($)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let $=["Apple","Banana","Orange","Grape","Strawberry","Blueberry","Raspberry","Blackberry","Mango","Pineapple","Watermelon","Cantaloupe","Honeydew","Peach","Plum","Cherry","Pear","Kiwi","Papaya","Dragon Fruit","Lychee","Passion Fruit","Pomegranate","Coconut","Avocado","Lemon","Lime","Grapefruit","Apricot","Fig","Date"];return this.random.arrayElement($)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let $=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement($)}seafood(){let $=["Salmon","Tuna","Cod","Halibut","Trout","Mackerel","Sardines","Anchovies","Shrimp","Crab","Lobster","Scallops","Clams","Mussels","Oysters","Squid","Octopus","Tilapia","Sea Bass","Swordfish","Snapper","Grouper","Catfish"];return this.random.arrayElement($)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let $=["Chocolate Cake","Cheesecake","Apple Pie","Ice Cream","Brownies","Cookies","Tiramisu","Cr\xE8me Br\xFBl\xE9e","Panna Cotta","Macarons","Cupcakes","Donuts","Eclairs","Profiteroles","Cannoli","Baklava","Flan","Churros","Gelato","Sorbet","Mousse","Tart","Cobbler","Pudding","Trifle","Souffl\xE9"];return this.random.arrayElement($)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let $=["Italian","Chinese","Japanese","Mexican","Thai","Indian","French","Greek","Spanish","Korean","Vietnamese","Lebanese","Turkish","Brazilian","Moroccan","Ethiopian","Caribbean","Peruvian","German","American","British","Irish"];return this.random.arrayElement($)}description(){let $=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],Z=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement($)} ${this.random.arrayElement(Z)}`}}class B${random;constructor($){this.random=$}branch(){let $=["feature","bugfix","hotfix","refactor","chore","docs","test"],Z=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],X=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],_=this.random.arrayElement($),L=this.random.arrayElement(Z),j=this.random.arrayElement(X);return`${_}/${L}-${j}`}commitMessage(){let $=["feat","fix","docs","style","refactor","test","chore","perf"],Z=["api","ui","auth","db","config","deps","core","utils"],X=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],_=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],L=this.random.arrayElement($),j=this.random.boolean(0.5)?`(${this.random.arrayElement(Z)})`:"",Y=this.random.arrayElement(X),z=this.random.arrayElement(_);return`${L}${j}: ${Y} ${z}`}commitSha($){let Z=$?.short?7:40,X="0123456789abcdef",_="";for(let L=0;L<Z;L++)_+="0123456789abcdef"[this.random.int(0,15)];return _}commitEntry(){let $=this.commitSha({short:!0}),Z=this.commitMessage();return`${$} ${Z}`}commitAuthor($){let Z=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],X=$?.name??this.random.arrayElement(Z),_=$?.email??`${X.toLowerCase().replace(" ",".")}@example.com`;return`${X} <${_}>`}remote($){let Z=$?.protocol??this.random.arrayElement(["https","ssh"]),X=$?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),_=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),L=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),j={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if(Z==="ssh")return`git@${j[X]}:${_}/${L}.git`;return`https://${j[X]}/${_}/${L}.git`}tag(){let $=this.random.int(0,5),Z=this.random.int(0,20),X=this.random.int(0,50),_=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${$}.${Z}.${X}${_}`}}class p8{random;locale;constructor($,Z){this.random=$,this.locale=Z}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let $=["TCP","HTTP","SDD","RAM","GB","CSS","SSL","AGP","SQL","CLI","IB","UX","UI","FTP","AI","ADP","RSS","XML","EXE","COM","HDD","THX","MP3","GPU","API","DNS","IP","LAN","WAN","VPN","SSH","HTTPS","JSON","REST","SOAP"];return this.random.arrayElement($)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let $=["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","haptic","multi-byte","bluetooth","wireless","mobile","neural","optical","solid state","cloud","quantum","distributed","encrypted"];return this.random.arrayElement($)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let $=["driver","protocol","bandwidth","panel","microchip","program","port","card","array","interface","system","sensor","firewall","hard drive","pixel","alarm","feed","monitor","application","transmitter","bus","circuit","capacitor","matrix","server","database","network","router","switch","gateway","node","cluster"];return this.random.arrayElement($)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let $=["back up","bypass","hack","override","compress","copy","navigate","index","connect","generate","quantify","calculate","synthesize","input","transmit","program","reboot","parse","compile","encode","decode","encrypt","decrypt","patch","upgrade","deploy","configure","optimize","refactor","debug"];return this.random.arrayElement($)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let $=["backing up","bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","quantifying","calculating","synthesizing","transmitting","programming","parsing","compiling","encoding","decoding","encrypting","decrypting","patching","deploying","configuring","optimizing"];return this.random.arrayElement($)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let $=["If we {verb} the {noun}, we can get to the {abbreviation} {noun} through the {adjective} {abbreviation} {noun}!","We need to {verb} the {adjective} {abbreviation} {noun}!","Try to {verb} the {abbreviation} {noun}, maybe it will {verb} the {adjective} {noun}!","You can't {verb} the {noun} without {ingverb} the {adjective} {abbreviation} {noun}!","Use the {adjective} {abbreviation} {noun}, then you can {verb} the {adjective} {noun}!","The {abbreviation} {noun} is down, {verb} the {adjective} {noun} so we can {verb} the {abbreviation} {noun}!","{ingverb} the {noun} won't do anything, we need to {verb} the {adjective} {abbreviation} {noun}!","I'll {verb} the {adjective} {abbreviation} {noun}, that should {verb} the {abbreviation} {noun}!"];return this.random.arrayElement($).replace(/\{verb\}/g,()=>this.verb()).replace(/\{ingverb\}/g,()=>this.ingverb()).replace(/\{noun\}/g,()=>this.noun()).replace(/\{adjective\}/g,()=>this.adjective()).replace(/\{abbreviation\}/g,()=>this.abbreviation())}}class h${random;constructor($){this.random=$}randomElement($){return this.random.arrayElement($)}arrayElement($){return this.random.arrayElement($)}arrayElements($,Z){return this.random.arrayElements($,Z)}shuffle($){return this.random.shuffle($)}numerify($){return $.replace(/#/g,()=>String(this.random.int(0,9)))}lexify($){return $.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify($){return this.numerify(this.lexify($))}replaceSymbols($){return this.random.replaceSymbols($)}boolean($=0.5){return this.random.boolean($)}objectKey($){let Z=Object.keys($);return this.random.arrayElement(Z)}objectValue($){let Z=this.objectKey($);return $[Z]}multiple($,Z=3){return Array.from({length:Z},$)}maybe($,Z=0.5){return this.random.boolean(Z)?$():void 0}unique($,Z=50){let X=new Set,_=0;while(_<Z){let L=$();if(!X.has(L))return X.add(L),L;_++}throw Error(`Failed to generate unique value after ${Z} retries`)}replaceCreditCardSymbols($="####-####-####-####",Z="#"){return this.random.replaceCreditCardSymbols($,Z)}regexify($){return $.replace(/\[A-Z\]/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/\[a-z\]/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split(""))).replace(/\[0-9\]/g,()=>String(this.random.int(0,9))).replace(/\{(\d+)\}/g,(Z,X)=>{return""})}}class y${random;constructor($){this.random=$}url($){let Z=$?.width??640,X=$?.height??480;return`https://via.placeholder.com/${Z}x${X}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr($){let Z=$?.width??640,X=$?.height??480,_=$?.category??"";if(_)return`https://loremflickr.com/${Z}/${X}/${_}`;return`https://loremflickr.com/${Z}/${X}`}urlPicsumPhotos($){let Z=$?.width??640,X=$?.height??480,_=`https://picsum.photos/${Z}/${X}`;if($?.grayscale)_+="?grayscale";if($?.blur)_+=$?.grayscale?`&blur=${$.blur}`:`?blur=${$.blur}`;return _}dataUri($){let Z=$?.width??640,X=$?.height??480,_=$?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),L=`<svg xmlns="http://www.w3.org/2000/svg" width="${Z}" height="${X}"><rect width="${Z}" height="${X}" fill="#${_}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(L)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let $=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement($)}imageType(){let $=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement($)}}class d8{random;locale;domainWordsCache=null;constructor($,Z){this.random=$,this.locale=Z}getDomainWords(){if(!this.domainWordsCache){let $=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=$.map((Z)=>Z.toLowerCase().replace(/[^a-z0-9]/g,"")).filter((Z)=>Z.length>0)}return this.domainWordsCache}email($){let Z;if($?.firstName)Z=$.firstName.toLowerCase();else{let Y=this.locale.person.firstNameMale.length,z=this.locale.person.firstNameFemale.length,F=this.locale.person.firstNameNeutral?.length||0,E=Y+z+F,U=this.random.int(0,E-1);if(U<Y)Z=this.locale.person.firstNameMale[U].toLowerCase();else if(U<Y+z)Z=this.locale.person.firstNameFemale[U-Y].toLowerCase();else Z=this.locale.person.firstNameNeutral[U-Y-z].toLowerCase()}let X=$?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),_=$?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),L=this.random.arrayElement(WX),j=this.random.arrayElement(this.getDomainWords());return`${Z}${L}${X}@${j}.${_}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let $=this.locale.person.firstNameMale.length,Z=this.locale.person.firstNameFemale.length,X=this.locale.person.firstNameNeutral?.length||0,_=$+Z+X,L=this.random.int(0,_-1),j;if(L<$)j=this.locale.person.firstNameMale[L].toLowerCase();else if(L<$+Z)j=this.locale.person.firstNameFemale[L-$].toLowerCase();else j=this.locale.person.firstNameNeutral[L-$-Z].toLowerCase();let Y=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),z=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),F=[".","_",""],E=this.random.arrayElement(F);return`${j}${E}${Y}@${z}`}username($){let Z;if($?.firstName)Z=$.firstName.toLowerCase();else{let L=this.locale.person.firstNameMale.length,j=this.locale.person.firstNameFemale.length,Y=this.locale.person.firstNameNeutral?.length||0,z=L+j+Y,F=this.random.int(0,z-1);if(F<L)Z=this.locale.person.firstNameMale[F].toLowerCase();else if(F<L+j)Z=this.locale.person.firstNameFemale[F-L].toLowerCase();else Z=this.locale.person.firstNameNeutral[F-L-j].toLowerCase()}let X=$?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),_=[`${Z}${X}`,`${Z}_${X}`,`${Z}.${X}`,`${Z}${this.random.int(10,999)}`,`${Z}_${X}${this.random.int(10,99)}`];return this.random.arrayElement(_)}password($){let Z=$?.length??12,X=$?.memorable??!1,_=$?.prefix??"";if(X){let Y=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],z=[];for(let F=0;F<3;F++)z.push(this.random.arrayElement(Y));return _+z.join("-")+this.random.int(10,999)}let L="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",j=_;for(let Y=_.length;Y<Z;Y++)j+=L[this.random.int(0,L.length-1)];return j}url($){let Z=$?.protocol??this.random.arrayElement(["http","https"]),X=$?.domain??this.domainName();return`${Z}://${X}`}domainName(){return`${this.domainWord()}.${this.domainSuffix()}`}domainWord(){return this.random.arrayElement(this.getDomainWords())}domainSuffix(){return this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"])}ipv4(){return`${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}`}ipv6(){let $=[];for(let Z=0;Z<8;Z++)$.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return $.join(":")}mac($=":"){let Z=[];for(let X=0;X<6;X++)Z.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return Z.join($)}userAgent(){let $=["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/120.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 14.0; rv:109.0) Gecko/20100101 Firefox/120.0"];return this.random.arrayElement($)}slug($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return Z.join("-").toLowerCase()}ip(){return this.ipv4()}}class A${random;constructor($){this.random=$}word(){return this.random.arrayElement(DX)}words($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.word());return Z.join(" ")}sentence($){let Z=$??this.random.int(3,10),X=this.words(Z);return`${X.charAt(0).toUpperCase()+X.slice(1)}.`}sentences($=3,Z=" "){let X=[];for(let _=0;_<$;_++)X.push(this.sentence());return X.join(Z)}paragraph($){let Z=$??this.random.int(3,7);return this.sentences(Z)}paragraphs($=3,Z=`
441
+ `;Z+=`| Variable | Type | Description | Example |
442
+ `,Z+=`|----------|------|-------------|----------|
443
+ `;for(let Y of X)Z+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
444
+ `;return Z}}function az(X,$){let Z=mU("process");if(typeof Z>"u"||!Z.env)return $;let Y=Z.env[X];return Y!==void 0?Y:$}function vU(X,$,Z={}){return bU(X,$,Z,new WeakMap)}function bU(X,$,Z,Y){let{arrayMergeMode:U="replace",skipNullish:_=!1,customMerger:Q}=Z;if($===null||$===void 0)return _?X:$;if(Q){let L=Q(X,$);if(L!==void 0)return L}if(Array.isArray($)||Array.isArray(X))return fU(X,$,U,Y);if(!O9($)||!O9(X))return $;return $L(X,$,Z,Y)}function fU(X,$,Z,Y){if(Array.isArray($)&&!Array.isArray(X))return $;if(Array.isArray(X)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(X))switch(Z){case"replace":return $;case"concat":return tz(X,$);case"smart":return ez(X,$,Y);default:return $}return $}function tz(X,$){let Z=[...$];for(let Y of X)if(!Z.some((U)=>x1(U,Y)))Z.push(Y);return Z}function ez(X,$,Z){if($.length===0)return X;if(X.length===0)return $;if(O9($[0])&&O9(X[0]))return XL(X,$,Z);if($.every((Y)=>typeof Y==="string")&&X.every((Y)=>typeof Y==="string")){let Y=[...$];for(let U of X)if(!Y.includes(U))Y.push(U);return Y}return $}function XL(X,$,Z){let Y=[...$];for(let U of X){if(!O9(U)){Y.push(U);continue}let _=["id","name","key","path","type"],Q=!1;for(let L of _)if(L in U){if(Y.find((z)=>O9(z)&&(L in z)&&z[L]===U[L])){Q=!0;break}}if(!Q)Y.push(U)}return Y}function $L(X,$,Z,Y){let U=$;if(O9(U)&&Y.has(U))return Y.get(U);let _={...X};if(O9(U))Y.set(U,_);for(let Q in U){if(!Object.prototype.hasOwnProperty.call(U,Q))continue;let L=U[Q],z=_[Q];if(Z.skipNullish&&(L===null||L===void 0))continue;if(L===null||L===void 0){_[Q]=L;continue}if(O9(L)&&O9(z))_[Q]=bU(z,L,Z,Y);else if(Array.isArray(L)||Array.isArray(z))_[Q]=fU(z,L,Z.arrayMergeMode||"smart",Y);else _[Q]=L}return _}function Q5(X,$,Z="replace"){return vU(X,$,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function x1(X,$){if(X===$)return!0;if(Array.isArray(X)&&Array.isArray($)){if(X.length!==$.length)return!1;for(let Z=0;Z<X.length;Z++)if(!x1(X[Z],$[Z]))return!1;return!0}if(O9(X)&&O9($)){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let U of Z){if(!Object.prototype.hasOwnProperty.call($,U))return!1;if(!x1(X[U],$[U]))return!1}return!0}return!1}function O9(X){return Boolean(X&&typeof X==="object"&&!Array.isArray(X))}class LZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(X,$,Z={}){let{arrayStrategy:Y="replace",useCache:U=!0,cacheTtl:_,trackPerformance:Q=!0,verbose:L=!1}=Z;if(U){let j=hX.getWithFileCheck("file",X);if(j){if(L)console.log(`Configuration loaded from cache: ${X}`);return j}}let z=async()=>{if(!Q8(X))return null;try{let j=`?t=${Date.now()}`,E=await import(X+j),V=E.default||E,G="default"in E,J=Object.keys(E).length>0;if(!G&&!J)throw new C$(X,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof V!=="object"||V===null||Array.isArray(V))throw new C$(X,Error("Configuration must export a valid object"),"unknown");let W={config:Q5($,V,Y),source:{type:"file",path:X,priority:100,timestamp:new Date}};if(U)hX.setWithFileCheck("file",W,X,_);return W}catch(j){throw j instanceof Error?m9.configLoad(X,j):m9.configLoad(X,Error(String(j)))}};if(Q)return x$.track("loadFromPath",z,{path:X});return z()}async tryLoadFromPaths(X,$,Z={}){for(let Y of X)try{let U=await this.loadFromPath(Y,$,Z);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Z.verbose)console.warn(`Failed to load config from ${Y}:`,U)}return null}generateConfigPaths(X,$,Z){let Y=this.generateNamePatterns(X,Z),U=[];for(let _ of Y)for(let Q of this.extensions)U.push(uZ($,`${_}${Q}`));return U}generateNamePatterns(X,$){let Z=[];if(Z.push("config",".config"),X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let Y=$===void 0?[]:Array.isArray($)?$:[$];for(let _ of Y){if(!_)continue;if(Z.push(_,`.${_}.config`,`${_}.config`,`.${_}`),X)Z.push(`${X}.${_}.config`,`.${X}.${_}.config`)}let U=new Set;return Z.filter((_)=>{if(!_||U.has(_))return!1;return U.add(_),!0})}checkFileAccess(X){return yU(async()=>{return Q8(X)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(X,$,Z){let Y=[];if(!Q8(X))return Y;if($||Z){let U=this.generateNamePatterns($||"",Z);for(let _ of U)for(let Q of this.extensions){let L=uZ(X,`${_}${Q}`);if(await this.checkFileAccess(L))Y.push(L)}}else try{let{readdirSync:U}=await import("fs"),_=U(X);for(let Q of _)if(this.looksLikeConfigFile(Q)){let L=uZ(X,Q);if(await this.checkFileAccess(L))Y.push(L)}}catch{return[]}return Y}looksLikeConfigFile(X){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(($)=>$.test(X))}async validateConfigFile(X){let $=[];try{if(!Q8(X))return $.push("Configuration file does not exist"),$;let Z=await import(X),Y=Z.default||Z;if(Y===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)$.push("Configuration must be an object");else if(Array.isArray(Y))$.push("Configuration cannot be an array at the root level");if(X.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),_=U(X,"utf8");JSON.parse(_)}catch(U){$.push(`Invalid JSON syntax: ${U}`)}}catch(Z){$.push(`Failed to load configuration file: ${Z}`)}return $}async getFileModificationTime(X){try{let{statSync:$}=await import("fs");return $(X).mtime}catch{return null}}async preloadConfigurations(X,$={}){let Z=new Map;return await Promise.allSettled(X.map(async(Y)=>{try{let U=await this.loadFromPath(Y,{},$);if(U)Z.set(Y,U.config)}catch(U){if($.verbose)console.warn(`Failed to preload ${Y}:`,U)}})),Z}}class z5{async validateConfiguration(X,$,Z={}){let{stopOnFirstError:Y=!1,validateRequired:U=!0,validateTypes:_=!0,customRules:Q=[],trackPerformance:L=!0,verbose:z=!1}=Z,j=async()=>{let E=[],V=[],G={stopOnFirstError:Y,validateRequired:U,validateTypes:_,customRules:Q,trackPerformance:L,verbose:z};try{if(typeof $==="string")return await this.validateWithSchemaFile(X,$,G);else if(Array.isArray($))return this.validateWithRules(X,[...$,...Q],G);else return this.validateWithJSONSchema(X,$,G)}catch(J){return E.push({path:"",message:`Validation failed: ${J}`,rule:"system"}),{isValid:!1,errors:E,warnings:V}}};if(L)return await x$.track("validateConfiguration",j);return j()}async validateWithSchemaFile(X,$,Z){try{if(!Bz($))throw new w$($,[{path:"",message:"Schema file does not exist"}]);let Y=await import($),U=Y.default||Y;if(Array.isArray(U))return this.validateWithRules(X,U,Z);else return this.validateWithJSONSchema(X,U,Z)}catch(Y){throw new w$($,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(X,$,Z){let Y=[],U=[];return this.validateObjectAgainstSchema(X,$,"",Y,U,Z),{isValid:Y.length===0,errors:Y,warnings:U}}validateObjectAgainstSchema(X,$,Z,Y,U,_){if(_.validateTypes&&$.type){let Q=Array.isArray(X)?"array":typeof X,L=Array.isArray($.type)?$.type:[$.type];if(!L.includes(Q)){if(Y.push({path:Z,message:`Expected type ${L.join(" or ")}, got ${Q}`,expected:L.join(" or "),actual:Q,rule:"type"}),_.stopOnFirstError)return}}if($.enum&&!$.enum.includes(X)){if(Y.push({path:Z,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"}),_.stopOnFirstError)return}if(typeof X==="string"){if($.minLength!==void 0&&X.length<$.minLength)Y.push({path:Z,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:X.length,rule:"minLength"});if($.maxLength!==void 0&&X.length>$.maxLength)Y.push({path:Z,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:X.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(X))Y.push({path:Z,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:X,rule:"pattern"})}}if(typeof X==="number"){if($.minimum!==void 0&&X<$.minimum)Y.push({path:Z,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:X,rule:"minimum"});if($.maximum!==void 0&&X>$.maximum)Y.push({path:Z,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:X,rule:"maximum"})}if(Array.isArray(X)&&$.items)for(let Q=0;Q<X.length;Q++){let L=Z?`${Z}[${Q}]`:`[${Q}]`;if(this.validateObjectAgainstSchema(X[Q],$.items,L,Y,U,_),_.stopOnFirstError&&Y.length>0)return}if(X&&typeof X==="object"&&!Array.isArray(X)){let Q=X;if(_.validateRequired&&$.required){for(let L of $.required)if(!(L in Q)){if(Y.push({path:Z?`${Z}.${L}`:L,message:`Missing required property '${L}'`,expected:"required",rule:"required"}),_.stopOnFirstError)return}}if($.properties){for(let[L,z]of Object.entries($.properties))if(L in Q){let j=Z?`${Z}.${L}`:L;if(this.validateObjectAgainstSchema(Q[L],z,j,Y,U,_),_.stopOnFirstError&&Y.length>0)return}}if($.additionalProperties===!1){let L=new Set(Object.keys($.properties||{}));for(let z of Object.keys(Q))if(!L.has(z))U.push({path:Z?`${Z}.${z}`:z,message:`Additional property '${z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(X,$,Z){let Y=[],U=[];for(let _ of $)try{let Q=this.getValueByPath(X,_.path),L=this.validateWithRule(Q,_,_.path);if(Y.push(...L),Z.stopOnFirstError&&Y.length>0)break}catch(Q){Y.push({path:_.path,message:`Rule validation failed: ${Q}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:U}}validateWithRule(X,$,Z){let Y=[];if($.required&&(X===void 0||X===null))return Y.push({path:Z,message:$.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),Y;if(X===void 0||X===null)return Y;if($.type){let U=Array.isArray(X)?"array":typeof X;if(U!==$.type)Y.push({path:Z,message:$.message||`Expected type ${$.type}, got ${U}`,expected:$.type,actual:U,rule:"type"})}if($.min!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U<$.min)Y.push({path:Z,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:U,rule:"min"})}if($.max!==void 0){let U=Array.isArray(X)?X.length:typeof X==="string"?X.length:typeof X==="number"?X:0;if(U>$.max)Y.push({path:Z,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:U,rule:"max"})}if($.pattern&&typeof X==="string"){if(!$.pattern.test(X))Y.push({path:Z,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:X,rule:"pattern"})}if($.enum&&!$.enum.includes(X))Y.push({path:Z,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:X,rule:"enum"});if($.validator){let U=$.validator(X);if(U)Y.push({path:Z,message:$.message||U,rule:"custom"})}return Y}getValueByPath(X,$){if(!$)return X;let Z=$.split("."),Y=X;for(let U of Z)if(Y&&typeof Y==="object"&&U in Y)Y=Y[U];else return;return Y}generateRulesFromInterface(X){let $=[],Z=X.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of Z){let[,U,_,Q]=Y;$.push({path:U,required:!_,type:this.mapTypeScriptType(Q)})}return $}mapTypeScriptType(X){switch(X.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:nU},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function ZL(X){if(!X)return"";let $=Array.isArray(X)?X.filter(Boolean):[X];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Z)=>`"${Z}"`).join(", ")}`}class B1{fileLoader=new LZ;envProcessor=new zZ;validator=new z5;async loadConfig(X){let $=Date.now(),{cache:Z,performance:Y,schema:U,validate:_,...Q}=X;try{if(Z?.enabled){let z=this.checkCache(Q.name||"",Q);if(z)return z}let L;try{L=await this.loadConfigurationStrategies(Q,!0,Z)}catch(z){let j=Q.__strictErrorHandling;if(z instanceof Error&&z.name==="ConfigNotFoundError"){if(j)throw z;L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`No configuration file found for "${Q.name||"config"}", using defaults with environment variables`]}}else if(z instanceof Error&&z.name==="ConfigLoadError"){let E=z.message.includes("EACCES")||z.message.includes("EPERM")||z.message.includes("permission denied"),V=!E&&(z.message.includes("syntax")||z.message.includes("Expected")||z.message.includes("Unexpected")||z.message.includes("BuildMessage")||z.message.includes("errors building")),G=z.message.includes("Configuration must export a valid object")||z.message.includes("Configuration file is empty and exports nothing");if(j&&(G||E))throw z;if(V&&(!j||!G))L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading error, using defaults: ${z.message}`]};else throw z}else L={...await this.applyEnvironmentVariables(Q.name||"",Q.defaultConfig,Q.checkEnv!==!1,Q.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${z instanceof Error?z.message:String(z)}`]}}if(U||_)await this.validateConfiguration(L.config,U,_,Q.name);if(Z?.enabled&&L)this.cacheResult(Q.name||"",L,Z,Q);if(Y?.enabled){let z={operation:"loadConfig",duration:Date.now()-$,configName:Q.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(z);if(Y.slowThreshold&&z.duration>Y.slowThreshold)j9.warn(`Slow configuration loading detected: ${z.duration}ms for ${Q.name}`);L.metrics=z}return L}catch(L){let z=Date.now()-$;throw j9.error(`Configuration loading failed after ${z}ms:`,[L instanceof Error?L:Error(String(L))]),L}}async loadConfigurationStrategies(X,$=!1,Z){let{name:Y="",alias:U,cwd:_,configDir:Q,defaultConfig:L,checkEnv:z=!0,arrayStrategy:j="replace",verbose:E=!1}=X,V=_||XX.cwd(),G=[],J=await this.loadLocalConfiguration(Y,U,V,Q,L,j,E,z,Z);if(J)return G.push(...this.getLocalSearchPaths(Y,U,V,Q)),this.finalizeResult(J,G,z,Y,E);let W=await this.loadHomeConfiguration(Y,U,L,j,E,z);if(W)return G.push(...this.getHomeSearchPaths(Y,U)),this.finalizeResult(W,G,z,Y,E);let F=await this.loadPackageJsonConfiguration(Y,U,V,L,j,E,z);if(F)return G.push(l0(V,"package.json")),this.finalizeResult(F,G,z,Y,E);if(G.push(...this.getAllSearchPaths(Y,U,V,Q)),$)throw m9.configNotFound(Y,G,U);return{...await this.applyEnvironmentVariables(Y,L,z,E),warnings:[`No configuration file found for "${Y}"${ZL(U)}, using defaults with environment variables`]}}async loadLocalConfiguration(X,$,Z,Y,U,_,Q,L,z){let j=L?aX(X,U,Q):U,E=this.getLocalDirectories(Z,Y);for(let V of E){if(Q)j9.info(`Searching for configuration in: ${V}`);let G=this.fileLoader.generateConfigPaths(X,V,$),J=await this.fileLoader.tryLoadFromPaths(G,j,{arrayStrategy:_,verbose:Q,cacheTtl:z?.ttl,useCache:!z?.ttl||z.ttl>100});if(J){if(Q)j9.success(`Configuration loaded from: ${J.source.path}`);return J}}return null}async loadHomeConfiguration(X,$,Z,Y,U,_){if(!X)return null;let Q=_?aX(X,Z,U):Z,L=[l0(HX(),".config",X),l0(HX(),".config"),HX()];for(let z of L){if(U)j9.info(`Checking home directory: ${z}`);let j=this.fileLoader.generateConfigPaths(X,z,$),E=await this.fileLoader.tryLoadFromPaths(j,Q,{arrayStrategy:Y,verbose:U});if(E){if(U)j9.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration(X,$,Z,Y,U,_,Q){let L=Q?aX(X,Y,_):Y;try{let z=l0(Z,"package.json");if(!S1(z))return null;let j={};try{j=JSON.parse(vz(z,"utf8"))}catch(G){if(_)j9.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let E=j[X],V=X;if(!E&&$){let G=Array.isArray($)?$:[$];for(let J of G){if(!J)continue;if(j[J]){E=j[J],V=J;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(_)j9.success(`Configuration loaded from package.json: ${V}`);return{config:Q5(L,E,U),source:{type:"package.json",path:z,priority:30,timestamp:new Date}}}}catch(z){if(_)j9.warn("Failed to load package.json:",[z instanceof Error?z:Error(String(z))])}return null}async applyEnvironmentVariables(X,$,Z,Y){if(!Z||!X||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:aX(X,$,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(X,$,Z,Y,U){return{config:X.config,source:X.source,path:X.source.path}}async validateConfiguration(X,$,Z,Y){let U=[];if(Z){let _=Z(X);if(_)U.push(..._)}if($){let _=await this.validator.validateConfiguration(X,$);if(!_.isValid)U.push(..._.errors.map((Q)=>Q.path?`${Q.path}: ${Q.message}`:Q.message))}if(U.length>0)throw m9.configValidation(Y||"unknown",U,Y)}checkCache(X,$){let Z=this.generateCacheKey(X,$);return hX.get(Z)||null}cacheResult(X,$,Z,Y){let U=this.generateCacheKey(X,Y);hX.set(U,$,void 0,Z.ttl)}generateCacheKey(X,$){let Z=[X];if($.alias){let Y=Array.isArray($.alias)?$.alias.join(","):$.alias;Z.push(`alias:${Y}`)}if($.cwd)Z.push(`cwd:${$.cwd}`);if($.configDir)Z.push(`configDir:${$.configDir}`);if("checkEnv"in $)Z.push(`checkEnv:${$.checkEnv}`);return Z.join("|")}getLocalDirectories(X,$){return Array.from(new Set([X,l0(X,"config"),l0(X,".config"),$?l0(X,$):void 0].filter(Boolean)))}getAllSearchPaths(X,$,Z,Y){let U=[];return U.push(...this.getLocalSearchPaths(X,$,Z,Y)),U.push(...this.getHomeSearchPaths(X,$)),U.push(l0(Z,"package.json")),U}getLocalSearchPaths(X,$,Z,Y){let U=this.getLocalDirectories(Z,Y),_=[];for(let Q of U)_.push(...this.fileLoader.generateConfigPaths(X,Q,$));return _}getHomeSearchPaths(X,$){if(!X)return[];let Z=[l0(HX(),".config",X),l0(HX(),".config"),HX()],Y=[];for(let U of Z)Y.push(...this.fileLoader.generateConfigPaths(X,U,$));return Y}async loadConfigWithResult(X){return this.loadConfig(X)}}function rY(X){let $=!(X.message.includes("EACCES")||X.message.includes("EPERM")||X.message.includes("permission denied"))&&(X.message.includes("syntax")||X.message.includes("Expected")||X.message.includes("Unexpected")||X.message.includes("BuildMessage")),Z=X.message.includes("Configuration must export a valid object")||X.message.includes("Configuration file is empty and exports nothing");return $||Z}async function YL(X){return k9.loadConfig({...X,__strictErrorHandling:!0})}async function L5(X){let $="defaultConfig"in X&&X.defaultConfig!==void 0?X.defaultConfig:{},Z="cache"in X||"performance"in X||"schema"in X||"validate"in X;try{let Y;if(Z)Y=await k9.loadConfig(X);else Y=await k9.loadConfig({...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??$}catch(Y){let U=Y instanceof Error?Y.name:"UnknownError",_=Y instanceof Error?Y.message:String(Y);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||_.includes("config"))&&X.verbose)j9.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let Q=Z?{...X,defaultConfig:$}:{...X,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in X?X.checkEnv!==!1:!0)return(await k9.applyEnvironmentVariables(Q.name||"",$,!0,Q.verbose||!1))?.config??$;return $}}async function UL(X={defaultConfig:{}}){if(typeof X==="string"){let{cwd:$}=await import("process");try{return(await k9.loadConfig({name:X,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&rY(Z)))return(await k9.applyEnvironmentVariables(X,{},!0,!1)).config;throw Z}}try{return(await k9.loadConfig({...X,cwd:X.cwd||XX.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&rY($)))return(await k9.applyEnvironmentVariables(X.name||"",X.defaultConfig||{},X.checkEnv!==!1,X.verbose||!1)).config;throw $}}async function _L(X,$,Z="replace"){let Y=new LZ;try{let U=await Y.loadFromPath(X,$,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function aX(X,$,Z=!1){let Y=new zZ,U=X.toUpperCase().replace(/[^A-Z0-9]/g,"_");function _(Q,L=[]){let z={...Q};for(let[j,E]of Object.entries(Q)){let V=[...L,j],G=[`${U}_${V.join("_").toUpperCase()}`,`${U}_${V.map((F)=>F.toUpperCase()).join("")}`,`${U}_${V.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],J,W;for(let F of G)if(J=XX.env[F],J!==void 0){W=F;break}if(J!==void 0&&W)if(typeof E==="boolean")z[j]=["true","1","yes"].includes(J.toLowerCase());else if(typeof E==="number"){let F=Number(J);if(!Number.isNaN(F))z[j]=F}else if(Array.isArray(E))try{z[j]=JSON.parse(J)}catch{z[j]=J.split(",").map((F)=>F.trim())}else z[j]=J;else if(E&&typeof E==="object"&&!Array.isArray(E))z[j]=_(E,V)}return z}return _($)}function QL(X){let $=l0(XX.cwd(),X.configDir),Z=l0(XX.cwd(),X.generatedDir),Y=l0(Z,"config-types.ts");if(!S1(sY(Y)))yz(sY(Y),{recursive:!0,mode:511});let U=S1($)?hz($).map((Q)=>Q.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],_=`// Generated by bunfig v${SL}
445
+ export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
446
+ `;bz(Y,_,{mode:438})}function zL(X){let $=null,Z=null,Y=()=>{if(!Z)Z=L5(X).then((_)=>{return $=_,_},(_)=>{let Q="defaultConfig"in X?X.defaultConfig:{};if($=Q,"verbose"in X&&X.verbose)j9.warn("Config loading failed, using defaults:",[_ instanceof Error?_:Error(String(_))]);return Q});return Z},U="defaultConfig"in X?X.defaultConfig:{};return $=U,Y(),new Proxy({},{get(_,Q){if($)return $[Q];let L=U[Q];return Y(),L},has(_,Q){return Q in($||U)},ownKeys(){return Object.keys($||U)},getOwnPropertyDescriptor(_,Q){return Object.getOwnPropertyDescriptor($||U,Q)},set(_,Q,L){if(!$)$={...U};return $[Q]=L,!0}})}function LL(X){let $=oY(dz.cwd(),X?.configDir||"./config");function Z(){if(!fz($))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),_=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Q=gz($).filter((z)=>U.has(nZ(z))).map((z)=>({base:z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:z})),L=new Map;for(let{base:z,file:j}of Q){let E=nZ(j).toLowerCase(),V=L.get(z);if(!V){L.set(z,j);continue}let G=nZ(V).toLowerCase();if(_.indexOf(E)<_.indexOf(G))L.set(z,j)}return Array.from(L.entries()).map(([z,j])=>({base:z,file:j})).sort((z,j)=>z.base.localeCompare(j.base))}function Y(){let U=Z(),_=U.map((z)=>z.base),Q=_.length?_.map((z)=>`'${z}'`).join(" | "):"string",L=U.length?`{
447
+ ${U.map((z)=>{let j=oY($,z.file).replace(/\\/g,"/");return` '${z.base}': typeof import('${j}').default`}).join(`,
448
+ `)}
449
+ }`:"Record<string, any>";return`export type ConfigNames = ${Q}
450
+ export type ConfigByName = ${L}
451
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
452
+ export type ConfigOf = Config
453
+ `}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(_)=>{return{path:_.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}async function jL(){if(!Q1)Q1=await L5({name:"faker",alias:"mock",defaultConfig:XZ});return Q1}function SX(X){let $=X.replace(/-/g,"_").split("_"),Z=$[0].toLowerCase(),Y=$[1]?.toUpperCase(),U=Y?`${Z}-${Y.toLowerCase()}`:Z;return{full:X,language:Z,region:Y,packageName:U,normalized:Y?`${Z}_${Y}`:Z}}function EL(X){let $=SX(X);if($.region)return[$.normalized,$.language];return[$.language]}function GL(X){return`@mock-locale/${SX(X).packageName}`}function gU(X,$){let Z={...X};for(let Y in $){let U=$[Y],_=X[Y];if(U===void 0)continue;if(typeof U==="object"&&U!==null&&!Array.isArray(U)&&typeof _==="object"&&_!==null&&!Array.isArray(_))Z[Y]=gU(_,U);else Z[Y]=U}return Z}function AX(){let X=xU.cwd(),$=NX(X,"package.json");if(!TX($))return!1;try{let Z=JSON.parse(cz($,"utf-8"));return!!(Z.workspaces||Z.workspace)}catch{return!1}}function dU(){let X=xU.cwd();if(TX(NX(X,"bun.lockb"))||TX(NX(X,"bun.lock")))return"bun";if(TX(NX(X,"pnpm-lock.yaml")))return"pnpm";if(TX(NX(X,"yarn.lock")))return"yarn";if(TX(NX(X,"package-lock.json")))return"npm";return"bun"}function pU(X,$={}){let Z=dU(),{silent:Y=!1}=$;if(!Y)console.log(`
454
+ \uD83D\uDCE6 Installing ${X} using ${Z}...`);let U={bun:{cmd:"bun",args:["add",X]},npm:{cmd:"npm",args:["install",X]},yarn:{cmd:"yarn",args:["add",X]},pnpm:{cmd:"pnpm",args:["add",X]}},{cmd:_,args:Q}=U[Z];try{let L=pz(_,Q,{stdio:"pipe",shell:!0}),z=L.stdout?.toString()||"",j=L.stderr?.toString()||"",E=z+j;if(!Y){if(z)console.log(z);if(j)console.error(j)}if(L.status===0){if(!Y)console.log(`\u2713 Successfully installed ${X}`);return!0}else{let V=E;if(V.toLowerCase().includes("dependency loop")||V.includes("DependencyLoop")||V.includes("has a dependency loop")||V.includes("An internal error occurred (DependencyLoop)")){if(!Y){if(console.log(`
455
+ \u26A0\uFE0F Package ${X} is already available in the workspace and cannot be installed separately due to a dependency loop.`),AX())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!Y)console.error(`\u2717 Failed to install ${X}`);return!1}}catch(L){if(!Y)console.error(`\u2717 Error installing ${X}:`,L);return!1}}function A$(X,$){let Z=[];for(let Y of $.rules)if(!Y.validator(X)){let U=Y.errorMessage||`Validation failed for value: ${X}`;if(Z.push(U),$.strict)throw Error(U)}return{isValid:Z.length===0,errors:Z}}function k$(X,$){let{items:Z}=$;if(Z.length===0)throw Error("Cannot select from empty weighted items array");let Y=Z.reduce((Q,L)=>Q+L.weight,0);if(Y<=0)throw Error("Total weight must be greater than 0");let U=X.number()*Y,_=0;for(let Q of Z)if(_+=Q.weight,U<=_)return Q.item;return Z[Z.length-1].item}function FL(X,$){return X.filter((Z)=>{if($.gender&&Z.gender&&Z.gender!==$.gender)return!1;if($.country){let Y=Array.isArray($.country)?$.country:[$.country];if(Z.country&&!Y.includes(Z.country))return!1}if($.region){let Y=Array.isArray($.region)?$.region:[$.region];if(Z.region&&!Y.includes(Z.region))return!1}if($.locale&&Z.locale&&Z.locale!==$.locale)return!1;if($.ageRange&&Z.age){let{min:Y,max:U}=$.ageRange;if(Z.age<Y||Z.age>U)return!1}for(let[Y,U]of Object.entries($))if(Y!=="gender"&&Y!=="country"&&Y!=="region"&&Y!=="locale"&&Y!=="ageRange"&&Z[Y]!==void 0){if(!(Array.isArray(U)?U:[U]).includes(Z[Y]))return!1}return!0})}function d9(X,$){let Z={...X};for(let Y of $){let{field:U,dependsOn:_,mapping:Q}=Y;if(Z[_]&&Q[Z[_]])Z[U]=Q[Z[_]]}return Z}function OL(X,$={}){let Z=X();if($.relationships)return d9(Z,$.relationships);return Z}class j5{providers=new Map;register(X){let{category:$,name:Z}=X;if(!this.providers.has($))this.providers.set($,new Map);this.providers.get($).set(Z,X)}get(X,$){return this.providers.get(X)?.get($)}getProvidersInCategory(X){let $=this.providers.get(X);return $?Array.from($.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove(X,$){let Z=this.providers.get(X);if(Z)return Z.delete($);return!1}clear(){this.providers.clear()}}class _${random;locale;constructor(X,$){this.random=X,this.locale=$}street(){let X=this.random.arrayElement(this.locale.address.street),$=this.streetSuffix();return`${X} ${$}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress(X){let $=this.buildingNumber(),Z=this.street();if(X?.useFullAddress)return`${$} ${Z}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${$} ${Z}`}buildingNumber(){let X=this.random.arrayElement(this.locale.address.buildingNumber??["#","##","###"]);return this.random.replaceSymbols(X)}city(){return this.random.arrayElement(this.locale.address.city)}state(){return this.random.arrayElement(this.locale.address.state)}stateAbbr(){return this.random.arrayElement(this.locale.address.stateAbbr??[])}country(){return this.random.arrayElement(this.locale.address.country)}countryCode(){return this.random.arrayElement(this.locale.address.countryCode??[])}zipCode(){let X=this.random.arrayElement(this.locale.address.zipCode);return this.random.replaceSymbols(X)}direction(){return this.random.arrayElement(this.locale.address.direction??["North","South","East","West"])}latitude(X){let $=X?.min??-90,Z=X?.max??90,Y=X?.precision??4;return this.random.float($,Z,Y)}longitude(X){let $=X?.min??-180,Z=X?.max??180,Y=X?.precision??4;return this.random.float($,Z,Y)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced(X){let $;if(X?.constraints?.country){let Z=X.constraints.country,Y=Array.isArray(Z)?Z:[Z];$=this.city()}else $=this.city();if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({city:$,country:X?.constraints?.country},X.relationships).city||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.city()}}return $}countryAdvanced(X){let $;if(X?.constraints?.country){let Z=X.constraints.country,Y=Array.isArray(Z)?Z:[Z];$=this.random.arrayElement(Y)}else $=this.country();if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({country:$},X.relationships).country||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.country()}}return $}addressAdvanced(X){let $=this.countryAdvanced(X),Z=this.cityAdvanced(X),Y=this.state(),U=this.stateAbbr(),_=this.zipCode(),Q=this.street(),L=this.latitude(),z=this.longitude(),j={street:Q,city:Z,state:Y,stateAbbr:U,country:$,countryCode:this.countryCode(),zipCode:_,latitude:L,longitude:z};if(X?.relationships)return d9(j,X.relationships);return j}neighborhood(X){let $=X?.size||this.random.int(3,10),Z=this.cityAdvanced(X),Y=this.state(),U=this.zipCode(),_=[];for(let Q=0;Q<$;Q++)_.push({street:this.street(),city:Z,state:Y,zipCode:U,latitude:this.latitude({min:this.latitude()-0.01,max:this.latitude()+0.01}),longitude:this.longitude({min:this.longitude()-0.01,max:this.longitude()+0.01})});return _}}class Q${random;locale;constructor(X,$){this.random=X,this.locale=$}type(){if(this.locale?.animal?.type)return this.random.arrayElement(this.locale.animal.type);let X=["Mammal","Bird","Reptile","Amphibian","Fish","Invertebrate","Insect","Arachnid"];return this.random.arrayElement(X)}dog(){if(this.locale?.animal?.dog)return this.random.arrayElement(this.locale.animal.dog);let X=["Golden Retriever","Labrador Retriever","German Shepherd","Bulldog","Beagle","Poodle","Rottweiler","Yorkshire Terrier","Boxer","Dachshund","Siberian Husky","Great Dane","Doberman Pinscher","Australian Shepherd","Cavalier King Charles Spaniel","Shih Tzu","Boston Terrier","Pomeranian","Havanese","Shetland Sheepdog","Bernese Mountain Dog","English Springer Spaniel","Brittany","Pug","Cocker Spaniel","Border Collie"];return this.random.arrayElement(X)}cat(){if(this.locale?.animal?.cat)return this.random.arrayElement(this.locale.animal.cat);let X=["Persian","Maine Coon","Ragdoll","British Shorthair","Siamese","Scottish Fold","Sphynx","Abyssinian","Devon Rex","American Shorthair","Bengal","Russian Blue","Birman","Oriental Shorthair","Norwegian Forest Cat","Cornish Rex","Himalayan","Exotic Shorthair","Burmese","Turkish Angora","Somali","Manx","Tonkinese"];return this.random.arrayElement(X)}bird(){if(this.locale?.animal?.bird)return this.random.arrayElement(this.locale.animal.bird);let X=["Eagle","Hawk","Falcon","Owl","Parrot","Macaw","Cockatoo","Parakeet","Canary","Finch","Sparrow","Robin","Blue Jay","Cardinal","Crow","Raven","Pigeon","Dove","Hummingbird","Woodpecker","Pelican","Swan","Duck","Goose","Flamingo","Penguin","Ostrich","Emu","Peacock","Turkey","Chicken","Rooster"];return this.random.arrayElement(X)}fish(){if(this.locale?.animal?.fish)return this.random.arrayElement(this.locale.animal.fish);let X=["Goldfish","Betta","Guppy","Angelfish","Neon Tetra","Molly","Platy","Swordtail","Clownfish","Tang","Damselfish","Lionfish","Grouper","Snapper","Tuna","Marlin","Swordfish","Shark","Ray","Barracuda","Catfish","Bass","Pike","Trout","Carp"];return this.random.arrayElement(X)}bear(){let X=["Grizzly Bear","Black Bear","Polar Bear","Brown Bear","Panda Bear","Sun Bear","Sloth Bear","Spectacled Bear","Asian Black Bear","Kodiak Bear"];return this.random.arrayElement(X)}cetacean(){let X=["Blue Whale","Humpback Whale","Orca","Dolphin","Porpoise","Beluga Whale","Sperm Whale","Gray Whale","Narwhal","Bottlenose Dolphin","Pilot Whale"];return this.random.arrayElement(X)}horse(){if(this.locale?.animal?.horse)return this.random.arrayElement(this.locale.animal.horse);let X=["Arabian","Thoroughbred","Quarter Horse","Morgan","Appaloosa","Paint Horse","Tennessee Walker","Standardbred","Mustang","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Shire","Haflinger","Icelandic","Shetland Pony"];return this.random.arrayElement(X)}insect(){if(this.locale?.animal?.insect)return this.random.arrayElement(this.locale.animal.insect);let X=["Butterfly","Moth","Bee","Wasp","Ant","Beetle","Dragonfly","Grasshopper","Cricket","Ladybug","Firefly","Mosquito","Fly","Cockroach","Termite","Flea","Praying Mantis","Cicada","Caterpillar","Walking Stick"];return this.random.arrayElement(X)}lion(){let X=["African Lion","Asiatic Lion","Mountain Lion","Sea Lion"];return this.random.arrayElement(X)}rabbit(){if(this.locale?.animal?.rabbit)return this.random.arrayElement(this.locale.animal.rabbit);let X=["Holland Lop","Netherland Dwarf","Mini Rex","Lionhead","Flemish Giant","English Lop","Mini Lop","Dutch","Himalayan","Californian","New Zealand","Rex","Angora"];return this.random.arrayElement(X)}snake(){let X=["Python","Boa Constrictor","Rattlesnake","Cobra","Viper","Anaconda","Garter Snake","Corn Snake","King Snake","Milk Snake","Black Mamba","Copperhead","Cottonmouth"];return this.random.arrayElement(X)}}class z${random;locale;constructor(X,$){this.random=X,this.locale=$}title(){if(this.locale?.book?.title)return this.random.arrayElement(this.locale.book.title);let X=["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","The Chronicles of Narnia","Brave New World","The Divine Comedy","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude","The Sound and the Fury","Invisible Man","Beloved","The Grapes of Wrath","Catch-22","Slaughterhouse-Five","Fahrenheit 451","The Handmaid's Tale","The Road","Life of Pi","The Kite Runner","The Book Thief"];return this.random.arrayElement(X)}author(){if(this.locale?.book?.author)return this.random.arrayElement(this.locale.book.author);let X=["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee","Maya Angelou","Toni Morrison","Gabriel Garc\xEDa M\xE1rquez","Franz Kafka","James Joyce","Virginia Woolf","Oscar Wilde","Emily Dickinson","Walt Whitman","Robert Frost","Sylvia Plath","Kurt Vonnegut","Margaret Atwood","Haruki Murakami","Chimamanda Ngozi Adichie"];return this.random.arrayElement(X)}publisher(){if(this.locale?.book?.publisher)return this.random.arrayElement(this.locale.book.publisher);let X=["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Pearson","Wiley","Springer","McGraw-Hill","Bloomsbury","Vintage","Doubleday","Knopf"];return this.random.arrayElement(X)}genre(){if(this.locale?.book?.genre)return this.random.arrayElement(this.locale.book.genre);let X=["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Poetry","Drama","Comedy","Adventure","Young Adult","Children's","Crime","Western","Dystopian","Paranormal","Contemporary","Classic","Literary Fiction"];return this.random.arrayElement(X)}series(){if(this.locale?.book?.series)return this.random.arrayElement(this.locale.book.series);let X=["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","The Maze Runner","Divergent","The Mortal Instruments","Sherlock Holmes","Discworld","Dune","Foundation","The Wheel of Time","The Witcher","Millennium","Jack Reacher"];return this.random.arrayElement(X)}isbn(){if(this.random.boolean(0.5)){let _=Array.from({length:9},()=>this.random.int(0,9)),Q=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${_.slice(0,1).join("")}-${_.slice(1,4).join("")}-${_.slice(4,9).join("")}-${Q}`}let X="978",$=this.random.int(0,9),Z=Array.from({length:3},()=>this.random.int(0,9)).join(""),Y=Array.from({length:5},()=>this.random.int(0,9)).join(""),U=this.random.int(0,9);return`${X}-${$}-${Z}-${Y}-${U}`}format(){let X=["Hardcover","Paperback","Mass Market Paperback","eBook","Audiobook","Kindle","PDF","EPUB","Board Book","Leather Bound","Library Binding"];return this.random.arrayElement(X)}review(){if(this.locale?.book?.review)return this.random.arrayElement(this.locale.book.review);let X=["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","A page-turner with incredible characters.","One of the best books I've ever read.","Absolutely captivating!"];return this.random.arrayElement(X)}}class L${random;locale;constructor(X,$){this.random=X,this.locale=$}hex(X){let $=X?.prefix??"#",Z=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return $+Z}rgb(X){let $=this.random.int(0,255),Z=this.random.int(0,255),Y=this.random.int(0,255);if(X?.alpha){let U=this.random.float(0,1,2);if(X?.format==="array")return[$,Z,Y,U];return`rgba(${$}, ${Z}, ${Y}, ${U})`}if(X?.format==="array")return[$,Z,Y];return`rgb(${$}, ${Z}, ${Y})`}hsl(X){let $=this.random.int(0,360),Z=this.random.int(0,100),Y=this.random.int(0,100);if(X?.alpha){let U=this.random.float(0,1,2);if(X?.format==="array")return[$,Z,Y,U];return`hsla(${$}, ${Z}%, ${Y}%, ${U})`}if(X?.format==="array")return[$,Z,Y];return`hsl(${$}, ${Z}%, ${Y}%)`}css(X){let $=X?.format??this.random.arrayElement(["hex","rgb","hsl"]);if($==="hex")return this.hex();if($==="rgb")return this.rgb();return this.hsl()}name(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);let X=["Red","Blue","Green","Yellow","Purple","Orange","Pink","Brown","Black","White","Gray","Cyan","Magenta","Lime","Navy","Teal","Olive","Maroon","Aqua","Silver","Fuchsia","Gold","Indigo","Violet"];return this.random.arrayElement(X)}hexColor(){return this.hex()}rgbColor(){return this.rgb()}rgbColorAsArray(){return this.rgb({format:"array"})}}class j${random;locale;constructor(X,$){this.random=X,this.locale=$}product(){let X=this.locale?.commerce?.productAdjective??["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable"],$=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],Z=this.locale?.commerce?.product??["Chair","Table","Lamp","Keyboard","Mouse","Computer","Shoes","Shirt","Pants","Hat","Gloves","Towel","Soap","Bike","Ball","Book","Wallet","Watch","Phone","Desk","Bottle","Plate","Cup","Bag","Pen","Notebook","Backpack","Sunglasses"];return`${this.random.arrayElement(X)} ${this.random.arrayElement($)} ${this.random.arrayElement(Z)}`}productName(){return this.product()}department(){if(this.locale?.commerce?.department)return this.random.arrayElement(this.locale.commerce.department);let X=["Books","Movies","Music","Games","Electronics","Computers","Home","Garden","Tools","Grocery","Health","Beauty","Toys","Kids","Baby","Clothing","Shoes","Jewelry","Sports","Outdoors","Automotive","Industrial"];return this.random.arrayElement(X)}price(X){let $=X?.min??1,Z=X?.max??1000,Y=X?.dec??2,U=X?.symbol??"",_=this.random.float($,Z,Y);return U+_.toFixed(Y)}productAdjective(){if(this.locale?.commerce?.productAdjective)return this.random.arrayElement(this.locale.commerce.productAdjective);let X=["Small","Ergonomic","Rustic","Intelligent","Gorgeous","Incredible","Fantastic","Practical","Sleek","Awesome","Generic","Handcrafted","Handmade","Licensed","Refined","Unbranded","Tasty","Premium","Luxury","Professional","Durable","Innovative","Compact","Versatile","Modern","Classic","Vintage","Contemporary"];return this.random.arrayElement(X)}productMaterial(){if(this.locale?.commerce?.productMaterial)return this.random.arrayElement(this.locale.commerce.productMaterial);let X=["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum","Bronze","Copper","Brass","Titanium","Ceramic","Velvet","Linen","Wool"];return this.random.arrayElement(X)}productDescription(){let X=["The beautiful range of {adjective} {material} {product} comes with a {feature}.","Experience the {adjective} {product} that redefines {benefit}.","Our {adjective} {material} {product} is designed for {benefit}.","Discover the {adjective} {product} with {feature} for {benefit}."],$=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],Z=["maximum comfort","everyday use","professional performance","home and office","outdoor adventures","creative projects","productivity","entertainment"];return this.random.arrayElement(X).replace("{adjective}",this.productAdjective().toLowerCase()).replace("{material}",this.productMaterial().toLowerCase()).replace("{product}","product").replace("{feature}",this.random.arrayElement($)).replace("{benefit}",this.random.arrayElement(Z))}review(){let X=["This product exceeded my expectations!","Absolutely love it! Worth every penny.","Great quality and fast shipping.","Not what I expected, but still decent.","Amazing! Highly recommend to everyone.","Perfect for my needs. Very satisfied.","Good value for the price.","Could be better, but it does the job.","Fantastic product! Will buy again.","Best purchase I've made this year!"];return this.random.arrayElement(X)}discountCode(){let X=["SAVE","GET","DEAL","OFFER","PROMO","SALE","DISCOUNT","SPECIAL"],$=this.random.int(10,99);return`${this.random.arrayElement(X)}${$}`}sku(){let X=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),$=this.random.int(1e4,99999),Z=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${X}-${$}-${Z}`}}class E${random;locale;constructor(X,$){this.random=X,this.locale=$}name(){let X=this.random.arrayElement(this.locale.company.name??["Company"]),$=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${X} ${$}`}suffix(){return this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"])}industry(){return this.random.arrayElement(this.locale.company.industry??["Technology"])}catchphrase(){let X=this.random.arrayElement(this.locale.company.adjective??["innovative"]),$=this.random.arrayElement(this.locale.company.descriptor??["digital"]),Z=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${X} ${$} ${Z}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let X=this.buzzword(),$=this.random.arrayElement(this.locale.company.descriptor??["digital"]),Z=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${X} ${$} ${Z}`}}class u8{random;constructor(X){this.random=X}engine(){let X=["MySQL","PostgreSQL","MongoDB","SQLite","Redis","Oracle","Microsoft SQL Server","MariaDB","Cassandra","Elasticsearch","DynamoDB","CouchDB","Neo4j","Firebase","Firestore","InfluxDB","TimescaleDB","RethinkDB","ArangoDB","CockroachDB"];return this.random.arrayElement(X)}type(){let X=["VARCHAR","INTEGER","BIGINT","SMALLINT","DECIMAL","NUMERIC","FLOAT","DOUBLE","BOOLEAN","DATE","TIME","TIMESTAMP","DATETIME","TEXT","BLOB","JSON","JSONB","UUID","ENUM","ARRAY","SERIAL","BIGSERIAL"];return this.random.arrayElement(X)}collation(){let X=["utf8_general_ci","utf8_unicode_ci","utf8mb4_general_ci","utf8mb4_unicode_ci","latin1_swedish_ci","latin1_general_ci","utf8_bin","utf8mb4_bin"];return this.random.arrayElement(X)}column(){let X=["id","user_id","name","email","password","created_at","updated_at","deleted_at","first_name","last_name","phone","address","city","state","country","zip_code","status","role","permissions","description","price","quantity","total","subtotal","tax","discount","shipping","notes","metadata","settings","preferences","avatar"];return this.random.arrayElement(X)}table(){let X=["users","posts","comments","products","orders","customers","invoices","payments","categories","tags","roles","permissions","sessions","settings","notifications","messages","attachments","logs","analytics","reports","subscriptions","transactions"];return this.random.arrayElement(X)}mongodbObjectId(){let X="";for(let $=0;$<24;$++)X+="0123456789abcdef"[this.random.int(0,15)];return X}constraint(){let X=["PRIMARY KEY","FOREIGN KEY","UNIQUE","NOT NULL","CHECK","DEFAULT","INDEX"];return this.random.arrayElement(X)}queryType(){let X=["SELECT","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","JOIN","LEFT JOIN","RIGHT JOIN","INNER JOIN","OUTER JOIN","UNION","WHERE"];return this.random.arrayElement(X)}connectionString(X){let $=X?.engine??this.engine().toLowerCase().replace(/ /g,""),Z="user",Y="password",U="localhost",_=this.random.int(3000,9999),Q=this.table(),L={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[$]||"jdbc";if($==="mongodb")return`${L}://user:password@localhost:${_}/${Q}`;return`${L}://user:password@localhost:${_}/${Q}`}}class n8{random;constructor(X){this.random=X}past(X){let $=X?.years??1,Z=X?.to??new Date,Y=X?.from??new Date(Z.getTime()-$*365*24*60*60*1000);return this.between({from:Y,to:Z})}future(X){let $=X?.years??1,Z=X?.from??new Date,Y=X?.to??new Date(Z.getTime()+$*365*24*60*60*1000);return this.between({from:Z,to:Y})}between(X){let $=X.from??new Date(Date.now()-31536000000),Z=X.to??new Date,Y=$.getTime(),U=Z.getTime(),_=this.random.int(Y,U);return new Date(_)}recent(X){let $=X?.days??1,Z=new Date,Y=new Date(Z.getTime()-$*24*60*60*1000);return this.between({from:Y,to:Z})}soon(X){let $=X?.days??1,Z=new Date,Y=new Date(Z.getTime()+$*24*60*60*1000);return this.between({from:Z,to:Y})}month(){let X=["January","February","March","April","May","June","July","August","September","October","November","December"];return this.random.arrayElement(X)}weekday(){let X=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];return this.random.arrayElement(X)}dateTime(){return this.between({from:new Date(1970,0,1),to:new Date})}dateTimeBetween(X){return this.between(X)}birthdate(X){let $=X?.mode??"age",Z=X?.refDate??new Date;if($==="year"){let z=X?.min??1900,j=X?.max??Z.getUTCFullYear(),E=new Date(Date.UTC(z,0,1)),V=new Date(Date.UTC(j,11,31,23,59,59,999));return this.between({from:E,to:V})}let Y=Math.max(0,X?.min??18),U=Math.max(Y,X?.max??80),_=(z)=>z*365.25*24*60*60*1000,Q=new Date(Z.getTime()-_(U)),L=new Date(Z.getTime()-_(Y));return this.between({from:Q,to:L})}}class i8{random;constructor(X){this.random=X}amount(X){let $=X?.min??0,Z=X?.max??1e4,Y=X?.dec??2,U=X?.symbol??"",_=this.random.float($,Z,Y);return U+_.toFixed(Y)}account(X=8){let $="";for(let Z=0;Z<X;Z++)$+=this.random.int(0,9);return $}accountName(){let X=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement(X)} Account`}routingNumber(){return this.account(9)}creditCardNumber(X){let $=X?.formatted??!0,Z=X?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),Y="",U=16;switch(Z){case"visa":Y="4",U=16;break;case"mastercard":Y=`5${this.random.int(1,5)}`,U=16;break;case"amex":Y=`3${this.random.arrayElement(["4","7"])}`,U=15;break;case"discover":Y="6011",U=16;break}let _=Y;while(_.length<U)_+=this.random.int(0,9);if($){if(Z==="amex")return`${_.slice(0,4)}-${_.slice(4,10)}-${_.slice(10)}`;return _.match(/.{1,4}/g)?.join("-")??_}return _}cvv(){return this.account(3)}iban(X){let $=X?.countryCode??"GB",Z=X?.formatted??!1,Y=this.random.int(10,99).toString(),U="WEST",_=this.account(14),Q=$+Y+"WEST"+_;if(Z)return Q.match(/.{1,4}/g)?.join(" ")??Q;return Q}bic(){let X="";for(let $=0;$<4;$++)X+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let $=0;$<2;$++)X+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let $=0;$<2;$++)X+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(Z,Y)=>Y.toString())]);return X}bitcoin(){let X=this.random.arrayElement(["1","3"]);for(let $=0;$<33;$++)X+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return X}ethereum(){let X="0x";for(let $=0;$<40;$++)X+="0123456789abcdef"[this.random.int(0,15)];return X}currencyCode(){let X=["USD","EUR","GBP","JPY","AUD","CAD","CHF","CNY","SEK","NZD","INR","BRL","RUB","KRW"];return this.random.arrayElement(X)}currencyName(){let X=["US Dollar","Euro","British Pound","Japanese Yen","Australian Dollar","Canadian Dollar","Swiss Franc","Chinese Yuan","Swedish Krona","New Zealand Dollar","Indian Rupee","Brazilian Real","Russian Ruble","South Korean Won"];return this.random.arrayElement(X)}currencySymbol(){let X=["$","\u20AC","\xA3","\xA5","\u20B9","R$","\u20BD","\u20A9","kr","CHF"];return this.random.arrayElement(X)}transactionType(){let X=["deposit","withdrawal","payment","invoice","transfer"];return this.random.arrayElement(X)}}class G${random;locale;constructor(X,$){this.random=X,this.locale=$}dish(){if(this.locale?.food?.dish)return this.random.arrayElement(this.locale.food.dish);let X=["Spaghetti Carbonara","Chicken Alfredo","Beef Tacos","Margherita Pizza","Caesar Salad","Pad Thai","Chicken Tikka Masala","Sushi Roll","Beef Burger","Fish and Chips","Ramen","Tom Yum Soup","Greek Salad","Lasagna","Paella","Pho","Falafel Wrap","Burrito Bowl","Chicken Curry","Steak Frites","Risotto","Poke Bowl","Bibimbap","Shakshuka","Eggs Benedict","Club Sandwich","Caprese Salad","Fettuccine Alfredo","Chicken Parmesan","Pulled Pork Sandwich","Gyro","Butter Chicken","Peking Duck"];return this.random.arrayElement(X)}ingredient(){if(this.locale?.food?.ingredient)return this.random.arrayElement(this.locale.food.ingredient);let X=["Garlic","Onion","Tomato","Basil","Oregano","Thyme","Rosemary","Cilantro","Parsley","Salt","Pepper","Olive Oil","Butter","Flour","Sugar","Eggs","Milk","Cheese","Chicken","Beef","Pork","Fish","Shrimp","Rice","Pasta","Potatoes","Carrots","Celery","Bell Pepper","Mushrooms","Spinach","Lettuce","Cucumber","Avocado","Lemon","Lime","Ginger","Soy Sauce","Vinegar","Honey","Cinnamon","Cumin"];return this.random.arrayElement(X)}spice(){if(this.locale?.food?.spice)return this.random.arrayElement(this.locale.food.spice);let X=["Basil","Oregano","Thyme","Rosemary","Sage","Cilantro","Parsley","Mint","Dill","Paprika","Cumin","Turmeric","Coriander","Cardamom","Cinnamon","Nutmeg","Cloves","Black Pepper","White Pepper","Cayenne","Chili Powder","Curry Powder","Garam Masala","Saffron","Vanilla","Bay Leaf","Fennel","Anise","Tarragon","Marjoram"];return this.random.arrayElement(X)}vegetable(){if(this.locale?.food?.vegetable)return this.random.arrayElement(this.locale.food.vegetable);let X=["Broccoli","Carrot","Celery","Lettuce","Spinach","Kale","Cabbage","Cauliflower","Brussels Sprouts","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Tomato","Cucumber","Bell Pepper","Zucchini","Eggplant","Mushroom","Onion","Garlic","Radish","Beet","Turnip","Artichoke","Bok Choy","Arugula","Swiss Chard"];return this.random.arrayElement(X)}fruit(){if(this.locale?.food?.fruit)return this.random.arrayElement(this.locale.food.fruit);let X=["Apple","Banana","Orange","Grape","Strawberry","Blueberry","Raspberry","Blackberry","Mango","Pineapple","Watermelon","Cantaloupe","Honeydew","Peach","Plum","Cherry","Pear","Kiwi","Papaya","Dragon Fruit","Lychee","Passion Fruit","Pomegranate","Coconut","Avocado","Lemon","Lime","Grapefruit","Apricot","Fig","Date"];return this.random.arrayElement(X)}meat(){if(this.locale?.food?.meat)return this.random.arrayElement(this.locale.food.meat);let X=["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Rabbit","Goat","Quail","Pheasant","Bacon","Sausage","Ham","Salami"];return this.random.arrayElement(X)}seafood(){let X=["Salmon","Tuna","Cod","Halibut","Trout","Mackerel","Sardines","Anchovies","Shrimp","Crab","Lobster","Scallops","Clams","Mussels","Oysters","Squid","Octopus","Tilapia","Sea Bass","Swordfish","Snapper","Grouper","Catfish"];return this.random.arrayElement(X)}dessert(){if(this.locale?.food?.dessert)return this.random.arrayElement(this.locale.food.dessert);let X=["Chocolate Cake","Cheesecake","Apple Pie","Ice Cream","Brownies","Cookies","Tiramisu","Cr\xE8me Br\xFBl\xE9e","Panna Cotta","Macarons","Cupcakes","Donuts","Eclairs","Profiteroles","Cannoli","Baklava","Flan","Churros","Gelato","Sorbet","Mousse","Tart","Cobbler","Pudding","Trifle","Souffl\xE9"];return this.random.arrayElement(X)}ethnicCategory(){if(this.locale?.food?.cuisine)return this.random.arrayElement(this.locale.food.cuisine);let X=["Italian","Chinese","Japanese","Mexican","Thai","Indian","French","Greek","Spanish","Korean","Vietnamese","Lebanese","Turkish","Brazilian","Moroccan","Ethiopian","Caribbean","Peruvian","German","American","British","Irish"];return this.random.arrayElement(X)}description(){let X=["Delicious","Savory","Sweet","Spicy","Tangy","Crispy","Tender","Juicy","Flavorful","Rich","Fresh","Aromatic","Creamy","Zesty","Hearty","Light"],$=["and flavorful","and satisfying","and aromatic","and authentic","and homemade","and traditional","and innovative","and exquisite","and mouthwatering"];return`${this.random.arrayElement(X)} ${this.random.arrayElement($)}`}}class l8{random;constructor(X){this.random=X}branch(){let X=["feature","bugfix","hotfix","refactor","chore","docs","test"],$=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],Z=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],Y=this.random.arrayElement(X),U=this.random.arrayElement($),_=this.random.arrayElement(Z);return`${Y}/${U}-${_}`}commitMessage(){let X=["feat","fix","docs","style","refactor","test","chore","perf"],$=["api","ui","auth","db","config","deps","core","utils"],Z=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],Y=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],U=this.random.arrayElement(X),_=this.random.boolean(0.5)?`(${this.random.arrayElement($)})`:"",Q=this.random.arrayElement(Z),L=this.random.arrayElement(Y);return`${U}${_}: ${Q} ${L}`}commitSha(X){let $=X?.short?7:40,Z="0123456789abcdef",Y="";for(let U=0;U<$;U++)Y+="0123456789abcdef"[this.random.int(0,15)];return Y}commitEntry(){let X=this.commitSha({short:!0}),$=this.commitMessage();return`${X} ${$}`}commitAuthor(X){let $=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],Z=X?.name??this.random.arrayElement($),Y=X?.email??`${Z.toLowerCase().replace(" ",".")}@example.com`;return`${Z} <${Y}>`}remote(X){let $=X?.protocol??this.random.arrayElement(["https","ssh"]),Z=X?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),Y=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),U=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),_={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if($==="ssh")return`git@${_[Z]}:${Y}/${U}.git`;return`https://${_[Z]}/${Y}/${U}.git`}tag(){let X=this.random.int(0,5),$=this.random.int(0,20),Z=this.random.int(0,50),Y=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${X}.${$}.${Z}${Y}`}}class F${random;locale;constructor(X,$){this.random=X,this.locale=$}abbreviation(){if(this.locale?.hacker?.abbreviation)return this.random.arrayElement(this.locale.hacker.abbreviation);let X=["TCP","HTTP","SDD","RAM","GB","CSS","SSL","AGP","SQL","CLI","IB","UX","UI","FTP","AI","ADP","RSS","XML","EXE","COM","HDD","THX","MP3","GPU","API","DNS","IP","LAN","WAN","VPN","SSH","HTTPS","JSON","REST","SOAP"];return this.random.arrayElement(X)}adjective(){if(this.locale?.hacker?.adjective)return this.random.arrayElement(this.locale.hacker.adjective);let X=["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","haptic","multi-byte","bluetooth","wireless","mobile","neural","optical","solid state","cloud","quantum","distributed","encrypted"];return this.random.arrayElement(X)}noun(){if(this.locale?.hacker?.noun)return this.random.arrayElement(this.locale.hacker.noun);let X=["driver","protocol","bandwidth","panel","microchip","program","port","card","array","interface","system","sensor","firewall","hard drive","pixel","alarm","feed","monitor","application","transmitter","bus","circuit","capacitor","matrix","server","database","network","router","switch","gateway","node","cluster"];return this.random.arrayElement(X)}verb(){if(this.locale?.hacker?.verb)return this.random.arrayElement(this.locale.hacker.verb);let X=["back up","bypass","hack","override","compress","copy","navigate","index","connect","generate","quantify","calculate","synthesize","input","transmit","program","reboot","parse","compile","encode","decode","encrypt","decrypt","patch","upgrade","deploy","configure","optimize","refactor","debug"];return this.random.arrayElement(X)}ingverb(){if(this.locale?.hacker?.ingverb)return this.random.arrayElement(this.locale.hacker.ingverb);let X=["backing up","bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","quantifying","calculating","synthesizing","transmitting","programming","parsing","compiling","encoding","decoding","encrypting","decrypting","patching","deploying","configuring","optimizing"];return this.random.arrayElement(X)}phrase(){if(this.locale?.hacker?.phrase)return this.random.arrayElement(this.locale.hacker.phrase);let X=["If we {verb} the {noun}, we can get to the {abbreviation} {noun} through the {adjective} {abbreviation} {noun}!","We need to {verb} the {adjective} {abbreviation} {noun}!","Try to {verb} the {abbreviation} {noun}, maybe it will {verb} the {adjective} {noun}!","You can't {verb} the {noun} without {ingverb} the {adjective} {abbreviation} {noun}!","Use the {adjective} {abbreviation} {noun}, then you can {verb} the {adjective} {noun}!","The {abbreviation} {noun} is down, {verb} the {adjective} {noun} so we can {verb} the {abbreviation} {noun}!","{ingverb} the {noun} won't do anything, we need to {verb} the {adjective} {abbreviation} {noun}!","I'll {verb} the {adjective} {abbreviation} {noun}, that should {verb} the {abbreviation} {noun}!"];return this.random.arrayElement(X).replace(/\{verb\}/g,()=>this.verb()).replace(/\{ingverb\}/g,()=>this.ingverb()).replace(/\{noun\}/g,()=>this.noun()).replace(/\{adjective\}/g,()=>this.adjective()).replace(/\{abbreviation\}/g,()=>this.abbreviation())}}class s8{random;constructor(X){this.random=X}randomElement(X){return this.random.arrayElement(X)}arrayElement(X){return this.random.arrayElement(X)}arrayElements(X,$){return this.random.arrayElements(X,$)}shuffle(X){return this.random.shuffle(X)}numerify(X){return X.replace(/#/g,()=>String(this.random.int(0,9)))}lexify(X){return X.replace(/\?/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split("")))}bothify(X){return this.numerify(this.lexify(X))}replaceSymbols(X){return this.random.replaceSymbols(X)}boolean(X=0.5){return this.random.boolean(X)}objectKey(X){let $=Object.keys(X);return this.random.arrayElement($)}objectValue(X){let $=this.objectKey(X);return X[$]}multiple(X,$=3){return Array.from({length:$},X)}maybe(X,$=0.5){return this.random.boolean($)?X():void 0}unique(X,$=50){let Z=new Set,Y=0;while(Y<$){let U=X();if(!Z.has(U))return Z.add(U),U;Y++}throw Error(`Failed to generate unique value after ${$} retries`)}replaceCreditCardSymbols(X="####-####-####-####",$="#"){return this.random.replaceCreditCardSymbols(X,$)}regexify(X){return X.replace(/\[A-Z\]/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/\[a-z\]/g,()=>this.random.arrayElement("abcdefghijklmnopqrstuvwxyz".split(""))).replace(/\[0-9\]/g,()=>String(this.random.int(0,9))).replace(/\{(\d+)\}/g,($,Z)=>{return""})}}class o8{random;constructor(X){this.random=X}url(X){let $=X?.width??640,Z=X?.height??480;return`https://via.placeholder.com/${$}x${Z}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr(X){let $=X?.width??640,Z=X?.height??480,Y=X?.category??"";if(Y)return`https://loremflickr.com/${$}/${Z}/${Y}`;return`https://loremflickr.com/${$}/${Z}`}urlPicsumPhotos(X){let $=X?.width??640,Z=X?.height??480,Y=`https://picsum.photos/${$}/${Z}`;if(X?.grayscale)Y+="?grayscale";if(X?.blur)Y+=X?.grayscale?`&blur=${X.blur}`:`?blur=${X.blur}`;return Y}dataUri(X){let $=X?.width??640,Z=X?.height??480,Y=X?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),U=`<svg xmlns="http://www.w3.org/2000/svg" width="${$}" height="${Z}"><rect width="${$}" height="${Z}" fill="#${Y}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(U)}`}githubAvatar(){return`https://avatars.githubusercontent.com/u/${this.random.int(1,1e5)}`}category(){let X=["abstract","animals","business","cats","city","food","nature","nightlife","fashion","people","sports","technics","transport","travel"];return this.random.arrayElement(X)}imageType(){let X=["jpg","jpeg","png","gif","svg","webp","bmp","tiff"];return this.random.arrayElement(X)}}class O${random;locale;domainWordsCache=null;constructor(X,$){this.random=X,this.locale=$}getDomainWords(){if(!this.domainWordsCache){let X=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=X.map(($)=>$.toLowerCase().replace(/[^a-z0-9]/g,"")).filter(($)=>$.length>0)}return this.domainWordsCache}email(X){let $;if(X?.firstName)$=X.firstName.toLowerCase();else{let Q=this.locale.person.firstNameMale.length,L=this.locale.person.firstNameFemale.length,z=this.locale.person.firstNameNeutral?.length||0,j=Q+L+z,E=this.random.int(0,j-1);if(E<Q)$=this.locale.person.firstNameMale[E].toLowerCase();else if(E<Q+L)$=this.locale.person.firstNameFemale[E-Q].toLowerCase();else $=this.locale.person.firstNameNeutral[E-Q-L].toLowerCase()}let Z=X?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=X?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),U=this.random.arrayElement(rU),_=this.random.arrayElement(this.getDomainWords());return`${$}${U}${Z}@${_}.${Y}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let X=this.locale.person.firstNameMale.length,$=this.locale.person.firstNameFemale.length,Z=this.locale.person.firstNameNeutral?.length||0,Y=X+$+Z,U=this.random.int(0,Y-1),_;if(U<X)_=this.locale.person.firstNameMale[U].toLowerCase();else if(U<X+$)_=this.locale.person.firstNameFemale[U-X].toLowerCase();else _=this.locale.person.firstNameNeutral[U-X-$].toLowerCase();let Q=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),L=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),z=[".","_",""],j=this.random.arrayElement(z);return`${_}${j}${Q}@${L}`}username(X){let $;if(X?.firstName)$=X.firstName.toLowerCase();else{let U=this.locale.person.firstNameMale.length,_=this.locale.person.firstNameFemale.length,Q=this.locale.person.firstNameNeutral?.length||0,L=U+_+Q,z=this.random.int(0,L-1);if(z<U)$=this.locale.person.firstNameMale[z].toLowerCase();else if(z<U+_)$=this.locale.person.firstNameFemale[z-U].toLowerCase();else $=this.locale.person.firstNameNeutral[z-U-_].toLowerCase()}let Z=X?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=[`${$}${Z}`,`${$}_${Z}`,`${$}.${Z}`,`${$}${this.random.int(10,999)}`,`${$}_${Z}${this.random.int(10,99)}`];return this.random.arrayElement(Y)}password(X){let $=X?.length??12,Z=X?.memorable??!1,Y=X?.prefix??"";if(Z){let Q=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],L=[];for(let z=0;z<3;z++)L.push(this.random.arrayElement(Q));return Y+L.join("-")+this.random.int(10,999)}let U="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",_=Y;for(let Q=Y.length;Q<$;Q++)_+=U[this.random.int(0,U.length-1)];return _}url(X){let $=X?.protocol??this.random.arrayElement(["http","https"]),Z=X?.domain??this.domainName();return`${$}://${Z}`}domainName(){return`${this.domainWord()}.${this.domainSuffix()}`}domainWord(){return this.random.arrayElement(this.getDomainWords())}domainSuffix(){return this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"])}ipv4(){return`${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}.${this.random.int(0,255)}`}ipv6(){let X=[];for(let $=0;$<8;$++)X.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return X.join(":")}mac(X=":"){let $=[];for(let Z=0;Z<6;Z++)$.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return $.join(X)}userAgent(){let X=["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/120.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 14.0; rv:109.0) Gecko/20100101 Firefox/120.0"];return this.random.arrayElement(X)}slug(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return $.join("-").toLowerCase()}ip(){return this.ipv4()}}class r8{random;constructor(X){this.random=X}word(){return this.random.arrayElement(aU)}words(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.word());return $.join(" ")}sentence(X){let $=X??this.random.int(3,10),Z=this.words($);return`${Z.charAt(0).toUpperCase()+Z.slice(1)}.`}sentences(X=3,$=" "){let Z=[];for(let Y=0;Y<X;Y++)Z.push(this.sentence());return Z.join($)}paragraph(X){let $=X??this.random.int(3,7);return this.sentences($)}paragraphs(X=3,$=`
395
456
 
396
- `){let X=[];for(let _=0;_<$;_++)X.push(this.paragraph());return X.join(Z)}text($){let Z=$??200,X="";while(X.length<Z)X+=`${this.paragraph()} `;return X.trim().slice(0,Z)}slug($=3){return this.words($).replace(/ /g,"-")}lines($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.sentence());return Z.join(`
397
- `)}}class c8{random;locale;constructor($,Z){this.random=$,this.locale=Z}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let $=["Rock","Pop","Jazz","Blues","Classical","Hip Hop","R&B","Country","Electronic","Dance","Metal","Punk","Reggae","Soul","Funk","Disco","House","Techno","Dubstep","Indie","Alternative","Folk","Gospel","Latin","K-Pop","EDM","Trap","Lo-Fi","Ambient","Ska"];return this.random.arrayElement($)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let $=["Dancing in the Moonlight","Bohemian Rhapsody","Stairway to Heaven","Hotel California","Imagine","Yesterday","Hey Jude","Sweet Child O' Mine","Smells Like Teen Spirit","Billie Jean","Thriller","Purple Rain","Born to Run","Like a Rolling Stone","What's Going On","Respect","Good Vibrations","Johnny B. Goode","I Want to Hold Your Hand","Satisfaction","My Generation","Brown Sugar","Layla","Crossroads","The End","Light My Fire","All Along the Watchtower","While My Guitar Gently Weeps","A Day in the Life"];return this.random.arrayElement($)}albumName(){let $=["Abbey Road","The Dark Side of the Moon","Thriller","Back in Black","The Wall","Rumours","Nevermind","Led Zeppelin IV","Born in the U.S.A.","Sgt. Pepper's Lonely Hearts Club Band","OK Computer","The Beatles (White Album)","Purple Rain","Hotel California","21","Appetite for Destruction","Lemonade","To Pimp a Butterfly","Random Access Memories"];return this.random.arrayElement($)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let $=["The Beatles","Led Zeppelin","Pink Floyd","Queen","The Rolling Stones","Elvis Presley","Michael Jackson","Madonna","David Bowie","Nirvana","Radiohead","U2","AC/DC","Metallica","Bob Dylan","Jimi Hendrix","Prince","Stevie Wonder","Aretha Franklin","The Who","The Doors","Fleetwood Mac","Eagles","Guns N' Roses","Red Hot Chili Peppers","Coldplay","Beyonc\xE9","Taylor Swift","Drake","Kendrick Lamar","Adele","Ed Sheeran"];return this.random.arrayElement($)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let $=["Guitar","Piano","Drums","Bass","Violin","Saxophone","Trumpet","Flute","Clarinet","Cello","Harp","Keyboard","Harmonica","Accordion","Ukulele","Banjo","Mandolin","Trombone","French Horn","Tuba","Oboe","Bassoon","Xylophone","Marimba","Tambourine","Synthesizer","Didgeridoo","Sitar","Tabla","Djembe"];return this.random.arrayElement($)}note(){let $=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement($)}chord(){let $=this.note(),Z=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${$}${Z}`}tempo(){return this.random.int(60,200)}key(){let $=this.note(),Z=this.random.arrayElement(["Major","Minor"]);return`${$} ${Z}`}timeSignature(){let $=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement($)}}class v${random;constructor($){this.random=$}int($){let Z=$?.min??0,X=$?.max??100;return this.random.int(Z,X)}float($){let Z=$?.min??0,X=$?.max??1,_=$?.precision??2;return this.random.float(Z,X,_)}bigInt($){let Z=$?.min??0n,X=($?.max??1000000n)-Z+1n,_=BigInt(Math.floor(this.random.number()*Number(X)));return Z+_}binary($){let Z=$?.length??8,X="";for(let _=0;_<Z;_++)X+=this.random.int(0,1);return X}octal($){let Z=$?.length??3,X="";for(let _=0;_<Z;_++)X+=this.random.int(0,7);return X}hex($){let Z=$?.length??6,X="0123456789ABCDEF",_="";for(let L=0;L<Z;L++)_+="0123456789ABCDEF"[this.random.int(0,15)];return _}randomNumber($){return this.int($)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class m8{random;locale;constructor($,Z){this.random=$,this.locale=Z}firstName($){if($?.gender==="male")return this.firstNameMale();if($?.gender==="female")return this.firstNameFemale();if($?.gender==="neutral")return this.firstNameNeutral();let Z=this.locale.person.firstNameMale.length,X=this.locale.person.firstNameFemale.length,_=this.locale.person.firstNameNeutral?.length||0,L=Z+X+_,j=this.random.int(0,L-1);if(j<Z)return this.locale.person.firstNameMale[j];if(j<Z+X)return this.locale.person.firstNameFemale[j-Z];return this.locale.person.firstNameNeutral[j-Z-X]}firstNameMale(){return this.random.arrayElement(this.locale.person.firstNameMale)}firstNameFemale(){return this.random.arrayElement(this.locale.person.firstNameFemale)}firstNameNeutral(){if(!this.locale.person.firstNameNeutral||this.locale.person.firstNameNeutral.length===0){let $=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement($)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName($){if(!$)return`${this.firstName()} ${this.lastName()}`;let Z=this.firstName({gender:$.gender}),X=this.lastName();if($.prefix&&$.suffix)return`${this.prefix()} ${Z} ${X} ${this.suffix()}`;if($.prefix)return`${this.prefix()} ${Z} ${X}`;if($.suffix)return`${Z} ${X} ${this.suffix()}`;return`${Z} ${X}`}prefix(){return this.random.arrayElement(this.locale.person.prefix)}suffix(){return this.random.arrayElement(this.locale.person.suffix)}gender(){return this.random.arrayElement(this.locale.person.gender)}jobTitle(){return this.random.arrayElement(this.locale.person.jobTitle)}name(){return this.fullName()}firstNameAdvanced($){let Z;if($?.constraints)Z=this.firstName({gender:$.constraints.gender});else Z=this.firstName({gender:$?.gender});if($?.weighted)Z=j1(this.random,$.weighted);if($?.relationships)Z=x9({firstName:Z,gender:$?.gender||$?.constraints?.gender},$.relationships).firstName||Z;if($?.validation){let X=L1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.firstName({gender:$?.gender||$?.constraints?.gender})}}return Z}fullNameAdvanced($){let Z;if($?.constraints)Z=this.fullName({gender:$.constraints.gender,prefix:$.prefix,suffix:$.suffix});else Z=this.fullName($);if($?.weighted)Z=j1(this.random,$.weighted);if($?.relationships)Z=x9({fullName:Z,gender:$?.gender||$?.constraints?.gender},$.relationships).fullName||Z;if($?.validation){let X=L1(Z,$.validation);if(!X.isValid){if($.validation.strict)throw Error(`Validation failed: ${X.errors.join(", ")}`);Z=this.fullName({gender:$?.gender||$?.constraints?.gender,prefix:$?.prefix,suffix:$?.suffix})}}return Z}profile($){let Z=$?.constraints?.gender||$?.gender||this.gender(),X=this.firstNameAdvanced({...$,gender:Z}),_=this.lastName(),L=`${X} ${_}`,j={firstName:X,lastName:_,fullName:L,gender:Z,jobTitle:this.jobTitle(),age:$?.constraints?.ageRange?this.random.int($.constraints.ageRange.min,$.constraints.ageRange.max):this.random.int(18,80)};if($?.relationships)return x9(j,$.relationships);return j}family($){let Z=$?.size||this.random.int(2,6),X=this.lastName(),_=["parent","parent","child","child","child","grandparent"],L=[];for(let j=0;j<Z;j++){let Y=_[j]||"relative",z=Y==="parent"||Y==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",F=this.firstNameAdvanced({...$,gender:z,constraints:{...$?.constraints,gender:z}});L.push({firstName:F,lastName:X,fullName:`${F} ${X}`,gender:z,relationship:Y})}return{members:L,lastName:X}}}class u8{random;locale;constructor($,Z){this.random=$,this.locale=Z}number($){let Z=$??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols(Z)}phoneNumber($){return this.number($)}}class n8{random;locale;constructor($,Z){this.random=$,this.locale=Z}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let $=["Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Argon","Potassium","Calcium","Iron","Copper","Zinc","Silver","Gold","Mercury","Lead","Uranium","Platinum","Titanium"];return this.random.arrayElement($)}chemicalElementSymbol(){let $=["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Fe","Cu","Zn","Ag","Au","Hg","Pb","U","Pt","Ti"];return this.random.arrayElement($)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let $=["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","coulomb","volt","ohm","farad","weber","tesla","henry","celsius","lumen","lux","becquerel","gray","sievert","katal","hertz","radian","steradian"];return this.random.arrayElement($)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let $=["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Magnetic Constant","Electric Constant","Fine Structure Constant","Rydberg Constant","Gas Constant","Stefan-Boltzmann Constant"];return this.random.arrayElement($)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let $=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement($)}dnaSequence($=12){let Z=["A","T","C","G"],X="";for(let _=0;_<$;_++)X+=this.random.arrayElement(Z);return X}rnaSequence($=12){let Z=["A","U","C","G"],X="";for(let _=0;_<$;_++)X+=this.random.arrayElement(Z);return X}hypothesis(){let $=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],Z=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement($)}, then ${this.random.arrayElement(Z)}`}}class i8{random;locale;constructor($,Z){this.random=$,this.locale=Z}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let $=["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding","Cycling","Running","Marathon","Triathlon","Gymnastics","Fencing","Archery","Martial Arts","Karate","Judo","Taekwondo","MMA","Formula 1","NASCAR","Sailing"];return this.random.arrayElement($)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let $=["Lakers","Warriors","Bulls","Celtics","Knicks","Heat","Spurs","Mavericks","Yankees","Red Sox","Dodgers","Cubs","Giants","Astros","Braves","Phillies","Patriots","49ers","Cowboys","Packers","Steelers","Eagles","Seahawks","Chiefs","Manchester United","Real Madrid","Barcelona","Liverpool","Bayern Munich","PSG","Maple Leafs","Bruins","Canadiens","Blackhawks","Penguins","Lightning"];return this.random.arrayElement($)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let $=["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Pel\xE9","Cristiano Ronaldo","Lionel Messi","Roger Federer","Usain Bolt","Simone Biles","Michael Phelps","Kobe Bryant","Derek Jeter","Joe Montana","Magic Johnson","Larry Bird"];return this.random.arrayElement($)}position(){let $=["Quarterback","Running Back","Wide Receiver","Linebacker","Defensive Back","Point Guard","Shooting Guard","Small Forward","Power Forward","Center","Pitcher","Catcher","First Base","Shortstop","Outfielder","Forward","Midfielder","Defender","Goalkeeper","Striker","Winger"];return this.random.arrayElement($)}event(){let $=["Super Bowl","World Series","NBA Finals","Stanley Cup","FIFA World Cup","Olympics","Wimbledon","Masters Tournament","Kentucky Derby","Indianapolis 500","Tour de France","Boston Marathon","UEFA Champions League","World Cup","The Open Championship","US Open","French Open","Australian Open"];return this.random.arrayElement($)}league(){let $=["NFL","NBA","MLB","NHL","MLS","Premier League","La Liga","Serie A","Bundesliga","Ligue 1","UEFA","FIFA","NCAA","PGA","ATP","WTA","F1","NASCAR","IndyCar"];return this.random.arrayElement($)}quote(){let $=["Just do it!","Winners never quit and quitters never win.","Hard work beats talent when talent doesn't work hard.","The only way to prove you're a good sport is to lose.","Champions keep playing until they get it right.","It's not whether you get knocked down, it's whether you get up.","You miss 100% of the shots you don't take.","The difference between the impossible and the possible lies in determination."];return this.random.arrayElement($)}equipment(){let $=["Ball","Bat","Glove","Helmet","Racket","Puck","Skates","Cleats","Pads","Jersey","Goggles","Swimsuit","Bicycle","Surfboard","Skateboard","Snowboard","Skis","Golf Clubs","Tennis Racket","Boxing Gloves","Mouthguard"];return this.random.arrayElement($)}}class b${random;constructor($){this.random=$}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let $="0123456789abcdef",Z="";for(let X=0;X<36;X++)if(X===8||X===13||X===18||X===23)Z+="-";else if(X===14)Z+="4";else if(X===19){let _=this.random.int(0,15);Z+=$[_&3|8]}else Z+=$[this.random.int(0,15)];return Z}nanoid($=21){let Z="";for(let X=0;X<$;X++)Z+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return Z}alpha($){let Z=$?.length??10,X=$?.casing??"mixed",_="abcdefghijklmnopqrstuvwxyz",L="ABCDEFGHIJKLMNOPQRSTUVWXYZ",j="";if(X==="lower")j="abcdefghijklmnopqrstuvwxyz";else if(X==="upper")j="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else j="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let Y="";for(let z=0;z<Z;z++)Y+=j[this.random.int(0,j.length-1)];return Y}alphanumeric($){let Z=$?.length??10,X=$?.casing??"mixed",_="abcdefghijklmnopqrstuvwxyz",L="ABCDEFGHIJKLMNOPQRSTUVWXYZ",j="0123456789",Y="0123456789";if(X==="lower")Y+="abcdefghijklmnopqrstuvwxyz";else if(X==="upper")Y+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else Y+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let z="";for(let F=0;F<Z;F++)z+=Y[this.random.int(0,Y.length-1)];return z}numeric($=10){if(!this.random.isSeeded()){let X="";for(let _=0;_<$;_++)X+=Math.floor(Math.random()*10);return X}let Z="";for(let X=0;X<$;X++)Z+=this.random.int(0,9);return Z}sample($=10){return this.alphanumeric({length:$})}symbol($=5){let Z="";for(let X=0;X<$;X++)Z+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return Z}hexadecimal($){let Z=$?.length??6,X=$?.prefix??"",_="0123456789abcdef",L=X;for(let j=0;j<Z;j++)L+="0123456789abcdef"[this.random.int(0,15)];return L}}class l8{random;locale;constructor($,Z){this.random=$,this.locale=Z}fileName($){let Z;if(this.locale?.system?.fileName)Z=this.locale.system.fileName;else Z=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let X=this.random.arrayElement(Z),_=$?.extension??this.fileExtension();return`${X}.${_}`}fileExtension(){let $=["pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","json","xml","jpg","jpeg","png","gif","bmp","svg","webp","ico","mp3","wav","ogg","flac","aac","m4a","mp4","avi","mov","wmv","flv","webm","mkv","zip","rar","tar","gz","7z","bz2","html","css","js","ts","jsx","tsx","vue","py","java","cpp","c","go","rs"];return this.random.arrayElement($)}commonFileName(){let $=["README.md","package.json","tsconfig.json",".gitignore",".env","docker-compose.yml","Dockerfile","index.html","index.js","app.js","main.py","requirements.txt","Makefile","LICENSE","CHANGELOG.md","yarn.lock","package-lock.json","pom.xml"];return this.random.arrayElement($)}mimeType(){let $=["application/json","application/xml","application/pdf","application/zip","text/html","text/css","text/javascript","text/plain","text/csv","image/jpeg","image/png","image/gif","image/svg+xml","image/webp","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg","video/avi","application/octet-stream","multipart/form-data","application/x-www-form-urlencoded"];return this.random.arrayElement($)}commonMimeType(){let $=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement($)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let $=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement($)}directoryPath(){let $=["/usr/local/bin","/usr/bin","/etc","/var/log","/tmp","/home","/root","/opt","/srv","/mnt","/media","/dev","/proc","/sys","C:\\Program Files","C:\\Users","C:\\Windows","C:\\Temp","/Applications","/Library","/System","/Users","/Documents","/Downloads"];return this.random.arrayElement($)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let $=this.random.int(0,10),Z=this.random.int(0,20),X=this.random.int(0,50);return`${$}.${Z}.${X}`}networkInterface(){let $=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement($)}cron(){let $=this.random.boolean(0.5)?"*":this.random.int(0,59),Z=this.random.boolean(0.5)?"*":this.random.int(0,23),X=this.random.boolean(0.5)?"*":this.random.int(1,31),_=this.random.boolean(0.5)?"*":this.random.int(1,12),L=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${$} ${Z} ${X} ${_} ${L}`}}class s8{random;locale;constructor($,Z){this.random=$,this.locale=Z}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(SX)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(MX)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(RX)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(JX)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(CX)}vin(){let $="";for(let Z=0;Z<17;Z++)$+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return $}registration(){let $=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement($).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let $=this.random.int(2000,2024),Z=this.manufacturer(),X=this.model();return`${$} ${Z} ${X}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let $=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement($)}}class o8{random;locale;constructor($,Z){this.random=$,this.locale=Z}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let $=["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold","warm","cool","bright","dark","loud","quiet","strong","weak","clean","dirty","new","old","young","fresh","dry","wet","smooth","rough","sharp","dull","simple","complex","easy","difficult","good","bad","right","wrong","true","false"];return this.random.arrayElement($)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let $=["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well","almost","always","never","often","rarely","sometimes","usually","frequently","occasionally","immediately","instantly","eventually","probably","possibly"];return this.random.arrayElement($)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let $=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement($)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let $=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement($)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let $=["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","air","fire","earth","mountain","river","ocean","sky","sun","moon","star","cloud","rain","snow","person","man","woman","child","friend","family","food","music","art","book","school","work","time","day","night","morning","evening","world","life","love"];return this.random.arrayElement($)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let $=["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through","during","before","after","against","among","into","onto","upon","within","without","toward","near","beside","behind"];return this.random.arrayElement($)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let $=["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","look","see","hear","think","know","want","like","love","hate","need","make","take","give","get","put","come","go","say","tell","ask","answer","help","start","stop","begin","end","open","close","show","hide","find","lose","buy","sell","learn"];return this.random.arrayElement($)}sample(){let $=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],Z=this.random.arrayElement($);return this[Z]()}words($=3){let Z=[];for(let X=0;X<$;X++)Z.push(this.sample());return Z.join(" ")}}class f${seed;constructor($){this.seed=$}isSeeded(){return this.seed!==void 0}number(){if(this.seed!==void 0)return this.seed=(this.seed*9301+49297)%233280,this.seed/233280;return Math.random()}int($=0,Z=100){return Math.floor(this.number()*(Z-$+1))+$}float($=0,Z=1,X=2){let _=this.number()*(Z-$)+$;return Number.parseFloat(_.toFixed(X))}arrayElement($){if($.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return $[Math.floor(Math.random()*$.length)];return $[this.int(0,$.length-1)]}arrayElements($,Z){if($.length===0)return[];let X=Z??this.int(1,$.length);return[...$].sort(()=>this.number()-0.5).slice(0,Math.min(X,$.length))}shuffle($){let Z=[...$];for(let X=Z.length-1;X>0;X--){let _=this.int(0,X);[Z[X],Z[_]]=[Z[_],Z[X]]}return Z}boolean($=0.5){return this.number()<$}replaceSymbols($){if(this.seed===void 0){let Z="";for(let X=0;X<$.length;X++){let _=$[X];if(_==="#")Z+="0123456789"[Math.floor(Math.random()*10)];else if(_==="?")Z+=EZ[Math.floor(Math.random()*26)];else Z+=_}return Z}return $.replace(/[#?]/g,(Z)=>{if(Z==="#")return String(this.int(0,9));return this.arrayElement(EZ)})}replaceCreditCardSymbols($="####-####-####-####",Z="#"){return $.replace(new RegExp(Z,"g"),()=>String(this.int(0,9)))}weightedArrayElement($){if($.length===0)throw Error("Cannot pick from empty weighted items array");let Z=$.reduce((L,j)=>L+j.weight,0);if(Z<=0)throw Error("Total weight must be greater than 0");let X=this.number()*Z,_=0;for(let L of $)if(_+=L.weight,X<=_)return L.item;return $[$.length-1].item}weightedArrayElements($,Z,X=!1){if($.length===0)return[];let _=Z??this.int(1,$.length),L=[],j=[...$];for(let Y=0;Y<_&&j.length>0;Y++){let z=this.weightedArrayElement(j);if(L.push(z),!X){let F=j.findIndex((E)=>E.item===z);if(F!==-1)j.splice(F,1)}}return L}weightedBoolean($=0.5){return this.number()<$}weightedInt($,Z,X){let _=Z-$+1;if(X){if(X.length!==_)throw Error("Weights array length must match the range size");let L=X.map((j,Y)=>({item:$+Y,weight:j}));return this.weightedArrayElement(L)}return this.int($,Z)}}class o${random;_locale;_autoInstallLocales;person;address;internet;phone;company;lorem;date;number;string;color;finance;helpers;vehicle;image;git;science;music;database;food;commerce;book;animal;sport;hacker;system;word;constructor($){let Z=$?.locale??"en",X=$?.seed;if(this._autoInstallLocales=$?.autoInstallLocales??!1,Z!=="en"&&!n0.isCached(Z))console.warn(`[ts-mocker] Locale '${Z}' requires async loading. Use 'await Faker.create({ locale: "${Z}" })' for better performance. Falling back to English.`),this._locale=n0.loadSync("en");else this._locale=n0.loadSync(Z);this.random=new f$(X),this.person=new m8(this.random,this._locale),this.address=new h8(this.random,this._locale),this.internet=new d8(this.random,this._locale),this.phone=new u8(this.random,this._locale),this.company=new f8(this.random,this._locale),this.lorem=new A$(this.random),this.date=new k$(this.random),this.number=new v$(this.random),this.string=new b$(this.random),this.color=new v8(this.random,this._locale),this.finance=new x$(this.random),this.helpers=new h$(this.random),this.image=new y$(this.random),this.git=new B$(this.random),this.science=new n8(this.random,this._locale),this.music=new c8(this.random,this._locale),this.database=new T$(this.random),this.food=new g8(this.random,this._locale),this.commerce=new b8(this.random,this._locale),this.book=new A8(this.random,this._locale),this.animal=new y8(this.random,this._locale),this.sport=new i8(this.random,this._locale),this.hacker=new p8(this.random,this._locale),this.system=new l8(this.random,this._locale),this.word=new o8(this.random,this._locale),this.vehicle=new s8(this.random,this._locale)}static async create($){let Z=$?.locale??"en";return await n0.load(Z),new o$($)}seed($){return this.random=new f$($),Object.assign(this.person,new m8(this.random,this._locale)),Object.assign(this.address,new h8(this.random,this._locale)),Object.assign(this.internet,new d8(this.random,this._locale)),Object.assign(this.phone,new u8(this.random,this._locale)),Object.assign(this.company,new f8(this.random,this._locale)),Object.assign(this.lorem,new A$(this.random)),Object.assign(this.date,new k$(this.random)),Object.assign(this.number,new v$(this.random)),Object.assign(this.string,new b$(this.random)),Object.assign(this.color,new v8(this.random,this._locale)),Object.assign(this.finance,new x$(this.random)),Object.assign(this.helpers,new h$(this.random)),Object.assign(this.image,new y$(this.random)),Object.assign(this.git,new B$(this.random)),Object.assign(this.science,new n8(this.random,this._locale)),Object.assign(this.music,new c8(this.random,this._locale)),Object.assign(this.database,new T$(this.random)),Object.assign(this.food,new g8(this.random,this._locale)),Object.assign(this.commerce,new b8(this.random,this._locale)),Object.assign(this.book,new A8(this.random,this._locale)),Object.assign(this.animal,new y8(this.random,this._locale)),Object.assign(this.sport,new i8(this.random,this._locale)),Object.assign(this.hacker,new p8(this.random,this._locale)),Object.assign(this.system,new l8(this.random,this._locale)),Object.assign(this.word,new o8(this.random,this._locale)),Object.assign(this.vehicle,new s8(this.random,this._locale)),this}async setLocale($){return this._locale=await n0.load($),this.reinitializeLocaleModules(),this}setLocaleSync($){if(!n0.isCached($)&&$!=="en")return console.warn(`[ts-mocker] Locale '${$}' is not loaded. Use 'await faker.setLocale("${$}")' or preload it first.`),this;return this._locale=n0.loadSync($),this.reinitializeLocaleModules(),this}async preloadLocales($){return await n0.preload($),this}reinitializeLocaleModules(){Object.assign(this.person,new m8(this.random,this._locale)),Object.assign(this.address,new h8(this.random,this._locale)),Object.assign(this.internet,new d8(this.random,this._locale)),Object.assign(this.phone,new u8(this.random,this._locale)),Object.assign(this.company,new f8(this.random,this._locale)),Object.assign(this.food,new g8(this.random,this._locale)),Object.assign(this.animal,new y8(this.random,this._locale)),Object.assign(this.sport,new i8(this.random,this._locale)),Object.assign(this.music,new c8(this.random,this._locale)),Object.assign(this.commerce,new b8(this.random,this._locale)),Object.assign(this.book,new A8(this.random,this._locale)),Object.assign(this.vehicle,new s8(this.random,this._locale)),Object.assign(this.word,new o8(this.random,this._locale)),Object.assign(this.hacker,new p8(this.random,this._locale)),Object.assign(this.system,new l8(this.random,this._locale)),Object.assign(this.color,new v8(this.random,this._locale)),Object.assign(this.science,new n8(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return n0.getAvailableLocales()}static isLocaleLoaded($){return n0.isCached($)}static async preloadLocales($){await n0.preload($)}name(){return this.person.name()}email(){return this.internet.email()}}var Y1,r$,aY,eY,S7,$$,YZ,B0,Q0,$F,M7,ZF,R7,XF,_F,b5,LF,J7,C7,f5,jF,YF,FF,zF,Z$,EX,UF,y0,EF,OF,w7,X$,FZ,N0,L0,QF,q7,VF,H7,GF,KF,g5,IF,N7,P7,WF,p5,DF,SF,MF,RF,JF,_$,OX,CF,X9,T7,g$,k7,x7,zZ,B7,h7,p$,y7,A7,g9,QX,j9,L$,wF,qF,d$,d5=null,UZ,R8,s0,Y8,n0,VX,GX,KX,IX,WX,DX,SX,MX,RX,JX,CX,EZ,OZ,wX,HF=n(async()=>{Y1=new t2,r$=new a2,aY=w$(LZ.cwd(),"config"),eY=w$(LZ.cwd(),"src/generated"),S7=C$.env.CLARITY_LOG_DIR||UY(BY(),"logs"),$$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:S7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},YZ=await hY(),B0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},Q0=B0,$F=B0.red,M7=B0.green,ZF=B0.yellow,R7=B0.blue,XF=B0.magenta,_F=B0.cyan,b5=B0.white,LF=B0.gray,J7=B0.bgRed,C7=B0.bgYellow,f5=B0.bold,jF=B0.dim,YF=B0.italic,FF=B0.underline,zF=B0.reset,Z$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EX={debug:"\uD83D\uDD0D",info:R7("\u2139"),success:M7("\u2713"),warning:C7(b5(f5(" WARN "))),error:J7(b5(f5(" ERROR ")))},UF=new H$("stacks"),y0=new H$("bunfig",{showTags:!0}),EF=p0(_1.cwd(),"config"),OF=p0(_1.cwd(),"src/generated"),w7=J$.env.CLARITY_LOG_DIR||FY(bY(),"logs"),X$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:w7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},FZ=await fY(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},L0=N0,QF=N0.red,q7=N0.green,VF=N0.yellow,H7=N0.blue,GF=N0.magenta,KF=N0.cyan,g5=N0.white,IF=N0.gray,N7=N0.bgRed,P7=N0.bgYellow,WF=N0.bgGray,p5=N0.bold,DF=N0.dim,SF=N0.italic,MF=N0.underline,RF=N0.strikethrough,JF=N0.reset,_$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},OX={debug:"\uD83D\uDD0D",info:H7("\u2139"),success:q7("\u2713"),warning:P7(g5(p5(" WARN "))),error:N7(g5(p5(" ERROR ")))},CF=new P$("stacks"),X9=class extends Error{timestamp;context;constructor(Z,X={}){super(Z);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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(([X,_])=>`${X}: ${_}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Z}`}},T7=class extends X9{code="CONFIG_NOT_FOUND";constructor(Z,X,_){let L=_?` or alias "${_}"`:"";super(`Configuration "${Z}"${L} not found`,{configName:Z,alias:_,searchPaths:X,searchPathCount:X.length})}},g$=class extends X9{code="CONFIG_LOAD_ERROR";constructor(Z,X,_){super(`Failed to load configuration from "${Z}": ${X.message}`,{configPath:Z,configName:_,originalError:X.name,originalMessage:X.message});this.cause=X}},k7=class extends X9{code="CONFIG_VALIDATION_ERROR";constructor(Z,X,_){super(`Configuration validation failed for "${Z}"`,{configPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},x7=class extends X9{code="CONFIG_MERGE_ERROR";constructor(Z,X,_,L){super(`Failed to merge configuration from "${Z}" with "${X}": ${_.message}`,{sourcePath:Z,targetPath:X,configName:L,originalError:_.name,originalMessage:_.message});this.cause=_}},zZ=class extends X9{code="ENV_VAR_ERROR";constructor(Z,X,_,L){super(`Failed to parse environment variable "${Z}" with value "${X}" as ${_}`,{envKey:Z,envValue:X,expectedType:_,configName:L})}},B7=class extends X9{code="FILE_SYSTEM_ERROR";constructor(Z,X,_){super(`File system ${Z} failed for "${X}": ${_.message}`,{operation:Z,path:X,originalError:_.name,originalMessage:_.message});this.cause=_}},h7=class extends X9{code="TYPE_GENERATION_ERROR";constructor(Z,X,_){super(`Failed to generate types from "${Z}" to "${X}": ${_.message}`,{configDir:Z,outputPath:X,originalError:_.name,originalMessage:_.message});this.cause=_}},p$=class extends X9{code="SCHEMA_VALIDATION_ERROR";constructor(Z,X,_){super(`Schema validation failed${_?` for config "${_}"`:""}`,{schemaPath:Z,configName:_,validationErrors:X,errorCount:X.length})}},y7=class extends X9{code="BROWSER_CONFIG_ERROR";constructor(Z,X,_,L){super(`Failed to fetch configuration from "${Z}": ${X} ${_}`,{endpoint:Z,status:X,statusText:_,configName:L})}},A7=class extends X9{code="PLUGIN_ERROR";constructor(Z,X,_){super(`Plugin "${Z}" failed during ${X}: ${_.message}`,{pluginName:Z,operation:X,originalError:_.name,originalMessage:_.message});this.cause=_}},g9={configNotFound($,Z,X){return new T7($,Z,X)},configLoad($,Z,X){return new g$($,Z,X)},configValidation($,Z,X){return new k7($,Z,X)},configMerge($,Z,X,_){return new x7($,Z,X,_)},envVar($,Z,X,_){return new zZ($,Z,X,_)},fileSystem($,Z,X){return new B7($,Z,X)},typeGeneration($,Z,X){return new h7($,Z,X)},schemaValidation($,Z,X){return new p$($,Z,X)},browserConfig($,Z,X,_){return new y7($,Z,X,_)},plugin($,Z,X){return new A7($,Z,X)}},QX=/^https?:\/\//,j9=new P$("bunfig",{showTags:!0}),L$=new YX,wF=r0(R$.cwd(),"config"),qF=r0(R$.cwd(),"src/generated"),d$={verbose:!1,locale:"en",autoInstallLocales:!1},UZ=d$,R8={title:"English",person:{firstNameMale:["James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Mark","Donald","Steven","Paul","Andrew","Joshua","Kenneth","Kevin","Brian","George","Timothy","Ronald","Edward","Jason","Jeffrey","Ryan","Jacob","Gary","Nicholas","Eric","Jonathan","Stephen","Larry","Justin","Scott","Brandon","Benjamin","Samuel","Raymond","Gregory","Frank","Alexander","Patrick","Jack","Dennis","Jerry","Liam","Noah","Oliver","Elijah","Lucas","Mason","Logan","Ethan","Henry","Jackson","Sebastian","Aiden","Carter","Owen","Wyatt","Luke","Jayden","Dylan","Grayson","Levi","Isaac","Gabriel","Julian","Mateo","Jaxon","Lincoln"],firstNameFemale:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen","Lisa","Nancy","Betty","Margaret","Sandra","Ashley","Kimberly","Emily","Donna","Michelle","Dorothy","Carol","Amanda","Melissa","Deborah","Stephanie","Rebecca","Sharon","Laura","Cynthia","Kathleen","Amy","Angela","Shirley","Anna","Brenda","Pamela","Emma","Nicole","Helen","Olivia","Ava","Isabella","Sophia","Mia","Charlotte","Amelia","Harper","Evelyn","Abigail","Sofia","Ella","Scarlett","Grace","Chloe","Victoria","Aria","Lily","Aubrey","Zoey","Penelope","Lillian","Addison","Layla","Natalie","Camila"],firstNameNeutral:["Taylor","Jordan","Alex","Riley","Casey","Morgan","Avery","Quinn","Blake","Cameron","Sage","River","Phoenix","Rowan","Skyler","Charlie","Finley","Peyton","Reese","Kai"],lastName:["Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Rodriguez","Martinez","Hernandez","Lopez","Gonzalez","Wilson","Anderson","Thomas","Taylor","Moore","Jackson","Martin","Lee","Perez","Thompson","White","Harris","Sanchez","Clark","Ramirez","Lewis","Robinson","Walker","Young","Allen","King","Wright","Scott","Torres","Nguyen","Hill","Flores","Green","Adams","Nelson","Baker","Hall","Rivera","Campbell","Mitchell","Carter","Roberts","Gomez","Phillips","Evans","Turner","Diaz","Parker","Cruz","Edwards","Collins","Reyes","Stewart","Morris","Morales","Murphy","Cook","Rogers","Gutierrez","Ortiz","Morgan","Cooper","Peterson","Bailey","Reed","Kelly","Howard","Ramos","Kim","Cox","Ward","Richardson","Watson","Brooks","Chavez","Wood","James","Bennett","Gray","Mendoza","Ruiz","Hughes","Price","Alvarez","Castillo","Sanders","Patel","Myers","Long","Ross","Foster","Jimenez"],prefix:["Mr.","Mrs.","Ms.","Miss","Dr.","Prof."],suffix:["Jr.","Sr.","I","II","III","IV","V","MD","PhD","DDS"],gender:["Male","Female","Non-binary","Agender","Bigender","Genderfluid","Genderqueer"],jobTitle:["Software Engineer","Product Manager","Designer","Data Scientist","DevOps Engineer","Marketing Manager","Sales Representative","Accountant","Human Resources Manager","CEO","CTO","CFO","COO","Director","Manager","Analyst","Consultant","Administrator","Coordinator","Specialist","Developer","Architect","Engineer","Technician","Assistant","Project Manager","Business Analyst","Quality Assurance Engineer","UX Designer","UI Designer","Backend Developer","Frontend Developer","Full Stack Developer","Mobile Developer","Cloud Architect","Security Engineer","Network Engineer","Database Administrator","Systems Administrator","Technical Writer","Scrum Master","Product Owner","Release Manager","Content Manager","Social Media Manager","SEO Specialist","Digital Marketing Specialist","Growth Hacker","Brand Manager","Creative Director","Financial Analyst","Investment Banker","Risk Analyst","Compliance Officer","Tax Consultant","Legal Counsel","Paralegal","Executive Assistant","Operations Manager","Supply Chain Manager","Logistics Coordinator","Customer Success Manager","Account Executive","Sales Engineer","Technical Support"]},address:{street:["Main","Oak","Maple","Cedar","Elm","Washington","Lake","Hill","Park","River","Sunset","Pine","Walnut","Highland","Madison","Lincoln","Jackson","Franklin"],city:["New York","Los Angeles","Chicago","Playa Vista","Houston","Phoenix","Philadelphia","San Antonio","San Diego","Dallas","San Jose","Austin","Jacksonville","Fort Worth","Columbus","Charlotte","San Francisco","Indianapolis","Seattle","Denver","Boston","Nashville","Detroit","Memphis","Portland","Oklahoma City","Las Vegas","Louisville","Baltimore","Milwaukee","Albuquerque","Tucson","Fresno","Sacramento","Mesa","Kansas City","Atlanta","Long Beach","Colorado Springs","Raleigh","Miami","Virginia Beach","Omaha","Oakland","Minneapolis","Tulsa","Arlington","Tampa","New Orleans","Wichita","Cleveland","Bakersfield","Aurora","Anaheim","Honolulu","Santa Ana","Riverside","Corpus Christi","Lexington","Stockton","Henderson","Saint Paul","Cincinnati","Pittsburgh","Greensboro","Anchorage","Plano","Lincoln","Orlando","Irvine","Newark","Durham","Chula Vista","Toledo","Fort Wayne","St. Petersburg","Laredo","Jersey City"],state:["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],stateAbbr:["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],country:["United States","Canada","United Kingdom","Australia","Germany","France","Spain","Italy","Japan","China","India","Brazil","Mexico","Russia","South Korea"],countryCode:["US","CA","GB","AU","DE","FR","ES","IT","JP","CN","IN","BR","MX","RU","KR"],zipCode:["#####","#####-####"],buildingNumber:["###","####","#","##"],direction:["North","East","South","West","Northeast","Northwest","Southeast","Southwest"],streetSuffix:["Street","Avenue","Road","Boulevard","Drive","Court","Circle","Lane","Way","Place","Terrace","Parkway","Commons","Trail","Square","Run","Crossing"]},company:{name:["TechCorp","GlobalSoft","DataSystems","CloudNet","Innovate Inc","Digital Solutions","NextGen Tech","FutureTech","SmartSystems","CoreTech","PrimeSoft","AlphaTech"],suffix:["Inc","LLC","Corp","Group","Ltd","Co","Technologies","Solutions","Systems"],industry:["Technology","Finance","Healthcare","Education","Retail","Manufacturing","Telecommunications","Energy","Real Estate","Transportation","Media","Hospitality"],buzzwords:["synergize","leverage","innovate","disrupt","optimize","streamline","transform","revolutionize","empower","enable","facilitate","orchestrate","integrate"],adjective:["revolutionary","cutting-edge","innovative","next-generation","advanced","leading","premier","world-class","enterprise","scalable","robust","seamless"],descriptor:["global","digital","cloud-based","AI-powered","data-driven","user-centric","agile","secure","efficient","intelligent","automated","integrated"],noun:["solution","platform","system","service","technology","framework","infrastructure","application","network","portal","ecosystem","architecture","engine"]},internet:{domainSuffix:["com","net","org","io","co","app","dev","tech","ai","cloud"],freeEmail:["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","proton.me"]},phone:{formats:["###-###-####","(###) ###-####","1-###-###-####","+1-###-###-####","###.###.####"]},food:{dish:["Hamburger","Cheeseburger","Pizza","Hot Dog","Fried Chicken","BBQ Ribs","Mac and Cheese","Grilled Cheese","BLT Sandwich","Caesar Salad","Cobb Salad","Chicken Wings","Nachos","Tacos","Burrito","Quesadilla","Fish and Chips","Clam Chowder","Lobster Roll","Cheesesteak","Pulled Pork Sandwich","Buffalo Wings","Meatloaf","Pot Roast","Fried Catfish","Jambalaya","Gumbo","Po' Boy","Corn Dog","Chili","Baked Beans","Cornbread","Biscuits and Gravy"],ingredient:["Flour","Sugar","Salt","Pepper","Butter","Eggs","Milk","Cheese","Tomato","Onion","Garlic","Olive Oil","Chicken","Beef","Pork","Fish","Rice","Pasta","Bread","Potato","Carrot","Celery","Bell Pepper","Mushroom","Spinach","Broccoli","Lettuce","Avocado","Lemon","Lime","Basil","Oregano","Thyme","Rosemary","Parsley","Cilantro"],cuisine:["American","Italian","Mexican","Chinese","Japanese","Thai","Indian","French","Greek","Spanish","Mediterranean","Vietnamese","Korean","Turkish","Lebanese","Brazilian","Argentinian","Peruvian","Caribbean","Moroccan","Ethiopian"],dessert:["Apple Pie","Chocolate Cake","Ice Cream","Brownies","Cookies","Cheesecake","Donuts","Cupcakes","Tiramisu","Panna Cotta","Cr\xE8me Br\xFBl\xE9e","Macarons","Churros","Flan","Bread Pudding","Pecan Pie","Key Lime Pie","Banana Split","Sundae","Milkshake"],fruit:["Apple","Banana","Orange","Strawberry","Grape","Watermelon","Pineapple","Mango","Peach","Pear","Cherry","Blueberry","Raspberry","Blackberry","Kiwi","Plum","Apricot","Cantaloupe","Honeydew","Papaya","Guava","Lychee","Dragon Fruit"],vegetable:["Carrot","Broccoli","Cauliflower","Spinach","Kale","Lettuce","Cabbage","Cucumber","Tomato","Bell Pepper","Zucchini","Eggplant","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Onion","Garlic","Celery","Radish","Beet"],meat:["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Bacon","Sausage","Ham","Salami","Prosciutto","Ribeye","Sirloin","Tenderloin"],spice:["Black Pepper","Cumin","Paprika","Cinnamon","Nutmeg","Ginger","Turmeric","Curry","Chili Powder","Cayenne","Oregano","Basil","Thyme","Rosemary","Sage","Coriander","Cardamom","Cloves","Allspice","Bay Leaf","Mustard Seed","Fennel","Star Anise"]},animal:{dog:["Labrador Retriever","German Shepherd","Golden Retriever","French Bulldog","Bulldog","Poodle","Beagle","Rottweiler","German Shorthaired Pointer","Dachshund","Pembroke Welsh Corgi","Australian Shepherd","Yorkshire Terrier","Cavalier King Charles Spaniel","Doberman Pinscher","Boxer","Miniature Schnauzer","Great Dane","Siberian Husky","Bernese Mountain Dog","Pomeranian","Boston Terrier","Havanese","Shetland Sheepdog","Brittany","Cocker Spaniel"],cat:["Persian","Maine Coon","Ragdoll","Bengal","Siamese","British Shorthair","Abyssinian","Birman","Oriental Shorthair","Sphynx","Devon Rex","American Shorthair","Scottish Fold","Exotic Shorthair","Russian Blue","Norwegian Forest Cat","Siberian","Burmese","Manx","Cornish Rex","Himalayan","Turkish Angora","Balinese","Tonkinese"],bird:["Parakeet","Cockatiel","Lovebird","Canary","Finch","Parrot","Macaw","Cockatoo","African Grey","Conure","Budgie","Dove","Pigeon","Robin","Cardinal","Blue Jay","Sparrow","Crow","Raven","Hawk","Eagle","Owl","Hummingbird","Woodpecker"],fish:["Goldfish","Betta","Guppy","Molly","Platy","Swordtail","Tetra","Angelfish","Discus","Gourami","Barb","Danio","Koi","Oscar","Cichlid","Clownfish","Tang","Damselfish","Wrasse","Goby","Blenny","Pufferfish","Lionfish"],horse:["Arabian","Thoroughbred","Quarter Horse","Appaloosa","Paint","Tennessee Walker","Morgan","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Mustang","Shetland Pony","Welsh Pony","Palomino","Buckskin","Pinto","Warmblood"],rabbit:["Holland Lop","Netherland Dwarf","Mini Rex","Flemish Giant","English Lop","French Lop","Angora","Dutch","Lionhead","Rex","Polish","Himalayan"],insect:["Butterfly","Bee","Ant","Beetle","Ladybug","Dragonfly","Grasshopper","Cricket","Moth","Firefly","Praying Mantis","Walking Stick","Caterpillar","Wasp"],type:["Dog","Cat","Bird","Fish","Rabbit","Hamster","Guinea Pig","Mouse","Rat","Ferret","Chinchilla","Hedgehog","Turtle","Lizard","Snake","Frog"]},sport:{sport:["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding"],team:["Lakers","Warriors","Bulls","Celtics","Yankees","Red Sox","Cowboys","Patriots","49ers","Packers","Steelers","Maple Leafs","Bruins","Canadiens","Blackhawks"],athlete:["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Usain Bolt","Michael Phelps"]},music:{genre:["Rock","Pop","Hip Hop","Jazz","Blues","Country","Electronic","Classical","R&B","Soul","Funk","Reggae","Metal","Punk","Indie","Alternative","Folk","Disco","House","Techno","Dubstep","Trap","Gospel","Opera"],artist:["The Beatles","Elvis Presley","Michael Jackson","Madonna","Prince","Bob Dylan","Led Zeppelin","Pink Floyd","Queen","David Bowie","The Rolling Stones","Nirvana","Bruce Springsteen","Stevie Wonder","Aretha Franklin","Ray Charles","Johnny Cash"],song:["Bohemian Rhapsody","Imagine","Hey Jude","Billie Jean","Like a Rolling Stone","Smells Like Teen Spirit","Hotel California","Sweet Child O' Mine","Stairway to Heaven","Purple Haze","What's Going On","Respect","I Want to Hold Your Hand"],instrument:["Guitar","Piano","Drums","Bass","Violin","Cello","Saxophone","Trumpet","Flute","Clarinet","Trombone","Harp","Banjo","Mandolin","Ukulele","Harmonica","Accordion","Xylophone","Synthesizer","Keyboard"]},commerce:{product:["Chair","Table","Lamp","Sofa","Bed","Desk","Computer","Phone","Tablet","Watch","Shoes","Shirt","Pants","Jacket","Hat","Gloves","Bag","Wallet","Sunglasses","Bicycle","Car","Motorcycle","Camera","Headphones","Speaker"],productAdjective:["Small","Medium","Large","Ergonomic","Rustic","Modern","Sleek","Lightweight","Durable","Handmade","Recycled","Refined","Gorgeous","Incredible","Practical","Fantastic","Awesome","Generic","Unbranded","Licensed","Intelligent","Tasty"],productMaterial:["Steel","Wood","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Aluminum","Leather","Silk","Wool","Linen"],department:["Electronics","Clothing","Home & Garden","Sports","Automotive","Books","Toys","Health & Beauty","Grocery","Jewelry","Tools","Music","Movies","Baby","Pet Supplies"],color:["Red","Blue","Green","Yellow","Black","White","Gray","Silver","Gold","Purple","Pink","Orange","Brown","Navy","Teal","Maroon","Olive"]},book:{title:["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","Brave New World","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude"],author:["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee"],publisher:["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Bloomsbury","Vintage"],genre:["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Self-Help","Poetry","Drama","Adventure","Young Adult"],series:["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","Discworld","Dune","Foundation"],review:["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","One of the best books I've ever read."]},vehicle:{manufacturer:["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Tesla","Volvo","Porsche","Jeep","Mazda","Subaru"],model:["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Model 3","Model Y","3 Series","C-Class","A4","Golf","Mustang","Wrangler"],type:["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Electric","Hybrid"],fuel:["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel"],bicycle:["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Gravel Bike"]},word:{adjective:["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold"],adverb:["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well"],conjunction:["and","but","or","nor","for","yet","so","although","because","since","unless","while","when","if"],interjection:["wow","oh","ah","hey","oops","ouch","yay","hooray","hello","goodbye","yes","no"],noun:["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","fire","sun","moon"],preposition:["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through"],verb:["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","think","know","make","take","give"]},hacker:{abbreviation:["TCP","HTTP","RAM","GB","CSS","SSL","SQL","CLI","UI","UX","FTP","API","DNS","IP","LAN","WAN","VPN","SSH","JSON","REST"],adjective:["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","wireless","mobile","neural","optical","cloud","quantum"],noun:["driver","protocol","bandwidth","panel","microchip","program","port","card","interface","system","sensor","firewall","pixel","application","server","database","network"],verb:["bypass","hack","override","compress","copy","navigate","index","connect","generate","calculate","synthesize","transmit","program","parse","compile","encrypt","decrypt"],ingverb:["bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","calculating","synthesizing","transmitting","programming","parsing","compiling","encrypting"],phrase:["We need to bypass the digital firewall!","Try to hack the TCP protocol!","The SSL port is down, override the wireless system!","You can't compress the bandwidth without indexing the neural network!"]},system:{fileName:["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache"],fileType:["audio","image","text","video","application","document","spreadsheet","presentation","archive","code"]},science:{chemicalElement:["Hydrogen","Helium","Lithium","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Iron","Copper","Zinc","Silver","Gold"],unit:["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","volt","ohm","hertz","celsius"],constant:["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Gas Constant"],field:["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Biochemistry","Microbiology","Botany","Zoology"]}},s0=new Map,Y8=new Map,n0=class{static AVAILABLE_BASE_LOCALES=["af","ar","az","cs","da","de","en","eo","es","fa","fi","fr","he","hi","it","ja","ko","nl","no","pl","pt","sv","tl","tr","uk","zh","zu"];static AVAILABLE_LOCALE_VARIANTS=["af_ZA","de_AT","de_CH","de_DE","en_AU","en_CA","en_GB","en_GH","en_HK","en_IE","en_IN","en_NG","en_US","en_ZA","es_ES","es_MX","fr_BE","fr_CA","fr_CH","fr_FR","fr_LU","fr_SN","pt_BR","pt_MZ","pt_PT","zh_CN","zh_TW","zu_ZA"];static getAvailableLocales(){return[...this.AVAILABLE_BASE_LOCALES,...this.AVAILABLE_LOCALE_VARIANTS]}static getAvailableBaseLocales(){return this.AVAILABLE_BASE_LOCALES}static getAvailableLocaleVariants(){return this.AVAILABLE_LOCALE_VARIANTS}static async load(Z){let X=U8(Z).normalized;if(X==="en"){if(!s0.has("en"))s0.set("en",R8);return R8}if(s0.has(X))return s0.get(X);if(Y8.has(X))return Y8.get(X);let _=this.loadLocaleWithFallback(X);Y8.set(X,_);try{let L=await _;return s0.set(X,L),L}finally{Y8.delete(X)}}static loadSync(Z){let X=U8(Z).normalized;if(X==="en"){if(!s0.has("en"))s0.set("en",R8);return R8}if(s0.has(X))return s0.get(X);throw Error(`Locale '${Z}' is not loaded. Please use async loading with faker.setLocale('${Z}') or preload it.`)}static isCached(Z){let X=U8(Z).normalized;return s0.has(X)}static async preload(Z){await Promise.all(Z.map((X)=>this.load(X)))}static clearCache(){s0.clear(),Y8.clear()}static async loadLocaleWithFallback(Z){let X=sY(Z);for(let _=0;_<X.length;_++){let L=X[_],j=_===0&&X.length>1,Y=!j;try{if(j){let z=await this.loadLocaleModule(L),F=X[1];try{let E=await this.loadLocaleModule(F);return FX(E,z)}catch{return z}}else return await this.loadLocaleModule(L)}catch(z){if(_===X.length-1)throw z;continue}}throw Error(`Failed to load locale '${Z}' with fallback chain: ${X.join(" \u2192 ")}`)}static async tryWorkspaceImport(Z,X){if(!E8())return null;try{let _=await import(`../../${X.packageName}/dist/index.js`);return _[X.normalized]||_[X.language]||_.default}catch{try{let _=jY.cwd(),L=LY(_,"packages",X.packageName,"dist","index.js");if(!_Y(L))return null;let j=await import(`file://${L}`);return j[X.normalized]||j[X.language]||j.default}catch{return null}}}static async loadLocaleModule(Z){let X=oY(Z),_=U8(Z);try{let L=await import(X);return L[_.normalized]||L[_.language]||L.default}catch(L){let j=L instanceof Error?L.message:String(L);if(j.includes("Cannot find")||j.includes("not found")||j.includes("ModuleNotFound")){if(E8()&&X.startsWith("@mock-locale/")){let Y=await this.tryWorkspaceImport(Z,_);if(Y)return Y}if(UZ.autoInstallLocales)if(console.log(`
398
- \uD83D\uDD0D Locale '${Z}' not found. Auto-installing ${X}...`),UX(X)){if(E8()&&X.startsWith("@mock-locale/")){let Y=await this.tryWorkspaceImport(Z,_);if(Y)return Y}try{let Y=await import(X);return Y[_.normalized]||Y[_.language]||Y.default}catch(Y){if(E8()&&X.startsWith("@mock-locale/")){let z=await this.tryWorkspaceImport(Z,_);if(z)return z;throw Error(`Locale '${Z}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${X.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${Z}' after installation: ${Y instanceof Error?Y.message:String(Y)}`)}}else throw Error(`Failed to auto-install locale '${Z}'. Please install manually with: bun add ${X}`);throw Error(`Locale '${Z}' is not installed. Install it with: bun add ${X}
457
+ `){let Z=[];for(let Y=0;Y<X;Y++)Z.push(this.paragraph());return Z.join($)}text(X){let $=X??200,Z="";while(Z.length<$)Z+=`${this.paragraph()} `;return Z.trim().slice(0,$)}slug(X=3){return this.words(X).replace(/ /g,"-")}lines(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.sentence());return $.join(`
458
+ `)}}class J${random;locale;constructor(X,$){this.random=X,this.locale=$}genre(){if(this.locale?.music?.genre)return this.random.arrayElement(this.locale.music.genre);let X=["Rock","Pop","Jazz","Blues","Classical","Hip Hop","R&B","Country","Electronic","Dance","Metal","Punk","Reggae","Soul","Funk","Disco","House","Techno","Dubstep","Indie","Alternative","Folk","Gospel","Latin","K-Pop","EDM","Trap","Lo-Fi","Ambient","Ska"];return this.random.arrayElement(X)}songName(){if(this.locale?.music?.song)return this.random.arrayElement(this.locale.music.song);let X=["Dancing in the Moonlight","Bohemian Rhapsody","Stairway to Heaven","Hotel California","Imagine","Yesterday","Hey Jude","Sweet Child O' Mine","Smells Like Teen Spirit","Billie Jean","Thriller","Purple Rain","Born to Run","Like a Rolling Stone","What's Going On","Respect","Good Vibrations","Johnny B. Goode","I Want to Hold Your Hand","Satisfaction","My Generation","Brown Sugar","Layla","Crossroads","The End","Light My Fire","All Along the Watchtower","While My Guitar Gently Weeps","A Day in the Life"];return this.random.arrayElement(X)}albumName(){let X=["Abbey Road","The Dark Side of the Moon","Thriller","Back in Black","The Wall","Rumours","Nevermind","Led Zeppelin IV","Born in the U.S.A.","Sgt. Pepper's Lonely Hearts Club Band","OK Computer","The Beatles (White Album)","Purple Rain","Hotel California","21","Appetite for Destruction","Lemonade","To Pimp a Butterfly","Random Access Memories"];return this.random.arrayElement(X)}artist(){if(this.locale?.music?.artist)return this.random.arrayElement(this.locale.music.artist);let X=["The Beatles","Led Zeppelin","Pink Floyd","Queen","The Rolling Stones","Elvis Presley","Michael Jackson","Madonna","David Bowie","Nirvana","Radiohead","U2","AC/DC","Metallica","Bob Dylan","Jimi Hendrix","Prince","Stevie Wonder","Aretha Franklin","The Who","The Doors","Fleetwood Mac","Eagles","Guns N' Roses","Red Hot Chili Peppers","Coldplay","Beyonc\xE9","Taylor Swift","Drake","Kendrick Lamar","Adele","Ed Sheeran"];return this.random.arrayElement(X)}instrument(){if(this.locale?.music?.instrument)return this.random.arrayElement(this.locale.music.instrument);let X=["Guitar","Piano","Drums","Bass","Violin","Saxophone","Trumpet","Flute","Clarinet","Cello","Harp","Keyboard","Harmonica","Accordion","Ukulele","Banjo","Mandolin","Trombone","French Horn","Tuba","Oboe","Bassoon","Xylophone","Marimba","Tambourine","Synthesizer","Didgeridoo","Sitar","Tabla","Djembe"];return this.random.arrayElement(X)}note(){let X=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return this.random.arrayElement(X)}chord(){let X=this.note(),$=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${X}${$}`}tempo(){return this.random.int(60,200)}key(){let X=this.note(),$=this.random.arrayElement(["Major","Minor"]);return`${X} ${$}`}timeSignature(){let X=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement(X)}}class a8{random;constructor(X){this.random=X}int(X){let $=X?.min??0,Z=X?.max??100;return this.random.int($,Z)}float(X){let $=X?.min??0,Z=X?.max??1,Y=X?.precision??2;return this.random.float($,Z,Y)}bigInt(X){let $=X?.min??0n,Z=(X?.max??1000000n)-$+1n,Y=BigInt(Math.floor(this.random.number()*Number(Z)));return $+Y}binary(X){let $=X?.length??8,Z="";for(let Y=0;Y<$;Y++)Z+=this.random.int(0,1);return Z}octal(X){let $=X?.length??3,Z="";for(let Y=0;Y<$;Y++)Z+=this.random.int(0,7);return Z}hex(X){let $=X?.length??6,Z="0123456789ABCDEF",Y="";for(let U=0;U<$;U++)Y+="0123456789ABCDEF"[this.random.int(0,15)];return Y}randomNumber(X){return this.int(X)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class W${random;locale;constructor(X,$){this.random=X,this.locale=$}firstName(X){if(X?.gender==="male")return this.firstNameMale();if(X?.gender==="female")return this.firstNameFemale();if(X?.gender==="neutral")return this.firstNameNeutral();let $=this.locale.person.firstNameMale.length,Z=this.locale.person.firstNameFemale.length,Y=this.locale.person.firstNameNeutral?.length||0,U=$+Z+Y,_=this.random.int(0,U-1);if(_<$)return this.locale.person.firstNameMale[_];if(_<$+Z)return this.locale.person.firstNameFemale[_-$];return this.locale.person.firstNameNeutral[_-$-Z]}firstNameMale(){return this.random.arrayElement(this.locale.person.firstNameMale)}firstNameFemale(){return this.random.arrayElement(this.locale.person.firstNameFemale)}firstNameNeutral(){if(!this.locale.person.firstNameNeutral||this.locale.person.firstNameNeutral.length===0){let X=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale];return this.random.arrayElement(X)}return this.random.arrayElement(this.locale.person.firstNameNeutral)}lastName(){return this.random.arrayElement(this.locale.person.lastName)}fullName(X){if(!X)return`${this.firstName()} ${this.lastName()}`;let $=this.firstName({gender:X.gender}),Z=this.lastName();if(X.prefix&&X.suffix)return`${this.prefix()} ${$} ${Z} ${this.suffix()}`;if(X.prefix)return`${this.prefix()} ${$} ${Z}`;if(X.suffix)return`${$} ${Z} ${this.suffix()}`;return`${$} ${Z}`}prefix(){return this.random.arrayElement(this.locale.person.prefix)}suffix(){return this.random.arrayElement(this.locale.person.suffix)}gender(){return this.random.arrayElement(this.locale.person.gender)}jobTitle(){return this.random.arrayElement(this.locale.person.jobTitle)}name(){return this.fullName()}firstNameAdvanced(X){let $;if(X?.constraints)$=this.firstName({gender:X.constraints.gender});else $=this.firstName({gender:X?.gender});if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({firstName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).firstName||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.firstName({gender:X?.gender||X?.constraints?.gender})}}return $}fullNameAdvanced(X){let $;if(X?.constraints)$=this.fullName({gender:X.constraints.gender,prefix:X.prefix,suffix:X.suffix});else $=this.fullName(X);if(X?.weighted)$=k$(this.random,X.weighted);if(X?.relationships)$=d9({fullName:$,gender:X?.gender||X?.constraints?.gender},X.relationships).fullName||$;if(X?.validation){let Z=A$($,X.validation);if(!Z.isValid){if(X.validation.strict)throw Error(`Validation failed: ${Z.errors.join(", ")}`);$=this.fullName({gender:X?.gender||X?.constraints?.gender,prefix:X?.prefix,suffix:X?.suffix})}}return $}profile(X){let $=X?.constraints?.gender||X?.gender||this.gender(),Z=this.firstNameAdvanced({...X,gender:$}),Y=this.lastName(),U=`${Z} ${Y}`,_={firstName:Z,lastName:Y,fullName:U,gender:$,jobTitle:this.jobTitle(),age:X?.constraints?.ageRange?this.random.int(X.constraints.ageRange.min,X.constraints.ageRange.max):this.random.int(18,80)};if(X?.relationships)return d9(_,X.relationships);return _}family(X){let $=X?.size||this.random.int(2,6),Z=this.lastName(),Y=["parent","parent","child","child","child","grandparent"],U=[];for(let _=0;_<$;_++){let Q=Y[_]||"relative",L=Q==="parent"||Q==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",z=this.firstNameAdvanced({...X,gender:L,constraints:{...X?.constraints,gender:L}});U.push({firstName:z,lastName:Z,fullName:`${z} ${Z}`,gender:L,relationship:Q})}return{members:U,lastName:Z}}}class V${random;locale;constructor(X,$){this.random=X,this.locale=$}number(X){let $=X??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols($)}phoneNumber(X){return this.number(X)}}class I${random;locale;constructor(X,$){this.random=X,this.locale=$}chemicalElement(){if(this.locale?.science?.chemicalElement)return this.random.arrayElement(this.locale.science.chemicalElement);let X=["Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Argon","Potassium","Calcium","Iron","Copper","Zinc","Silver","Gold","Mercury","Lead","Uranium","Platinum","Titanium"];return this.random.arrayElement(X)}chemicalElementSymbol(){let X=["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Fe","Cu","Zn","Ag","Au","Hg","Pb","U","Pt","Ti"];return this.random.arrayElement(X)}unit(){if(this.locale?.science?.unit)return this.random.arrayElement(this.locale.science.unit);let X=["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","coulomb","volt","ohm","farad","weber","tesla","henry","celsius","lumen","lux","becquerel","gray","sievert","katal","hertz","radian","steradian"];return this.random.arrayElement(X)}constant(){if(this.locale?.science?.constant)return this.random.arrayElement(this.locale.science.constant);let X=["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Magnetic Constant","Electric Constant","Fine Structure Constant","Rydberg Constant","Gas Constant","Stefan-Boltzmann Constant"];return this.random.arrayElement(X)}field(){if(this.locale?.science?.field)return this.random.arrayElement(this.locale.science.field);let X=["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Quantum Mechanics","Thermodynamics","Electromagnetism","Biochemistry","Molecular Biology","Microbiology","Botany","Zoology","Meteorology","Oceanography"];return this.random.arrayElement(X)}dnaSequence(X=12){let $=["A","T","C","G"],Z="";for(let Y=0;Y<X;Y++)Z+=this.random.arrayElement($);return Z}rnaSequence(X=12){let $=["A","U","C","G"],Z="";for(let Y=0;Y<X;Y++)Z+=this.random.arrayElement($);return Z}hypothesis(){let X=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],$=["reaction rate increases","solubility changes","equilibrium shifts","rate decreases","yield improves","product formation accelerates","process efficiency increases"];return`If ${this.random.arrayElement(X)}, then ${this.random.arrayElement($)}`}}class K${random;locale;constructor(X,$){this.random=X,this.locale=$}sport(){if(this.locale?.sport?.sport)return this.random.arrayElement(this.locale.sport.sport);let X=["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding","Cycling","Running","Marathon","Triathlon","Gymnastics","Fencing","Archery","Martial Arts","Karate","Judo","Taekwondo","MMA","Formula 1","NASCAR","Sailing"];return this.random.arrayElement(X)}team(){if(this.locale?.sport?.team)return this.random.arrayElement(this.locale.sport.team);let X=["Lakers","Warriors","Bulls","Celtics","Knicks","Heat","Spurs","Mavericks","Yankees","Red Sox","Dodgers","Cubs","Giants","Astros","Braves","Phillies","Patriots","49ers","Cowboys","Packers","Steelers","Eagles","Seahawks","Chiefs","Manchester United","Real Madrid","Barcelona","Liverpool","Bayern Munich","PSG","Maple Leafs","Bruins","Canadiens","Blackhawks","Penguins","Lightning"];return this.random.arrayElement(X)}athlete(){if(this.locale?.sport?.athlete)return this.random.arrayElement(this.locale.sport.athlete);let X=["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Pel\xE9","Cristiano Ronaldo","Lionel Messi","Roger Federer","Usain Bolt","Simone Biles","Michael Phelps","Kobe Bryant","Derek Jeter","Joe Montana","Magic Johnson","Larry Bird"];return this.random.arrayElement(X)}position(){let X=["Quarterback","Running Back","Wide Receiver","Linebacker","Defensive Back","Point Guard","Shooting Guard","Small Forward","Power Forward","Center","Pitcher","Catcher","First Base","Shortstop","Outfielder","Forward","Midfielder","Defender","Goalkeeper","Striker","Winger"];return this.random.arrayElement(X)}event(){let X=["Super Bowl","World Series","NBA Finals","Stanley Cup","FIFA World Cup","Olympics","Wimbledon","Masters Tournament","Kentucky Derby","Indianapolis 500","Tour de France","Boston Marathon","UEFA Champions League","World Cup","The Open Championship","US Open","French Open","Australian Open"];return this.random.arrayElement(X)}league(){let X=["NFL","NBA","MLB","NHL","MLS","Premier League","La Liga","Serie A","Bundesliga","Ligue 1","UEFA","FIFA","NCAA","PGA","ATP","WTA","F1","NASCAR","IndyCar"];return this.random.arrayElement(X)}quote(){let X=["Just do it!","Winners never quit and quitters never win.","Hard work beats talent when talent doesn't work hard.","The only way to prove you're a good sport is to lose.","Champions keep playing until they get it right.","It's not whether you get knocked down, it's whether you get up.","You miss 100% of the shots you don't take.","The difference between the impossible and the possible lies in determination."];return this.random.arrayElement(X)}equipment(){let X=["Ball","Bat","Glove","Helmet","Racket","Puck","Skates","Cleats","Pads","Jersey","Goggles","Swimsuit","Bicycle","Surfboard","Skateboard","Snowboard","Skis","Golf Clubs","Tennis Racket","Boxing Gloves","Mouthguard"];return this.random.arrayElement(X)}}class t8{random;constructor(X){this.random=X}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let X="0123456789abcdef",$="";for(let Z=0;Z<36;Z++)if(Z===8||Z===13||Z===18||Z===23)$+="-";else if(Z===14)$+="4";else if(Z===19){let Y=this.random.int(0,15);$+=X[Y&3|8]}else $+=X[this.random.int(0,15)];return $}nanoid(X=21){let $="";for(let Z=0;Z<X;Z++)$+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return $}alpha(X){let $=X?.length??10,Z=X?.casing??"mixed",Y="abcdefghijklmnopqrstuvwxyz",U="ABCDEFGHIJKLMNOPQRSTUVWXYZ",_="";if(Z==="lower")_="abcdefghijklmnopqrstuvwxyz";else if(Z==="upper")_="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else _="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let Q="";for(let L=0;L<$;L++)Q+=_[this.random.int(0,_.length-1)];return Q}alphanumeric(X){let $=X?.length??10,Z=X?.casing??"mixed",Y="abcdefghijklmnopqrstuvwxyz",U="ABCDEFGHIJKLMNOPQRSTUVWXYZ",_="0123456789",Q="0123456789";if(Z==="lower")Q+="abcdefghijklmnopqrstuvwxyz";else if(Z==="upper")Q+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else Q+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let L="";for(let z=0;z<$;z++)L+=Q[this.random.int(0,Q.length-1)];return L}numeric(X=10){if(!this.random.isSeeded()){let Z="";for(let Y=0;Y<X;Y++)Z+=Math.floor(Math.random()*10);return Z}let $="";for(let Z=0;Z<X;Z++)$+=this.random.int(0,9);return $}sample(X=10){return this.alphanumeric({length:X})}symbol(X=5){let $="";for(let Z=0;Z<X;Z++)$+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return $}hexadecimal(X){let $=X?.length??6,Z=X?.prefix??"",Y="0123456789abcdef",U=Z;for(let _=0;_<$;_++)U+="0123456789abcdef"[this.random.int(0,15)];return U}}class R${random;locale;constructor(X,$){this.random=X,this.locale=$}fileName(X){let $;if(this.locale?.system?.fileName)$=this.locale.system.fileName;else $=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let Z=this.random.arrayElement($),Y=X?.extension??this.fileExtension();return`${Z}.${Y}`}fileExtension(){let X=["pdf","doc","docx","xls","xlsx","ppt","pptx","txt","csv","json","xml","jpg","jpeg","png","gif","bmp","svg","webp","ico","mp3","wav","ogg","flac","aac","m4a","mp4","avi","mov","wmv","flv","webm","mkv","zip","rar","tar","gz","7z","bz2","html","css","js","ts","jsx","tsx","vue","py","java","cpp","c","go","rs"];return this.random.arrayElement(X)}commonFileName(){let X=["README.md","package.json","tsconfig.json",".gitignore",".env","docker-compose.yml","Dockerfile","index.html","index.js","app.js","main.py","requirements.txt","Makefile","LICENSE","CHANGELOG.md","yarn.lock","package-lock.json","pom.xml"];return this.random.arrayElement(X)}mimeType(){let X=["application/json","application/xml","application/pdf","application/zip","text/html","text/css","text/javascript","text/plain","text/csv","image/jpeg","image/png","image/gif","image/svg+xml","image/webp","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg","video/avi","application/octet-stream","multipart/form-data","application/x-www-form-urlencoded"];return this.random.arrayElement(X)}commonMimeType(){let X=["application/json","application/pdf","text/html","text/plain","text/css","image/jpeg","image/png","image/gif","audio/mpeg","video/mp4"];return this.random.arrayElement(X)}fileType(){if(this.locale?.system?.fileType)return this.random.arrayElement(this.locale.system.fileType);let X=["audio","image","text","video","application","document","spreadsheet","presentation","archive","code","data","font","executable"];return this.random.arrayElement(X)}directoryPath(){let X=["/usr/local/bin","/usr/bin","/etc","/var/log","/tmp","/home","/root","/opt","/srv","/mnt","/media","/dev","/proc","/sys","C:\\Program Files","C:\\Users","C:\\Windows","C:\\Temp","/Applications","/Library","/System","/Users","/Documents","/Downloads"];return this.random.arrayElement(X)}filePath(){return`${this.directoryPath()}/${this.fileName()}`}semver(){let X=this.random.int(0,10),$=this.random.int(0,20),Z=this.random.int(0,50);return`${X}.${$}.${Z}`}networkInterface(){let X=["eth0","eth1","wlan0","wlan1","lo","docker0","veth0","br0","tun0","tap0","enp0s3","ens33","wlp2s0","en0","en1","wlan0","WiFi","Ethernet"];return this.random.arrayElement(X)}cron(){let X=this.random.boolean(0.5)?"*":this.random.int(0,59),$=this.random.boolean(0.5)?"*":this.random.int(0,23),Z=this.random.boolean(0.5)?"*":this.random.int(1,31),Y=this.random.boolean(0.5)?"*":this.random.int(1,12),U=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${X} ${$} ${Z} ${Y} ${U}`}}class D${random;locale;constructor(X,$){this.random=X,this.locale=$}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(tU)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(eU)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(X7)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement($7)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(Z7)}vin(){let X="";for(let $=0;$<17;$++)X+="ABCDEFGHJKLMNPRSTUVWXYZ0123456789"[this.random.int(0,32)];return X}registration(){let X=["???-####","###-???","??? ###","##?-###","???-###"];return this.random.arrayElement(X).replace(/\?/g,()=>this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""))).replace(/#/g,()=>String(this.random.int(0,9)))}vehicle(){let X=this.random.int(2000,2024),$=this.manufacturer(),Z=this.model();return`${X} ${$} ${Z}`}bicycle(){if(this.locale?.vehicle?.bicycle)return this.random.arrayElement(this.locale.vehicle.bicycle);let X=["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Touring Bike","Cyclocross","Gravel Bike","Track Bike","Recumbent"];return this.random.arrayElement(X)}}class M${random;locale;constructor(X,$){this.random=X,this.locale=$}adjective(){if(this.locale?.word?.adjective)return this.random.arrayElement(this.locale.word.adjective);let X=["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold","warm","cool","bright","dark","loud","quiet","strong","weak","clean","dirty","new","old","young","fresh","dry","wet","smooth","rough","sharp","dull","simple","complex","easy","difficult","good","bad","right","wrong","true","false"];return this.random.arrayElement(X)}adverb(){if(this.locale?.word?.adverb)return this.random.arrayElement(this.locale.word.adverb);let X=["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well","almost","always","never","often","rarely","sometimes","usually","frequently","occasionally","immediately","instantly","eventually","probably","possibly"];return this.random.arrayElement(X)}conjunction(){if(this.locale?.word?.conjunction)return this.random.arrayElement(this.locale.word.conjunction);let X=["and","but","or","nor","for","yet","so","although","because","since","unless","while","where","if","than","when","after","before","until"];return this.random.arrayElement(X)}interjection(){if(this.locale?.word?.interjection)return this.random.arrayElement(this.locale.word.interjection);let X=["wow","oh","ah","hey","oops","ouch","yay","hooray","alas","bravo","hello","goodbye","yes","no","well","hmm","uh","er","um"];return this.random.arrayElement(X)}noun(){if(this.locale?.word?.noun)return this.random.arrayElement(this.locale.word.noun);let X=["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","air","fire","earth","mountain","river","ocean","sky","sun","moon","star","cloud","rain","snow","person","man","woman","child","friend","family","food","music","art","book","school","work","time","day","night","morning","evening","world","life","love"];return this.random.arrayElement(X)}preposition(){if(this.locale?.word?.preposition)return this.random.arrayElement(this.locale.word.preposition);let X=["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through","during","before","after","against","among","into","onto","upon","within","without","toward","near","beside","behind"];return this.random.arrayElement(X)}verb(){if(this.locale?.word?.verb)return this.random.arrayElement(this.locale.word.verb);let X=["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","look","see","hear","think","know","want","like","love","hate","need","make","take","give","get","put","come","go","say","tell","ask","answer","help","start","stop","begin","end","open","close","show","hide","find","lose","buy","sell","learn"];return this.random.arrayElement(X)}sample(){let X=["adjective","adverb","conjunction","interjection","noun","preposition","verb"],$=this.random.arrayElement(X);return this[$]()}words(X=3){let $=[];for(let Z=0;Z<X;Z++)$.push(this.sample());return $.join(" ")}}class e8{seed;constructor(X){this.seed=X}isSeeded(){return this.seed!==void 0}number(){if(this.seed!==void 0)return this.seed=(this.seed*9301+49297)%233280,this.seed/233280;return Math.random()}int(X=0,$=100){return Math.floor(this.number()*($-X+1))+X}float(X=0,$=1,Z=2){let Y=this.number()*($-X)+X;return Number.parseFloat(Y.toFixed(Z))}arrayElement(X){if(X.length===0)throw Error("Cannot pick from empty array");if(this.seed===void 0)return X[Math.floor(Math.random()*X.length)];return X[this.int(0,X.length-1)]}arrayElements(X,$){if(X.length===0)return[];let Z=$??this.int(1,X.length);return[...X].sort(()=>this.number()-0.5).slice(0,Math.min(Z,X.length))}shuffle(X){let $=[...X];for(let Z=$.length-1;Z>0;Z--){let Y=this.int(0,Z);[$[Z],$[Y]]=[$[Y],$[Z]]}return $}boolean(X=0.5){return this.number()<X}replaceSymbols(X){if(this.seed===void 0){let $="";for(let Z=0;Z<X.length;Z++){let Y=X[Z];if(Y==="#")$+="0123456789"[Math.floor(Math.random()*10)];else if(Y==="?")$+=h1[Math.floor(Math.random()*26)];else $+=Y}return $}return X.replace(/[#?]/g,($)=>{if($==="#")return String(this.int(0,9));return this.arrayElement(h1)})}replaceCreditCardSymbols(X="####-####-####-####",$="#"){return X.replace(new RegExp($,"g"),()=>String(this.int(0,9)))}weightedArrayElement(X){if(X.length===0)throw Error("Cannot pick from empty weighted items array");let $=X.reduce((U,_)=>U+_.weight,0);if($<=0)throw Error("Total weight must be greater than 0");let Z=this.number()*$,Y=0;for(let U of X)if(Y+=U.weight,Z<=Y)return U.item;return X[X.length-1].item}weightedArrayElements(X,$,Z=!1){if(X.length===0)return[];let Y=$??this.int(1,X.length),U=[],_=[...X];for(let Q=0;Q<Y&&_.length>0;Q++){let L=this.weightedArrayElement(_);if(U.push(L),!Z){let z=_.findIndex((j)=>j.item===L);if(z!==-1)_.splice(z,1)}}return U}weightedBoolean(X=0.5){return this.number()<X}weightedInt(X,$,Z){let Y=$-X+1;if(Z){if(Z.length!==Y)throw Error("Weights array length must match the range size");let U=Z.map((_,Q)=>({item:X+Q,weight:_}));return this.weightedArrayElement(U)}return this.int(X,$)}}class jZ{random;_locale;_autoInstallLocales;person;address;internet;phone;company;lorem;date;number;string;color;finance;helpers;vehicle;image;git;science;music;database;food;commerce;book;animal;sport;hacker;system;word;constructor(X){let $=X?.locale??"en",Z=X?.seed;if(this._autoInstallLocales=X?.autoInstallLocales??!1,$!=="en"&&!Y9.isCached($))console.warn(`[ts-mocker] Locale '${$}' requires async loading. Use 'await Faker.create({ locale: "${$}" })' for better performance. Falling back to English.`),this._locale=Y9.loadSync("en");else this._locale=Y9.loadSync($);this.random=new e8(Z),this.person=new W$(this.random,this._locale),this.address=new _$(this.random,this._locale),this.internet=new O$(this.random,this._locale),this.phone=new V$(this.random,this._locale),this.company=new E$(this.random,this._locale),this.lorem=new r8(this.random),this.date=new n8(this.random),this.number=new a8(this.random),this.string=new t8(this.random),this.color=new L$(this.random,this._locale),this.finance=new i8(this.random),this.helpers=new s8(this.random),this.image=new o8(this.random),this.git=new l8(this.random),this.science=new I$(this.random,this._locale),this.music=new J$(this.random,this._locale),this.database=new u8(this.random),this.food=new G$(this.random,this._locale),this.commerce=new j$(this.random,this._locale),this.book=new z$(this.random,this._locale),this.animal=new Q$(this.random,this._locale),this.sport=new K$(this.random,this._locale),this.hacker=new F$(this.random,this._locale),this.system=new R$(this.random,this._locale),this.word=new M$(this.random,this._locale),this.vehicle=new D$(this.random,this._locale)}static async create(X){let $=X?.locale??"en";return await Y9.load($),new jZ(X)}seed(X){return this.random=new e8(X),Object.assign(this.person,new W$(this.random,this._locale)),Object.assign(this.address,new _$(this.random,this._locale)),Object.assign(this.internet,new O$(this.random,this._locale)),Object.assign(this.phone,new V$(this.random,this._locale)),Object.assign(this.company,new E$(this.random,this._locale)),Object.assign(this.lorem,new r8(this.random)),Object.assign(this.date,new n8(this.random)),Object.assign(this.number,new a8(this.random)),Object.assign(this.string,new t8(this.random)),Object.assign(this.color,new L$(this.random,this._locale)),Object.assign(this.finance,new i8(this.random)),Object.assign(this.helpers,new s8(this.random)),Object.assign(this.image,new o8(this.random)),Object.assign(this.git,new l8(this.random)),Object.assign(this.science,new I$(this.random,this._locale)),Object.assign(this.music,new J$(this.random,this._locale)),Object.assign(this.database,new u8(this.random)),Object.assign(this.food,new G$(this.random,this._locale)),Object.assign(this.commerce,new j$(this.random,this._locale)),Object.assign(this.book,new z$(this.random,this._locale)),Object.assign(this.animal,new Q$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.hacker,new F$(this.random,this._locale)),Object.assign(this.system,new R$(this.random,this._locale)),Object.assign(this.word,new M$(this.random,this._locale)),Object.assign(this.vehicle,new D$(this.random,this._locale)),this}async setLocale(X){return this._locale=await Y9.load(X),this.reinitializeLocaleModules(),this}setLocaleSync(X){if(!Y9.isCached(X)&&X!=="en")return console.warn(`[ts-mocker] Locale '${X}' is not loaded. Use 'await faker.setLocale("${X}")' or preload it first.`),this;return this._locale=Y9.loadSync(X),this.reinitializeLocaleModules(),this}async preloadLocales(X){return await Y9.preload(X),this}reinitializeLocaleModules(){Object.assign(this.person,new W$(this.random,this._locale)),Object.assign(this.address,new _$(this.random,this._locale)),Object.assign(this.internet,new O$(this.random,this._locale)),Object.assign(this.phone,new V$(this.random,this._locale)),Object.assign(this.company,new E$(this.random,this._locale)),Object.assign(this.food,new G$(this.random,this._locale)),Object.assign(this.animal,new Q$(this.random,this._locale)),Object.assign(this.sport,new K$(this.random,this._locale)),Object.assign(this.music,new J$(this.random,this._locale)),Object.assign(this.commerce,new j$(this.random,this._locale)),Object.assign(this.book,new z$(this.random,this._locale)),Object.assign(this.vehicle,new D$(this.random,this._locale)),Object.assign(this.word,new M$(this.random,this._locale)),Object.assign(this.hacker,new F$(this.random,this._locale)),Object.assign(this.system,new R$(this.random,this._locale)),Object.assign(this.color,new L$(this.random,this._locale)),Object.assign(this.science,new I$(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return Y9.getAvailableLocales()}static isLocaleLoaded(X){return Y9.isCached(X)}static async preloadLocales(X){await Y9.preload(X)}name(){return this.person.name()}email(){return this.internet.email()}}var cU,JL=(X)=>X,WL=(X,$)=>{for(var Z in $)cU(X,Z,{get:$[Z],enumerable:!0,configurable:!0,set:mz.bind($,Z)})},H9=(X,$)=>()=>(X&&($=X(X=0)),$),mU,hX,x$,aY,CX,tY,iZ,H$,VL,B0,G0,IL,eY,KL,X6,RL,DL,lZ,ML,$6,Z6,HL,sZ,CL,wL,qL,PL,TL,C8,uU,NL,Y6,SL="0.15.9",AL=()=>{},Z9,w8,C$,oZ,rZ,q8,aZ,tZ,w$,eZ,X1,m9,n9,$1,U6,z8,Z1,nU,Y1,j9,k9,_6,Q6,z6,kL=()=>{},U1,_1,XZ,Q1=null,y1,nX,z9,wX,Y9,iU,lU,sU,oU,rU,aU,tU,eU,X7,$7,Z7,h1,v1,Y7,xL=e(()=>{cU=Object.defineProperty,mU=import.meta.require,CX=H9(()=>{hX=new A1,x$=new k1,aY={createKey:uz,isEquivalent:nz,estimateMemoryUsage:iz}}),Y6=H9(()=>{tY=c8.env.CLARITY_LOG_DIR||Hz(lz(),"logs"),iZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},H$={...iZ},VL=(async()=>{try{let{loadConfig:X}=await Promise.resolve().then(()=>(_1(),U1)),$=await X({name:"clarity",alias:"logging",defaultConfig:iZ,cwd:c8.cwd()});if($)Object.assign(H$,$)}catch{}return H$})(),B0={red:(X)=>`\x1B[31m${X}\x1B[0m`,green:(X)=>`\x1B[32m${X}\x1B[0m`,yellow:(X)=>`\x1B[33m${X}\x1B[0m`,blue:(X)=>`\x1B[34m${X}\x1B[0m`,magenta:(X)=>`\x1B[35m${X}\x1B[0m`,cyan:(X)=>`\x1B[36m${X}\x1B[0m`,white:(X)=>`\x1B[37m${X}\x1B[0m`,gray:(X)=>`\x1B[90m${X}\x1B[0m`,bgRed:(X)=>`\x1B[41m${X}\x1B[0m`,bgYellow:(X)=>`\x1B[43m${X}\x1B[0m`,bgGray:(X)=>`\x1B[100m${X}\x1B[0m`,bold:(X)=>`\x1B[1m${X}\x1B[0m`,dim:(X)=>`\x1B[2m${X}\x1B[0m`,italic:(X)=>`\x1B[3m${X}\x1B[0m`,underline:(X)=>`\x1B[4m${X}\x1B[0m`,strikethrough:(X)=>`\x1B[9m${X}\x1B[0m`,reset:"\x1B[0m"},G0=B0,IL=B0.red,eY=B0.green,KL=B0.yellow,X6=B0.blue,RL=B0.magenta,DL=B0.cyan,lZ=B0.white,ML=B0.gray,$6=B0.bgRed,Z6=B0.bgYellow,HL=B0.bgGray,sZ=B0.bold,CL=B0.dim,wL=B0.italic,qL=B0.underline,PL=B0.strikethrough,TL=B0.reset,C8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uU={debug:"\uD83D\uDD0D",info:X6("\u2139"),success:eY("\u2713"),warning:Z6(lZ(sZ(" WARN "))),error:$6(lZ(sZ(" ERROR ")))},NL=new m8("stacks")}),n9=H9(()=>{Z9=class extends Error{timestamp;context;constructor(X,$={}){super(X);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 X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Z])=>`${$}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},w8=class extends Z9{code="CONFIG_NOT_FOUND";constructor(X,$,Z){let Y=Z===void 0?[]:Array.isArray(Z)?Z.filter(Boolean):[Z],U="";if(Y.length===1)U=` or alias "${Y[0]}"`;else if(Y.length>1)U=` or aliases ${Y.map((_)=>`"${_}"`).join(", ")}`;super(`Configuration "${X}"${U} not found`,{configName:X,alias:Z,searchPaths:$,searchPathCount:$.length})}},C$=class extends Z9{code="CONFIG_LOAD_ERROR";constructor(X,$,Z){super(`Failed to load configuration from "${X}": ${$.message}`,{configPath:X,configName:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},oZ=class extends Z9{code="CONFIG_VALIDATION_ERROR";constructor(X,$,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},rZ=class extends Z9{code="CONFIG_MERGE_ERROR";constructor(X,$,Z,Y){super(`Failed to merge configuration from "${X}" with "${$}": ${Z.message}`,{sourcePath:X,targetPath:$,configName:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},q8=class extends Z9{code="ENV_VAR_ERROR";constructor(X,$,Z,Y){super(`Failed to parse environment variable "${X}" with value "${$}" as ${Z}`,{envKey:X,envValue:$,expectedType:Z,configName:Y})}},aZ=class extends Z9{code="FILE_SYSTEM_ERROR";constructor(X,$,Z){super(`File system ${X} failed for "${$}": ${Z.message}`,{operation:X,path:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},tZ=class extends Z9{code="TYPE_GENERATION_ERROR";constructor(X,$,Z){super(`Failed to generate types from "${X}" to "${$}": ${Z.message}`,{configDir:X,outputPath:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},w$=class extends Z9{code="SCHEMA_VALIDATION_ERROR";constructor(X,$,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:$,errorCount:$.length})}},eZ=class extends Z9{code="BROWSER_CONFIG_ERROR";constructor(X,$,Z,Y){super(`Failed to fetch configuration from "${X}": ${$} ${Z}`,{endpoint:X,status:$,statusText:Z,configName:Y})}},X1=class extends Z9{code="PLUGIN_ERROR";constructor(X,$,Z){super(`Plugin "${X}" failed during ${$}: ${Z.message}`,{pluginName:X,operation:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},m9={configNotFound(X,$,Z){return new w8(X,$,Z)},configLoad(X,$,Z){return new C$(X,$,Z)},configValidation(X,$,Z){return new oZ(X,$,Z)},configMerge(X,$,Z,Y){return new rZ(X,$,Z,Y)},envVar(X,$,Z,Y){return new q8(X,$,Z,Y)},fileSystem(X,$,Z){return new aZ(X,$,Z)},typeGeneration(X,$,Z){return new tZ(X,$,Z)},schemaValidation(X,$,Z){return new w$(X,$,Z)},browserConfig(X,$,Z,Y){return new eZ(X,$,Z,Y)},plugin(X,$,Z){return new X1(X,$,Z)}}}),$1=H9(()=>{CX(),n9()}),z8=H9(()=>{U6={replace:"replace",concat:"concat",smart:"smart"}}),Z1=H9(()=>{CX(),n9(),z8()}),Y1=H9(()=>{CX(),n9(),nU=/^https?:\/\//}),z6=H9(()=>{Y6(),AL(),CX(),n9(),$1(),Z1(),Y1(),z8(),j9=new m8("bunfig",{showTags:!0}),k9=new B1,_6=l0(XX.cwd(),"config"),Q6=l0(XX.cwd(),"src/generated")}),U1={},WL(U1,{withErrorRecovery:()=>yU,tryLoadConfig:()=>_L,loadConfigWithResult:()=>YL,loadConfig:()=>L5,isRetryableError:()=>rz,isConfigNotFoundError:()=>oz,isBunfigError:()=>hU,globalPerformanceMonitor:()=>x$,globalCache:()=>hX,getEnvOrDefault:()=>az,generateConfigTypes:()=>QL,defaultGeneratedDir:()=>Q6,defaultConfigDir:()=>_6,deepMergeWithArrayStrategy:()=>Q5,deepMerge:()=>vU,createLibraryConfig:()=>zL,config:()=>UL,bunfigPlugin:()=>LL,applyEnvVarsToConfig:()=>aX,TypeGenerationError:()=>tZ,SchemaValidationError:()=>w$,PluginError:()=>X1,PerformanceMonitor:()=>k1,FileSystemError:()=>aZ,ErrorFactory:()=>m9,EnvVarError:()=>q8,EnvProcessor:()=>zZ,ConfigValidator:()=>z5,ConfigValidationError:()=>oZ,ConfigNotFoundError:()=>w8,ConfigMergeError:()=>rZ,ConfigLoader:()=>B1,ConfigLoadError:()=>C$,ConfigFileLoader:()=>LZ,ConfigCache:()=>A1,CacheUtils:()=>aY,BunfigError:()=>Z9,BrowserConfigError:()=>eZ,ArrayMergeStrategies:()=>U6}),_1=H9(()=>{z6(),n9(),CX(),n9(),kL(),$1(),Z1(),Y1(),z8()}),_1(),XZ={verbose:!1,locale:"en",autoInstallLocales:!1},y1=XZ,nX={title:"English",person:{firstNameMale:["James","John","Robert","Michael","William","David","Richard","Joseph","Thomas","Charles","Christopher","Daniel","Matthew","Anthony","Mark","Donald","Steven","Paul","Andrew","Joshua","Kenneth","Kevin","Brian","George","Timothy","Ronald","Edward","Jason","Jeffrey","Ryan","Jacob","Gary","Nicholas","Eric","Jonathan","Stephen","Larry","Justin","Scott","Brandon","Benjamin","Samuel","Raymond","Gregory","Frank","Alexander","Patrick","Jack","Dennis","Jerry","Liam","Noah","Oliver","Elijah","Lucas","Mason","Logan","Ethan","Henry","Jackson","Sebastian","Aiden","Carter","Owen","Wyatt","Luke","Jayden","Dylan","Grayson","Levi","Isaac","Gabriel","Julian","Mateo","Jaxon","Lincoln"],firstNameFemale:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen","Lisa","Nancy","Betty","Margaret","Sandra","Ashley","Kimberly","Emily","Donna","Michelle","Dorothy","Carol","Amanda","Melissa","Deborah","Stephanie","Rebecca","Sharon","Laura","Cynthia","Kathleen","Amy","Angela","Shirley","Anna","Brenda","Pamela","Emma","Nicole","Helen","Olivia","Ava","Isabella","Sophia","Mia","Charlotte","Amelia","Harper","Evelyn","Abigail","Sofia","Ella","Scarlett","Grace","Chloe","Victoria","Aria","Lily","Aubrey","Zoey","Penelope","Lillian","Addison","Layla","Natalie","Camila"],firstNameNeutral:["Taylor","Jordan","Alex","Riley","Casey","Morgan","Avery","Quinn","Blake","Cameron","Sage","River","Phoenix","Rowan","Skyler","Charlie","Finley","Peyton","Reese","Kai"],lastName:["Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Rodriguez","Martinez","Hernandez","Lopez","Gonzalez","Wilson","Anderson","Thomas","Taylor","Moore","Jackson","Martin","Lee","Perez","Thompson","White","Harris","Sanchez","Clark","Ramirez","Lewis","Robinson","Walker","Young","Allen","King","Wright","Scott","Torres","Nguyen","Hill","Flores","Green","Adams","Nelson","Baker","Hall","Rivera","Campbell","Mitchell","Carter","Roberts","Gomez","Phillips","Evans","Turner","Diaz","Parker","Cruz","Edwards","Collins","Reyes","Stewart","Morris","Morales","Murphy","Cook","Rogers","Gutierrez","Ortiz","Morgan","Cooper","Peterson","Bailey","Reed","Kelly","Howard","Ramos","Kim","Cox","Ward","Richardson","Watson","Brooks","Chavez","Wood","James","Bennett","Gray","Mendoza","Ruiz","Hughes","Price","Alvarez","Castillo","Sanders","Patel","Myers","Long","Ross","Foster","Jimenez"],prefix:["Mr.","Mrs.","Ms.","Miss","Dr.","Prof."],suffix:["Jr.","Sr.","I","II","III","IV","V","MD","PhD","DDS"],gender:["Male","Female","Non-binary","Agender","Bigender","Genderfluid","Genderqueer"],jobTitle:["Software Engineer","Product Manager","Designer","Data Scientist","DevOps Engineer","Marketing Manager","Sales Representative","Accountant","Human Resources Manager","CEO","CTO","CFO","COO","Director","Manager","Analyst","Consultant","Administrator","Coordinator","Specialist","Developer","Architect","Engineer","Technician","Assistant","Project Manager","Business Analyst","Quality Assurance Engineer","UX Designer","UI Designer","Backend Developer","Frontend Developer","Full Stack Developer","Mobile Developer","Cloud Architect","Security Engineer","Network Engineer","Database Administrator","Systems Administrator","Technical Writer","Scrum Master","Product Owner","Release Manager","Content Manager","Social Media Manager","SEO Specialist","Digital Marketing Specialist","Growth Hacker","Brand Manager","Creative Director","Financial Analyst","Investment Banker","Risk Analyst","Compliance Officer","Tax Consultant","Legal Counsel","Paralegal","Executive Assistant","Operations Manager","Supply Chain Manager","Logistics Coordinator","Customer Success Manager","Account Executive","Sales Engineer","Technical Support"]},address:{street:["Main","Oak","Maple","Cedar","Elm","Washington","Lake","Hill","Park","River","Sunset","Pine","Walnut","Highland","Madison","Lincoln","Jackson","Franklin"],city:["New York","Los Angeles","Chicago","Playa Vista","Houston","Phoenix","Philadelphia","San Antonio","San Diego","Dallas","San Jose","Austin","Jacksonville","Fort Worth","Columbus","Charlotte","San Francisco","Indianapolis","Seattle","Denver","Boston","Nashville","Detroit","Memphis","Portland","Oklahoma City","Las Vegas","Louisville","Baltimore","Milwaukee","Albuquerque","Tucson","Fresno","Sacramento","Mesa","Kansas City","Atlanta","Long Beach","Colorado Springs","Raleigh","Miami","Virginia Beach","Omaha","Oakland","Minneapolis","Tulsa","Arlington","Tampa","New Orleans","Wichita","Cleveland","Bakersfield","Aurora","Anaheim","Honolulu","Santa Ana","Riverside","Corpus Christi","Lexington","Stockton","Henderson","Saint Paul","Cincinnati","Pittsburgh","Greensboro","Anchorage","Plano","Lincoln","Orlando","Irvine","Newark","Durham","Chula Vista","Toledo","Fort Wayne","St. Petersburg","Laredo","Jersey City"],state:["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],stateAbbr:["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],country:["United States","Canada","United Kingdom","Australia","Germany","France","Spain","Italy","Japan","China","India","Brazil","Mexico","Russia","South Korea"],countryCode:["US","CA","GB","AU","DE","FR","ES","IT","JP","CN","IN","BR","MX","RU","KR"],zipCode:["#####","#####-####"],buildingNumber:["###","####","#","##"],direction:["North","East","South","West","Northeast","Northwest","Southeast","Southwest"],streetSuffix:["Street","Avenue","Road","Boulevard","Drive","Court","Circle","Lane","Way","Place","Terrace","Parkway","Commons","Trail","Square","Run","Crossing"]},company:{name:["TechCorp","GlobalSoft","DataSystems","CloudNet","Innovate Inc","Digital Solutions","NextGen Tech","FutureTech","SmartSystems","CoreTech","PrimeSoft","AlphaTech"],suffix:["Inc","LLC","Corp","Group","Ltd","Co","Technologies","Solutions","Systems"],industry:["Technology","Finance","Healthcare","Education","Retail","Manufacturing","Telecommunications","Energy","Real Estate","Transportation","Media","Hospitality"],buzzwords:["synergize","leverage","innovate","disrupt","optimize","streamline","transform","revolutionize","empower","enable","facilitate","orchestrate","integrate"],adjective:["revolutionary","cutting-edge","innovative","next-generation","advanced","leading","premier","world-class","enterprise","scalable","robust","seamless"],descriptor:["global","digital","cloud-based","AI-powered","data-driven","user-centric","agile","secure","efficient","intelligent","automated","integrated"],noun:["solution","platform","system","service","technology","framework","infrastructure","application","network","portal","ecosystem","architecture","engine"]},internet:{domainSuffix:["com","net","org","io","co","app","dev","tech","ai","cloud"],freeEmail:["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","proton.me"]},phone:{formats:["###-###-####","(###) ###-####","1-###-###-####","+1-###-###-####","###.###.####"]},food:{dish:["Hamburger","Cheeseburger","Pizza","Hot Dog","Fried Chicken","BBQ Ribs","Mac and Cheese","Grilled Cheese","BLT Sandwich","Caesar Salad","Cobb Salad","Chicken Wings","Nachos","Tacos","Burrito","Quesadilla","Fish and Chips","Clam Chowder","Lobster Roll","Cheesesteak","Pulled Pork Sandwich","Buffalo Wings","Meatloaf","Pot Roast","Fried Catfish","Jambalaya","Gumbo","Po' Boy","Corn Dog","Chili","Baked Beans","Cornbread","Biscuits and Gravy"],ingredient:["Flour","Sugar","Salt","Pepper","Butter","Eggs","Milk","Cheese","Tomato","Onion","Garlic","Olive Oil","Chicken","Beef","Pork","Fish","Rice","Pasta","Bread","Potato","Carrot","Celery","Bell Pepper","Mushroom","Spinach","Broccoli","Lettuce","Avocado","Lemon","Lime","Basil","Oregano","Thyme","Rosemary","Parsley","Cilantro"],cuisine:["American","Italian","Mexican","Chinese","Japanese","Thai","Indian","French","Greek","Spanish","Mediterranean","Vietnamese","Korean","Turkish","Lebanese","Brazilian","Argentinian","Peruvian","Caribbean","Moroccan","Ethiopian"],dessert:["Apple Pie","Chocolate Cake","Ice Cream","Brownies","Cookies","Cheesecake","Donuts","Cupcakes","Tiramisu","Panna Cotta","Cr\xE8me Br\xFBl\xE9e","Macarons","Churros","Flan","Bread Pudding","Pecan Pie","Key Lime Pie","Banana Split","Sundae","Milkshake"],fruit:["Apple","Banana","Orange","Strawberry","Grape","Watermelon","Pineapple","Mango","Peach","Pear","Cherry","Blueberry","Raspberry","Blackberry","Kiwi","Plum","Apricot","Cantaloupe","Honeydew","Papaya","Guava","Lychee","Dragon Fruit"],vegetable:["Carrot","Broccoli","Cauliflower","Spinach","Kale","Lettuce","Cabbage","Cucumber","Tomato","Bell Pepper","Zucchini","Eggplant","Asparagus","Green Beans","Peas","Corn","Potato","Sweet Potato","Onion","Garlic","Celery","Radish","Beet"],meat:["Beef","Chicken","Pork","Lamb","Turkey","Duck","Veal","Venison","Bison","Bacon","Sausage","Ham","Salami","Prosciutto","Ribeye","Sirloin","Tenderloin"],spice:["Black Pepper","Cumin","Paprika","Cinnamon","Nutmeg","Ginger","Turmeric","Curry","Chili Powder","Cayenne","Oregano","Basil","Thyme","Rosemary","Sage","Coriander","Cardamom","Cloves","Allspice","Bay Leaf","Mustard Seed","Fennel","Star Anise"]},animal:{dog:["Labrador Retriever","German Shepherd","Golden Retriever","French Bulldog","Bulldog","Poodle","Beagle","Rottweiler","German Shorthaired Pointer","Dachshund","Pembroke Welsh Corgi","Australian Shepherd","Yorkshire Terrier","Cavalier King Charles Spaniel","Doberman Pinscher","Boxer","Miniature Schnauzer","Great Dane","Siberian Husky","Bernese Mountain Dog","Pomeranian","Boston Terrier","Havanese","Shetland Sheepdog","Brittany","Cocker Spaniel"],cat:["Persian","Maine Coon","Ragdoll","Bengal","Siamese","British Shorthair","Abyssinian","Birman","Oriental Shorthair","Sphynx","Devon Rex","American Shorthair","Scottish Fold","Exotic Shorthair","Russian Blue","Norwegian Forest Cat","Siberian","Burmese","Manx","Cornish Rex","Himalayan","Turkish Angora","Balinese","Tonkinese"],bird:["Parakeet","Cockatiel","Lovebird","Canary","Finch","Parrot","Macaw","Cockatoo","African Grey","Conure","Budgie","Dove","Pigeon","Robin","Cardinal","Blue Jay","Sparrow","Crow","Raven","Hawk","Eagle","Owl","Hummingbird","Woodpecker"],fish:["Goldfish","Betta","Guppy","Molly","Platy","Swordtail","Tetra","Angelfish","Discus","Gourami","Barb","Danio","Koi","Oscar","Cichlid","Clownfish","Tang","Damselfish","Wrasse","Goby","Blenny","Pufferfish","Lionfish"],horse:["Arabian","Thoroughbred","Quarter Horse","Appaloosa","Paint","Tennessee Walker","Morgan","Andalusian","Friesian","Clydesdale","Percheron","Belgian","Mustang","Shetland Pony","Welsh Pony","Palomino","Buckskin","Pinto","Warmblood"],rabbit:["Holland Lop","Netherland Dwarf","Mini Rex","Flemish Giant","English Lop","French Lop","Angora","Dutch","Lionhead","Rex","Polish","Himalayan"],insect:["Butterfly","Bee","Ant","Beetle","Ladybug","Dragonfly","Grasshopper","Cricket","Moth","Firefly","Praying Mantis","Walking Stick","Caterpillar","Wasp"],type:["Dog","Cat","Bird","Fish","Rabbit","Hamster","Guinea Pig","Mouse","Rat","Ferret","Chinchilla","Hedgehog","Turtle","Lizard","Snake","Frog"]},sport:{sport:["Football","Basketball","Baseball","Soccer","Tennis","Golf","Hockey","Boxing","Wrestling","Swimming","Track and Field","Volleyball","Cricket","Rugby","Lacrosse","Badminton","Table Tennis","Bowling","Skiing","Snowboarding","Surfing","Skateboarding"],team:["Lakers","Warriors","Bulls","Celtics","Yankees","Red Sox","Cowboys","Patriots","49ers","Packers","Steelers","Maple Leafs","Bruins","Canadiens","Blackhawks"],athlete:["Michael Jordan","LeBron James","Tom Brady","Serena Williams","Tiger Woods","Muhammad Ali","Babe Ruth","Wayne Gretzky","Usain Bolt","Michael Phelps"]},music:{genre:["Rock","Pop","Hip Hop","Jazz","Blues","Country","Electronic","Classical","R&B","Soul","Funk","Reggae","Metal","Punk","Indie","Alternative","Folk","Disco","House","Techno","Dubstep","Trap","Gospel","Opera"],artist:["The Beatles","Elvis Presley","Michael Jackson","Madonna","Prince","Bob Dylan","Led Zeppelin","Pink Floyd","Queen","David Bowie","The Rolling Stones","Nirvana","Bruce Springsteen","Stevie Wonder","Aretha Franklin","Ray Charles","Johnny Cash"],song:["Bohemian Rhapsody","Imagine","Hey Jude","Billie Jean","Like a Rolling Stone","Smells Like Teen Spirit","Hotel California","Sweet Child O' Mine","Stairway to Heaven","Purple Haze","What's Going On","Respect","I Want to Hold Your Hand"],instrument:["Guitar","Piano","Drums","Bass","Violin","Cello","Saxophone","Trumpet","Flute","Clarinet","Trombone","Harp","Banjo","Mandolin","Ukulele","Harmonica","Accordion","Xylophone","Synthesizer","Keyboard"]},commerce:{product:["Chair","Table","Lamp","Sofa","Bed","Desk","Computer","Phone","Tablet","Watch","Shoes","Shirt","Pants","Jacket","Hat","Gloves","Bag","Wallet","Sunglasses","Bicycle","Car","Motorcycle","Camera","Headphones","Speaker"],productAdjective:["Small","Medium","Large","Ergonomic","Rustic","Modern","Sleek","Lightweight","Durable","Handmade","Recycled","Refined","Gorgeous","Incredible","Practical","Fantastic","Awesome","Generic","Unbranded","Licensed","Intelligent","Tasty"],productMaterial:["Steel","Wood","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Aluminum","Leather","Silk","Wool","Linen"],department:["Electronics","Clothing","Home & Garden","Sports","Automotive","Books","Toys","Health & Beauty","Grocery","Jewelry","Tools","Music","Movies","Baby","Pet Supplies"],color:["Red","Blue","Green","Yellow","Black","White","Gray","Silver","Gold","Purple","Pink","Orange","Brown","Navy","Teal","Maroon","Olive"]},book:{title:["To Kill a Mockingbird","1984","Pride and Prejudice","The Great Gatsby","Moby Dick","War and Peace","The Odyssey","The Catcher in the Rye","The Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Hobbit","Brave New World","Crime and Punishment","The Brothers Karamazov","One Hundred Years of Solitude"],author:["Ernest Hemingway","F. Scott Fitzgerald","Jane Austen","Charles Dickens","Mark Twain","Leo Tolstoy","Fyodor Dostoevsky","George Orwell","J.R.R. Tolkien","J.K. Rowling","Stephen King","Agatha Christie","William Shakespeare","Edgar Allan Poe","Harper Lee"],publisher:["Penguin Random House","HarperCollins","Simon & Schuster","Macmillan","Hachette","Scholastic","Oxford University Press","Cambridge University Press","Bloomsbury","Vintage"],genre:["Fiction","Non-Fiction","Mystery","Thriller","Romance","Science Fiction","Fantasy","Horror","Historical Fiction","Biography","Self-Help","Poetry","Drama","Adventure","Young Adult"],series:["Harry Potter","The Lord of the Rings","A Song of Ice and Fire","The Hunger Games","Twilight","The Chronicles of Narnia","Percy Jackson","Discworld","Dune","Foundation"],review:["A masterpiece of modern literature!","Gripping from start to finish.","Couldn't put it down!","A must-read for everyone.","Beautifully written and deeply moving.","An unforgettable story.","Brilliant and thought-provoking.","One of the best books I've ever read."]},vehicle:{manufacturer:["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Tesla","Volvo","Porsche","Jeep","Mazda","Subaru"],model:["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Model 3","Model Y","3 Series","C-Class","A4","Golf","Mustang","Wrangler"],type:["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Electric","Hybrid"],fuel:["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel"],bicycle:["Mountain Bike","Road Bike","BMX","Cruiser","Hybrid","Electric Bike","Folding Bike","Gravel Bike"]},word:{adjective:["beautiful","happy","sad","quick","slow","big","small","tall","short","long","wide","narrow","thick","thin","heavy","light","hard","soft","hot","cold"],adverb:["quickly","slowly","carefully","easily","hardly","loudly","quietly","suddenly","finally","really","very","completely","absolutely","perfectly","badly","well"],conjunction:["and","but","or","nor","for","yet","so","although","because","since","unless","while","when","if"],interjection:["wow","oh","ah","hey","oops","ouch","yay","hooray","hello","goodbye","yes","no"],noun:["table","chair","book","pen","computer","phone","door","window","car","house","tree","flower","dog","cat","bird","fish","water","fire","sun","moon"],preposition:["in","on","at","by","for","with","from","to","of","about","under","over","above","below","between","through"],verb:["run","walk","jump","swim","fly","eat","drink","sleep","work","play","read","write","speak","listen","watch","think","know","make","take","give"]},hacker:{abbreviation:["TCP","HTTP","RAM","GB","CSS","SSL","SQL","CLI","UI","UX","FTP","API","DNS","IP","LAN","WAN","VPN","SSH","JSON","REST"],adjective:["auxiliary","primary","back-end","digital","open-source","virtual","cross-platform","redundant","online","wireless","mobile","neural","optical","cloud","quantum"],noun:["driver","protocol","bandwidth","panel","microchip","program","port","card","interface","system","sensor","firewall","pixel","application","server","database","network"],verb:["bypass","hack","override","compress","copy","navigate","index","connect","generate","calculate","synthesize","transmit","program","parse","compile","encrypt","decrypt"],ingverb:["bypassing","hacking","overriding","compressing","copying","navigating","indexing","connecting","generating","calculating","synthesizing","transmitting","programming","parsing","compiling","encrypting"],phrase:["We need to bypass the digital firewall!","Try to hack the TCP protocol!","The SSL port is down, override the wireless system!","You can't compress the bandwidth without indexing the neural network!"]},system:{fileName:["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache"],fileType:["audio","image","text","video","application","document","spreadsheet","presentation","archive","code"]},science:{chemicalElement:["Hydrogen","Helium","Lithium","Carbon","Nitrogen","Oxygen","Fluorine","Neon","Sodium","Magnesium","Aluminum","Silicon","Phosphorus","Sulfur","Chlorine","Iron","Copper","Zinc","Silver","Gold"],unit:["meter","kilogram","second","ampere","kelvin","mole","candela","newton","pascal","joule","watt","volt","ohm","hertz","celsius"],constant:["Speed of Light","Gravitational Constant","Planck Constant","Boltzmann Constant","Avogadro Constant","Elementary Charge","Gas Constant"],field:["Physics","Chemistry","Biology","Astronomy","Geology","Ecology","Genetics","Neuroscience","Biochemistry","Microbiology","Botany","Zoology"]}},z9=new Map,wX=new Map,Y9=class{static AVAILABLE_BASE_LOCALES=["af","ar","az","cs","da","de","en","eo","es","fa","fi","fr","he","hi","it","ja","ko","nl","no","pl","pt","sv","tl","tr","uk","zh","zu"];static AVAILABLE_LOCALE_VARIANTS=["af_ZA","de_AT","de_CH","de_DE","en_AU","en_CA","en_GB","en_GH","en_HK","en_IE","en_IN","en_NG","en_US","en_ZA","es_ES","es_MX","fr_BE","fr_CA","fr_CH","fr_FR","fr_LU","fr_SN","pt_BR","pt_MZ","pt_PT","zh_CN","zh_TW","zu_ZA"];static getAvailableLocales(){return[...this.AVAILABLE_BASE_LOCALES,...this.AVAILABLE_LOCALE_VARIANTS]}static getAvailableBaseLocales(){return this.AVAILABLE_BASE_LOCALES}static getAvailableLocaleVariants(){return this.AVAILABLE_LOCALE_VARIANTS}static async load($){let Z=SX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",nX);return nX}if(z9.has(Z))return z9.get(Z);if(wX.has(Z))return wX.get(Z);let Y=this.loadLocaleWithFallback(Z);wX.set(Z,Y);try{let U=await Y;return z9.set(Z,U),U}finally{wX.delete(Z)}}static loadSync($){let Z=SX($).normalized;if(Z==="en"){if(!z9.has("en"))z9.set("en",nX);return nX}if(z9.has(Z))return z9.get(Z);throw Error(`Locale '${$}' is not loaded. Please use async loading with faker.setLocale('${$}') or preload it.`)}static isCached($){let Z=SX($).normalized;return z9.has(Z)}static async preload($){await Promise.all($.map((Z)=>this.load(Z)))}static clearCache(){z9.clear(),wX.clear()}static async loadLocaleWithFallback($){let Z=EL($);for(let Y=0;Y<Z.length;Y++){let U=Z[Y],_=Y===0&&Z.length>1,Q=!_;try{if(_){let L=await this.loadLocaleModule(U),z=Z[1];try{let j=await this.loadLocaleModule(z);return gU(j,L)}catch{return L}}else return await this.loadLocaleModule(U)}catch(L){if(Y===Z.length-1)throw L;continue}}throw Error(`Failed to load locale '${$}' with fallback chain: ${Z.join(" \u2192 ")}`)}static async tryWorkspaceImport($,Z){if(!AX())return null;try{let Y=await import(`../../${Z.packageName}/dist/index.js`);return Y[Z.normalized]||Y[Z.language]||Y.default}catch{try{let Y=Mz.cwd(),U=Dz(Y,"packages",Z.packageName,"dist","index.js");if(!Rz(U))return null;let _=await import(`file://${U}`);return _[Z.normalized]||_[Z.language]||_.default}catch{return null}}}static async loadLocaleModule($){let Z=GL($),Y=SX($);try{let U=await import(Z);return U[Y.normalized]||U[Y.language]||U.default}catch(U){let _=U instanceof Error?U.message:String(U);if(_.includes("Cannot find")||_.includes("not found")||_.includes("ModuleNotFound")){if(AX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}if(y1.autoInstallLocales)if(console.log(`
459
+ \uD83D\uDD0D Locale '${$}' not found. Auto-installing ${Z}...`),pU(Z)){if(AX()&&Z.startsWith("@mock-locale/")){let Q=await this.tryWorkspaceImport($,Y);if(Q)return Q}try{let Q=await import(Z);return Q[Y.normalized]||Q[Y.language]||Q.default}catch(Q){if(AX()&&Z.startsWith("@mock-locale/")){let L=await this.tryWorkspaceImport($,Y);if(L)return L;throw Error(`Locale '${$}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${Z.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${$}' after installation: ${Q instanceof Error?Q.message:String(Q)}`)}}else throw Error(`Failed to auto-install locale '${$}'. Please install manually with: bun add ${Z}`);throw Error(`Locale '${$}' is not installed. Install it with: bun add ${Z}
399
460
  Or install all locales with: bun add @mock-locale/{af,ar,az,cs,da,de,en,eo,es,fa,fi,fr,he,hi,it,ja,ko,nl,no,pl,pt,sv,tl,tr,uk,zh,zu}
400
- Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${Z}': ${j}`)}}},VX=new TZ,GX={email:($)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test($)},phone:($)=>{let Z=/^\+?[1-9]\d{0,15}$/,X=$.replace(/[\s\-()]/g,"");return X.length>=7&&Z.test(X)},name:($)=>{return/^[a-z\s\-']+$/i.test($)&&$.length>=2&&$.length<=50},age:($)=>{return Number.isInteger($)&&$>=0&&$<=150},url:($)=>{try{let Z=new URL($);return $.startsWith("http://")||$.startsWith("https://")}catch{return!1}},regex:($)=>(Z)=>{return $.test(Z)},length:($,Z)=>(X)=>{return X.length>=$&&X.length<=Z},range:($,Z)=>(X)=>{return X>=$&&X<=Z}},KX={phoneByCountry:{field:"phone",dependsOn:"country",mapping:{"United States":"+1-###-###-####","United Kingdom":"+44 #### ### ###",Germany:"+49 ### ########",France:"+33 # ## ## ## ##",Spain:"+34 ### ## ## ##",Italy:"+39 ### ### ###",Japan:"+81 ##-####-####",China:"+86 ### #### ####",Australia:"+61 ### ### ###",Canada:"+1-###-###-####"}},postalCodeByCountry:{field:"postalCode",dependsOn:"country",mapping:{"United States":"#####","United Kingdom":"AA## #AA",Germany:"#####",France:"#####",Spain:"#####",Italy:"#####",Japan:"###-####",China:"######",Australia:"####",Canada:"A#A #A#"}},firstNameByGender:{field:"firstName",dependsOn:"gender",mapping:{male:["John","Michael","David","James","Robert","William","Richard","Thomas","Christopher","Daniel"],female:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen"]}}},IX={commonFirstNames:{items:[{item:"John",weight:100},{item:"Michael",weight:85},{item:"David",weight:80},{item:"James",weight:75},{item:"Robert",weight:70},{item:"William",weight:65},{item:"Richard",weight:60},{item:"Thomas",weight:55},{item:"Christopher",weight:50},{item:"Daniel",weight:45}]},ageDistribution:{items:[{item:25,weight:80},{item:30,weight:90},{item:35,weight:95},{item:40,weight:100},{item:45,weight:85},{item:50,weight:70},{item:55,weight:55},{item:60,weight:40},{item:65,weight:25},{item:70,weight:15}]},countryDistribution:{items:[{item:"United States",weight:100},{item:"China",weight:95},{item:"India",weight:90},{item:"Brazil",weight:60},{item:"Russia",weight:55},{item:"Japan",weight:50},{item:"Germany",weight:45},{item:"United Kingdom",weight:40},{item:"France",weight:35},{item:"Italy",weight:30}]}},WX=[".","_","-",""],DX=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","fugiat","nulla","pariatur","excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"],SX=["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Hyundai","Kia","Mazda","Subaru","Lexus","Tesla","Volvo","Porsche","Jeep","Ram","GMC","Dodge","Chrysler","Buick","Cadillac","Acura","Infiniti","Genesis","Land Rover","Jaguar","Mini"],MX=["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Silverado","Tacoma","Altima","Sentra","Rogue","Model 3","Model Y","Model S","X5","X3","3 Series","5 Series","C-Class","E-Class","A4","Q5","Golf","Jetta","Passat","Tiguan","Escape","Explorer","Mustang","Ranger","Malibu","Equinox","Traverse","Wrangler","Grand Cherokee","Cherokee","Compass"],RX=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],JX=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],CX=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],EZ="abcdefghijklmnopqrstuvwxyz".split(""),OZ=new o$,wX=OZ}),qX={};IZ(qX,{validateData:()=>L1,selectWeightedItem:()=>j1,isInWorkspace:()=>E8,installPackage:()=>UX,globalProviderRegistry:()=>VX,getConfig:()=>lY,generateRealisticData:()=>tY,faker:()=>OZ,detectPackageManager:()=>zX,defaultConfig:()=>d$,default:()=>wX,config:()=>UZ,applyRelationships:()=>x9,applyConstraints:()=>rY,WordModule:()=>o8,WeightedSelections:()=>IX,VehicleModule:()=>s8,ValidationRules:()=>GX,SystemModule:()=>l8,StringModule:()=>b$,SportModule:()=>i8,ScienceModule:()=>n8,Random:()=>f$,PhoneModule:()=>u8,PersonModule:()=>m8,NumberModule:()=>v$,MusicModule:()=>c8,LoremModule:()=>A$,LocaleLoader:()=>n0,InternetModule:()=>d8,ImageModule:()=>y$,HelpersModule:()=>h$,HackerModule:()=>p8,GitModule:()=>B$,FoodModule:()=>g8,FinanceModule:()=>x$,Faker:()=>o$,DateModule:()=>k$,DatabaseModule:()=>T$,DataRelationships:()=>KX,DataProviderRegistry:()=>TZ,CompanyModule:()=>f8,CommerceModule:()=>b8,ColorModule:()=>v8,BookModule:()=>A8,AnimalModule:()=>y8,AddressModule:()=>h8});var NF=n(async()=>{await HF()});function Y9($){if(!b1)try{b1=(Y$(),sX(TX)).getModel}catch{b1=()=>{return}}return b1($)}function QQ($){if($.database instanceof QZ)r8=$.database;else r8=new QZ($.database||":memory:",{create:!0});c$.clear()}function V0(){if(!r8)r8=new QZ(":memory:",{create:!0});return r8}function PF($){let Z=new Set,X=$.belongsToMany;if(!X)return Z;if(Array.isArray(X)){for(let _ of X)if(typeof _==="string")Z.add(_.toLowerCase());else if(_&&typeof _==="object"&&_.model)Z.add(_.model.toLowerCase())}else if(typeof X==="object")for(let _ of Object.keys(X))Z.add(_);return Z}class i0{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor($,Z={}){this._definition=$,this._attributes={...Z},this._original=null;let X=PF($);if(X.size===0)return;let _=this;return new Proxy(this,{get(L,j,Y){if(typeof j==="string"&&X.has(j)&&!(j in L))return()=>{let z=HX($,j);if(!z||z.type!=="belongsToMany")throw Error(`[orm] relation '${j}' did not resolve to a belongsToMany on '${$.name}'`);let F=Y9(z.relatedModelName),E=F?.getDefinition?.()||F?.definition;if(!E)throw Error(`[orm] related model '${z.relatedModelName}' is not registered`);return new NX(_,$,z,E)};return Reflect.get(L,j,Y)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get($){let Z=this._definition.get?.[$];if(Z)try{let X=Z(this._attributes);if(X!==void 0)return X}catch{}return this._attributes[$]}getAttribute($){return this._attributes[$]}getAttributes(){return{...this._attributes}}set($,Z){if(this._original===null)this._original={...this._attributes};this._attributes[$]=Z}only($){let Z={};for(let X of $)Z[X]=this._attributes[X];return Z}except($){let Z=new Set($.map((_)=>_)),X={};for(let _ of Object.keys(this._attributes))if(!Z.has(_))X[_]=this._attributes[_];return X}getRelation($){return this._relations[$]}setRelation($,Z){this._relations[$]=Z}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let $=this._definition.primaryKey||"id";return this._attributes[$]}isDirty($){if(this._original===null)return!1;if($)return this._attributes[$]!==this._original[$];return Object.keys(this._attributes).some((Z)=>this._attributes[Z]!==this._original[Z])}isClean($){return!this.isDirty($)}getOriginal($){return this.getOriginalAttributes()[$]}getChanges(){if(this._original===null)return{};let $={};for(let Z of Object.keys(this._attributes))if(this._attributes[Z]!==this._original[Z])$[Z]=this._attributes[Z];return $}fill($){let Z=this._definition.attributes;for(let[X,_]of Object.entries($)){let L=Z[X];if(L?.fillable&&!L?.guarded)this._attributes[X]=_}return this}forceFill($){return Object.assign(this._attributes,$),this}save(){let $=V0(),Z=this._definition.primaryKey||"id",X=this._definition.hooks,_=this._definition.set||{};for(let[L,j]of Object.entries(_))if(this.isDirty(L))this._attributes[L]=j(this._attributes);if(this._attributes[Z]){X?.beforeUpdate?.(this,this.getChanges());let L=this.getChanges(),j=Object.keys(L);if(j.length>0){let Y=j.map((F)=>`${F} = ?`).join(", "),z=[...Object.values(L),this._attributes[Z]];if(this._definition.traits?.useTimestamps){let F=new Date().toISOString();$.run(`UPDATE ${this._definition.table} SET ${Y}, updated_at = ? WHERE ${Z} = ?`,[...Object.values(L),F,this._attributes[Z]])}else $.run(`UPDATE ${this._definition.table} SET ${Y} WHERE ${Z} = ?`,z)}X?.afterUpdate?.(this)}else{let L=this._definition.attributes,j={};for(let[E,U]of Object.entries(L))if(U.fillable&&this._attributes[E]!==void 0)j[E]=this._attributes[E];if(this._definition.traits?.useTimestamps){let E=new Date().toISOString();j.created_at=E,j.updated_at=E}if(this._definition.traits?.useUuid&&!j.uuid)j.uuid=crypto.randomUUID();X?.beforeCreate?.(j);let Y=Object.keys(j),z=Y.map(()=>"?").join(", "),F=$.run(`INSERT INTO ${this._definition.table} (${Y.join(", ")}) VALUES (${z})`,Object.values(j));for(let[E,U]of Object.entries(j))this._attributes[E]=U;this._attributes[Z]=F.lastInsertRowid,X?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}update($){return this.fill($),this.save()}fresh(){let $=V0(),Z=this._definition.primaryKey||"id",X=this._attributes[Z];if(X==null)return null;let _=$.query(`SELECT * FROM ${this._definition.table} WHERE ${Z} = ?`).get(X);if(!_)return null;return new i0(this._definition,_)}delete(){let $=V0(),Z=this._definition.primaryKey||"id",X=this._attributes[Z],_=this._definition.hooks;if(!X)throw Error("Cannot delete a model without a primary key");if(_?.beforeDelete?.(this),this._definition.traits?.useSoftDeletes)$.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${Z} = ?`,[new Date().toISOString(),X]);else $.run(`DELETE FROM ${this._definition.table} WHERE ${Z} = ?`,[X]);return _?.afterDelete?.(this),!0}refresh(){let $=V0(),Z=this._definition.primaryKey||"id",X=this._attributes[Z];if(!X)throw Error("Cannot refresh a model without a primary key");let _=$.query(`SELECT * FROM ${this._definition.table} WHERE ${Z} = ?`).get(X);if(!_)return null;return this._attributes=_,this._original=null,this}replicate(){let $=this._definition.primaryKey||"id",Z={...this._attributes};return delete Z[$],delete Z.uuid,delete Z.created_at,delete Z.updated_at,new i0(this._definition,Z)}toArray(){let $={...this._attributes};for(let[Z,X]of Object.entries(this._relations))if(Array.isArray(X))$[Z]=X.map((_)=>_.toArray());else if(X)$[Z]=X.toArray();else $[Z]=null;return $}toJSON(){let $=new Set;for(let[X,_]of Object.entries(this._definition.attributes))if(_.hidden)$.add(X);let Z={};for(let[X,_]of Object.entries(this._attributes))if(!$.has(X))Z[X]=_;for(let[X,_]of Object.entries(this._relations))if(Array.isArray(_))Z[X]=_.map((L)=>L.toJSON());else if(_)Z[X]=_.toJSON();else Z[X]=null;return Z}}function j$($){let Z=VZ.get($);if(Z!==void 0)return Z;return Z=$.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),VZ.set($,Z),Z}function J8($){let Z=GZ.get($);if(Z!==void 0)return Z;let X=j$($);if(X.endsWith("y")&&!X.endsWith("ay")&&!X.endsWith("ey")&&!X.endsWith("oy")&&!X.endsWith("uy"))Z=X.slice(0,-1)+"ies";else if(X.endsWith("s")||X.endsWith("x")||X.endsWith("ch")||X.endsWith("sh"))Z=`${X}es`;else Z=`${X}s`;return GZ.set($,Z),Z}function HX($,Z){let{name:X,table:_}=$,L=$.primaryKey||"id";function j(V){if(!V)return null;if(Array.isArray(V)){for(let Q of V){let O=typeof Q==="string"?Q:Q?.model||"";if(O&&O.toLowerCase()===Z.toLowerCase())return O}return null}if(typeof V==="object"){for(let[Q,O]of Object.entries(V))if(Q===Z||Q.toLowerCase()===Z.toLowerCase())return typeof O==="string"?O:O?.model||O?.target||Q}return null}function Y(){let V=$.belongsToMany;if(!V)return null;if(Array.isArray(V)){for(let Q of V)if(typeof Q==="string"){if(Q.toLowerCase()===Z.toLowerCase())return{entry:Q}}else if(Q&&typeof Q==="object"&&Q.model){if(Q.model.toLowerCase()===Z.toLowerCase())return{entry:Q}}return null}if(typeof V==="object"){for(let[Q,O]of Object.entries(V))if(Q===Z||Q.toLowerCase()===Z.toLowerCase())return{entry:O}}return null}let z=j($.hasMany);if(z){let Q=Y9(z)?.getTable?.()||J8(z),O=j$(X)+"_id";return{type:"hasMany",relatedModelName:z,relatedTable:Q,foreignKey:O,localKey:L}}let F=j($.hasOne);if(F){let Q=Y9(F)?.getTable?.()||J8(F),O=j$(X)+"_id";return{type:"hasOne",relatedModelName:F,relatedTable:Q,foreignKey:O,localKey:L}}let E=j($.belongsTo);if(E){let V=Y9(E),Q=V?.getTable?.()||J8(E),O=V?.getDefinition?.()?.primaryKey||"id",K=j$(E)+"_id";return{type:"belongsTo",relatedModelName:E,relatedTable:Q,foreignKey:K,localKey:O}}let U=Y();if(U){let V=typeof U.entry==="object",Q=V?U.entry.model:U.entry,K=Y9(Q)?.getTable?.()||J8(Q),I=V?U.entry:null,C,D;if(I?.table)C=I.table;else if(I?.through){D=I.through;let T=Y9(I.through);if(!T)throw Error(`[orm] belongsToMany relation '${Z}' on '${X}' references unknown through model '${I.through}'. Make sure '${I.through}' is registered.`);C=T.getTable?.()||T.getDefinition?.()?.table||J8(I.through)}else{let T=_.endsWith("s")?_.slice(0,-1):_,v=K.endsWith("s")?K.slice(0,-1):K;C=[T,v].sort().join("_")}let M=I?.foreignKey||`${_.endsWith("s")?_.slice(0,-1):_}_id`,J=I?.relatedKey||`${K.endsWith("s")?K.slice(0,-1):K}_id`,N=[];if(I?.pivot?.columns)for(let T of Object.keys(I.pivot.columns))N.push(T);if(D){let T=Y9(D),v=T?.getDefinition?.()||T?.definition,b=v?.attributes??{},f=v?.primaryKey??"id";for(let p of Object.keys(b)){if(p===M||p===J||p===f)continue;if(!N.includes(p))N.push(p)}}return{type:"belongsToMany",relatedModelName:Q,relatedTable:K,foreignKey:M,localKey:L,pivotTable:C,pivotFkParent:M,pivotFkRelated:J,pivotColumns:N,pivotModelName:D,pivotTimestamps:Boolean(I?.pivot?.timestamps)}}return null}class NX{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor($,Z,X,_){this._parent=$,this._parentDef=Z,this._resolved=X,this._relatedDef=_}get parentId(){let $=this._parentDef.primaryKey||"id";return this._parent.get($)}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,X){if(X===void 0)this._wheres.push({sql:`${this.relatedTable}.${$} = ?`,params:[Z]});else this._wheres.push({sql:`${this.relatedTable}.${$} ${String(Z)} ?`,params:[X]});return this}wherePivot($,Z,X){if(X===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${$} = ?`,params:[Z]});else this._pivotWheres.push({sql:`${this.pivotTable}.${$} ${String(Z)} ?`,params:[X]});return this}wherePivotIn($,Z){if(!Z.length)return this;let X=Z.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IN (${X})`,params:[...Z]}),this}wherePivotNotIn($,Z){if(!Z.length)return this;let X=Z.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} NOT IN (${X})`,params:[...Z]}),this}wherePivotNull($){return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IS NULL`,params:[]}),this}wherePivotNotNull($){return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IS NOT NULL`,params:[]}),this}orderBy($,Z="asc"){return this._orderBy.push(`${$} ${Z.toUpperCase()}`),this}limit($){return this._limit=$,this}offset($){return this._offset=$,this}buildSelect(){let $=[],Z=`SELECT ${this.relatedTable}.*, ${this.pivotTable}.* FROM ${this.relatedTable}`;Z+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,Z+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,$.push(this.parentId);for(let X of this._pivotWheres)Z+=` AND ${X.sql}`,$.push(...X.params);for(let X of this._wheres)Z+=` AND ${X.sql}`,$.push(...X.params);if(this._orderBy.length>0)Z+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)Z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Z+=` OFFSET ${this._offset}`;return{sql:Z,params:$}}hydrateRows($){let Z=new Set(Object.keys(this._relatedDef.attributes??{}));Z.add(this.relatedPk),Z.add("created_at"),Z.add("updated_at"),Z.add("deleted_at");let X=this.fkParent,_=this.fkRelated;return $.map((L)=>{let j={},Y={};for(let[F,E]of Object.entries(L)){if(F===X||F===_)continue;if(Z.has(F))j[F]=E;else Y[F]=E}j[this.relatedPk]=L[this.relatedPk];let z=new i0(this._relatedDef,j);return z.pivot=Y,z})}get(){let $=V0(),{sql:Z,params:X}=this.buildSelect(),_=$.query(Z).all(...X);return this.hydrateRows(_)}first(){return this._limit=1,this.get()[0]}count(){let $=V0(),Z=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,X=[this.parentId];for(let _ of this._pivotWheres)Z+=` AND ${_.sql}`,X.push(..._.params);return $.query(Z).get(...X).count}exists(){return this.count()>0}now(){return new Date().toISOString()}attach($,Z={}){let X=V0(),_=Array.isArray($)?$:[$];if(_.length===0)return 0;let L=this._resolved.pivotTimestamps?this.now():null,j=0;for(let Y of _){let z={[this.fkParent]:this.parentId,[this.fkRelated]:Y,...Z};if(L){if(z.created_at===void 0)z.created_at=L;if(z.updated_at===void 0)z.updated_at=L}let F=Object.keys(z),E=F.map(()=>"?").join(", "),U=`INSERT INTO ${this.pivotTable} (${F.join(", ")}) VALUES (${E})`,V=F.map((Q)=>z[Q]);X.run(U,V),j++}return j}detach($){let Z=V0(),X=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,_=[this.parentId];if($!==void 0&&$!==null){let L=Array.isArray($)?$:[$];if(L.length===0)return 0;let j=L.map(()=>"?").join(", ");X+=` AND ${this.fkRelated} IN (${j})`,_.push(...L)}return Z.run(X,_).changes}updateExistingPivot($,Z){let X=V0(),_={...Z};if(this._resolved.pivotTimestamps&&_.updated_at===void 0)_.updated_at=this.now();let L=Object.keys(_);if(L.length===0)return 0;let j=L.map((F)=>`${F} = ?`).join(", "),Y=`UPDATE ${this.pivotTable} SET ${j} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,z=[...L.map((F)=>_[F]),this.parentId,$];return X.run(Y,z).changes}sync($){let Z=V0(),X=new Map;for(let E of $)if(E!=null&&typeof E==="object"&&"id"in E){let{id:U,...V}=E;X.set(U,V)}else X.set(E,{});let _=Z.query(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`).all(this.parentId),L=new Set(_.map((E)=>E[this.fkRelated])),j=[],Y=[],z=[],F=[...L].filter((E)=>!X.has(E));if(F.length>0)this.detach(F),Y.push(...F);for(let[E,U]of X)if(!L.has(E))this.attach(E,U),j.push(E);else if(Object.keys(U).length>0)this.updateExistingPivot(E,U),z.push(E);return{attached:j,detached:Y,updated:z}}toggle($){let Z=V0(),X=Array.isArray($)?$:[$];if(X.length===0)return{attached:[],detached:[]};let _=X.map(()=>"?").join(", "),L=Z.query(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${_})`).all(this.parentId,...X),j=new Set(L.map((F)=>F[this.fkRelated])),Y=X.filter((F)=>!j.has(F)),z=X.filter((F)=>j.has(F));if(Y.length>0)this.attach(Y);if(z.length>0)this.detach(z);return{attached:Y,detached:z}}}class r{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor($){this._definition=$}where($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"and"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"and"});return this}orWhere($,Z,X){if(X===void 0)this._wheres.push({column:$,operator:"=",value:Z,boolean:"or"});else this._wheres.push({column:$,operator:Z,value:X,boolean:"or"});return this}whereIn($,Z){return this._wheres.push({column:$,operator:"in",value:Z,boolean:"and"}),this}orWhereIn($,Z){return this._wheres.push({column:$,operator:"in",value:Z,boolean:"or"}),this}whereNotIn($,Z){return this._wheres.push({column:$,operator:"not in",value:Z,boolean:"and"}),this}orWhereNotIn($,Z){return this._wheres.push({column:$,operator:"not in",value:Z,boolean:"or"}),this}whereNull($){return this._wheres.push({column:$,operator:"=",value:null,boolean:"and"}),this}orWhereNull($){return this._wheres.push({column:$,operator:"=",value:null,boolean:"or"}),this}whereNotNull($){return this._wheres.push({column:$,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull($){return this._wheres.push({column:$,operator:"!=",value:null,boolean:"or"}),this}whereLike($,Z){return this._wheres.push({column:$,operator:"like",value:Z,boolean:"and"}),this}orWhereLike($,Z){return this._wheres.push({column:$,operator:"like",value:Z,boolean:"or"}),this}whereNotLike($,Z){return this._wheres.push({column:$,operator:"not like",value:Z,boolean:"and"}),this}orWhereNotLike($,Z){return this._wheres.push({column:$,operator:"not like",value:Z,boolean:"or"}),this}whereRaw($,...Z){return this._wheres.push({raw:$,rawParams:Z,boolean:"and"}),this}orWhereRaw($,...Z){return this._wheres.push({raw:$,rawParams:Z,boolean:"or"}),this}whereGroup($){return this._addGroup("and",$)}orWhereGroup($){return this._addGroup("or",$)}_addGroup($,Z){let X=new r(this._definition);if(Z(X),X._wheres.length===0)return this;let _=[],L=X.buildWhereClauses(_);if(!L)return this;return this._wheres.push({raw:`(${L})`,rawParams:_,boolean:$}),this}whereBetween($,Z){return this._wheres.push({column:$,operator:">=",value:Z[0],boolean:"and"}),this._wheres.push({column:$,operator:"<=",value:Z[1],boolean:"and"}),this}whereNotBetween($,Z){return this._wheres.push({column:$,operator:"<",value:Z[0],boolean:"and"}),this._wheres.push({column:$,operator:">",value:Z[1],boolean:"or"}),this}when($,Z){if($)return Z(this);return this}orderBy($,Z="asc"){return this._orderBy.push({column:$,direction:Z}),this}orderByDesc($){return this.orderBy($,"desc")}orderByAsc($){return this.orderBy($,"asc")}limit($){return this._limit=$,this}take($){return this.limit($)}offset($){return this._offset=$,this}skip($){return this.offset($)}select(...$){return this._select=$,this}with(...$){return this._withRelations=$,this}getWithRelations(){return this._withRelations}buildWhereClauses($){let Z=[];for(let X=0;X<this._wheres.length;X++){let _=this._wheres[X],L;if(_.raw){if(L=_.raw,_.rawParams&&_.rawParams.length>0)$.push(..._.rawParams)}else if(_.value===null)L=_.operator==="="?`${_.column} IS NULL`:`${_.column} IS NOT NULL`;else if(_.operator==="in"||_.operator==="not in"){let j=_.value;L=`${_.column} ${_.operator.toUpperCase()} (${j.map(()=>"?").join(", ")})`,$.push(...j)}else L=`${_.column} ${_.operator} ?`,$.push(_.value);Z.push(X===0?L:`${_.boolean.toUpperCase()} ${L}`)}return Z.join(" ")}buildQuery(){let $=[],Z=`SELECT ${this._select.join(", ")} FROM ${this._definition.table}`;if(this._wheres.length>0)Z+=` WHERE ${this.buildWhereClauses($)}`;if(this._orderBy.length>0)Z+=` ORDER BY ${this._orderBy.map((X)=>`${X.column} ${X.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Z+=` OFFSET ${this._offset}`;return{sql:Z,params:$}}toSql(){return this.buildQuery()}eagerLoadRelations($){if($.length===0||this._withRelations.length===0)return;let Z=V0(),X=this._definition.primaryKey||"id";for(let _ of this._withRelations){let L=`${this._definition.name}:${_}`,j=KZ.get(L);if(j===void 0)j=HX(this._definition,_),KZ.set(L,j);if(!j)continue;if(j.type==="hasMany"||j.type==="hasOne"){let Y=$.map((V)=>V.get(X)).filter((V)=>V!=null);if(Y.length===0)continue;let z=Y.map(()=>"?").join(", "),F=Z.query(`SELECT * FROM ${j.relatedTable} WHERE ${j.foreignKey} IN (${z})`).all(...Y),E=Y9(j.relatedModelName),U=E?.getDefinition?.()||E?.definition||this._definition;if(j.type==="hasMany"){let V=new Map;for(let Q of F){let O=Q[j.foreignKey];if(!V.has(O))V.set(O,[]);V.get(O).push(Q)}for(let Q of $){let O=V.get(Q.get(X))||[];Q.setRelation(_,O.map((K)=>new i0(U,K)))}}else{let V=new Map;for(let Q of F)V.set(Q[j.foreignKey],Q);for(let Q of $){let O=V.get(Q.get(X));Q.setRelation(_,O?new i0(U,O):null)}}}if(j.type==="belongsTo"){let Y=$.map((O)=>O._attributes[j.foreignKey]).filter((O)=>O!=null),z=[...new Set(Y)];if(z.length===0)continue;let F=z.map(()=>"?").join(", "),E=Z.query(`SELECT * FROM ${j.relatedTable} WHERE ${j.localKey} IN (${F})`).all(...z),U=Y9(j.relatedModelName),V=U?.getDefinition?.()||U?.definition||this._definition,Q=new Map;for(let O of E)Q.set(O[j.localKey],O);for(let O of $){let K=O._attributes[j.foreignKey],I=Q.get(K);O.setRelation(_,I?new i0(V,I):null)}}if(j.type==="belongsToMany"){let Y=$.map((D)=>D.get(X)).filter((D)=>D!=null);if(Y.length===0)continue;if(!j.pivotTable||!j.pivotFkParent||!j.pivotFkRelated)continue;let z=Y.map(()=>"?").join(", "),F=Z.query(`SELECT * FROM ${j.pivotTable} WHERE ${j.pivotFkParent} IN (${z})`).all(...Y);if(F.length===0){for(let D of $)D.setRelation(_,[]);continue}let E=[...new Set(F.map((D)=>D[j.pivotFkRelated]))].filter((D)=>D!=null),U=Y9(j.relatedModelName),V=U?.getDefinition?.()||U?.definition||this._definition,Q=V?.primaryKey||"id",O=[];if(E.length>0){let D=E.map(()=>"?").join(", ");O=Z.query(`SELECT * FROM ${j.relatedTable} WHERE ${Q} IN (${D})`).all(...E)}let K=new Map;for(let D of O)K.set(D[Q],D);let I=new Map;for(let D of F){let M=D[j.pivotFkParent];if(!I.has(M))I.set(M,[]);I.get(M).push(D)}let C=new Set([j.pivotFkParent,j.pivotFkRelated]);for(let D of $){let M=D.get(X),N=(I.get(M)||[]).map((T)=>{let v=K.get(T[j.pivotFkRelated]);if(!v)return null;let b=new i0(V,v),f={};for(let[p,g]of Object.entries(T))if(!C.has(p))f[p]=g;return b.pivot=f,b}).filter((T)=>T!==null);D.setRelation(_,N)}}}}get(){let $=V0(),{sql:Z,params:X}=this.buildQuery(),L=$.query(Z).all(...X).map((j)=>new i0(this._definition,j));if(this._withRelations.length>0)this.eagerLoadRelations(L);return L}first(){return this._limit=1,this.get()[0]}firstOrFail(){let $=this.first();if(!$)throw Error(`No ${this._definition.name} found`);return $}last(){let $=this._definition.primaryKey||"id";return this._orderBy=[{column:$,direction:"desc"}],this._limit=1,this.get()[0]}count(){let $=V0(),Z=[],X=`SELECT COUNT(*) as count FROM ${this._definition.table}`;if(this._wheres.length>0)X+=` WHERE ${this.buildWhereClauses(Z)}`;return $.query(X).get(...Z).count}exists(){return this.count()>0}doesntExist(){return this.count()===0}sole(){this._limit=2;let $=this.get();if($.length===0)throw Error(`No ${this._definition.name} found`);if($.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return $[0]}increment($,Z=1){let X=V0(),_=[Z],L=`UPDATE ${this._definition.table} SET ${$} = ${$} + ?`;if(this._definition.traits?.useTimestamps)L+=", updated_at = ?",_.push(new Date().toISOString());if(this._wheres.length>0){let j=this.buildWhereClauses(_);L+=` WHERE ${j}`}return X.run(L,_).changes}decrement($,Z=1){return this.increment($,-Z)}chunk($,Z){let X=0;while(!0){let _=new r(this._definition);_._wheres=[...this._wheres],_._orderBy=[...this._orderBy],_._select=[...this._select],_._withRelations=[...this._withRelations],_._limit=$,_._offset=X*$;let L=_.get();if(L.length===0)break;if(Z(L)===!1)break;if(L.length<$)break;X++}}paginate($=1,Z=15){let X=this.count(),_=Math.ceil(X/Z);this._limit=Z,this._offset=($-1)*Z;let L=this.get();return{data:L,total:X,page:$,perPage:Z,lastPage:_,hasMorePages:$<_,isEmpty:L.length===0,from:L.length>0?($-1)*Z+1:null,to:L.length>0?($-1)*Z+L.length:null}}pluck($){let Z=V0(),X=[],_=`SELECT ${$} FROM ${this._definition.table}`;if(this._wheres.length>0)_+=` WHERE ${this.buildWhereClauses(X)}`;if(this._orderBy.length>0)_+=` ORDER BY ${this._orderBy.map((j)=>`${j.column} ${j.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)_+=` LIMIT ${this._limit}`;if(this._offset!==void 0)_+=` OFFSET ${this._offset}`;return Z.query(_).all(...X).map((j)=>j[$])}aggregate($,Z){let X=V0(),_=[],L=`SELECT ${$}(${Z}) as v FROM ${this._definition.table}`;if(this._wheres.length>0)L+=` WHERE ${this.buildWhereClauses(_)}`;return X.query(L).get(..._)?.v??null}max($){return this.aggregate("MAX",$)}min($){return this.aggregate("MIN",$)}avg($){return this.aggregate("AVG",$)||0}sum($){return this.aggregate("SUM",$)||0}delete(){let $=V0(),Z=[],X=`DELETE FROM ${this._definition.table}`;if(this._wheres.length>0)X+=` WHERE ${this.buildWhereClauses(Z)}`;return $.run(X,Z).changes}update($){let Z=V0(),X=Object.entries($),_=X.map(([Y])=>`${Y} = ?`).join(", "),L=X.map(([,Y])=>Y);if(this._definition.traits?.useTimestamps)L.push(new Date().toISOString());let j=`UPDATE ${this._definition.table} SET ${_}${this._definition.traits?.useTimestamps?", updated_at = ?":""}`;if(this._wheres.length>0)j+=` WHERE ${this.buildWhereClauses(L)}`;return Z.run(j,L).changes}}function TF($){let Z={query:()=>new r($),where(X,_,L){return new r($).where(X,_,L)},orWhere(X,_,L){return new r($).orWhere(X,_,L)},whereIn(X,_){return new r($).whereIn(X,_)},whereNotIn(X,_){return new r($).whereNotIn(X,_)},whereNull(X){return new r($).whereNull(X)},whereNotNull(X){return new r($).whereNotNull(X)},whereLike(X,_){return new r($).whereLike(X,_)},orderBy(X,_="asc"){return new r($).orderBy(X,_)},orderByDesc(X){return new r($).orderByDesc(X)},select(...X){return new r($).select(...X)},with(...X){return new r($).with(...X)},limit:(X)=>new r($).limit(X),take:(X)=>new r($).take(X),skip:(X)=>new r($).skip(X),find(X){let _=V0(),L=$.primaryKey||"id",j=`SELECT * FROM ${$.table} WHERE ${L} = ?`,Y=c$.get(j);if(!Y)Y=_.prepare(j),c$.set(j,Y);let z=Y.get(X);return z?new i0($,z):void 0},findOrFail(X){let _=Z.find(X);if(!_)throw Error(`${$.name} with id ${X} not found`);return _},findMany(X){let _=V0(),L=$.primaryKey||"id";return _.query(`SELECT * FROM ${$.table} WHERE ${L} IN (${X.map(()=>"?").join(", ")})`).all(...X).map((Y)=>new i0($,Y))},all:()=>new r($).get(),first:()=>new r($).first(),firstOrFail:()=>new r($).firstOrFail(),last:()=>new r($).last(),count:()=>new r($).count(),exists:()=>new r($).exists(),doesntExist:()=>new r($).doesntExist(),paginate:(X,_)=>new r($).paginate(X,_),whereBetween(X,_){return new r($).whereBetween(X,_)},whereNotBetween(X,_){return new r($).whereNotBetween(X,_)},create(X){let _=new i0($,X);return _.save(),_},createMany(X){return X.map((_)=>this.create(_))},updateOrCreate(X,_){let L=new r($);for(let[Y,z]of Object.entries(X))L=L.where(Y,z);let j=L.first();if(j)return j.update(_),j;return this.create({...X,..._})},firstOrCreate(X,_){let L=new r($);for(let[Y,z]of Object.entries(X))L=L.where(Y,z);return L.first()||this.create({...X,..._})},destroy(X){let _=V0(),L=$.primaryKey||"id";return _.run(`DELETE FROM ${$.table} WHERE ${L} = ?`,[X]).changes>0},remove(X){return this.destroy(X)},truncate(){V0().run(`DELETE FROM ${$.table}`)},getDefinition:()=>$,getTable:()=>$.table,make(X={}){return new i0($,X)},latest:(X="created_at")=>new r($).orderByDesc(X),oldest:(X="created_at")=>new r($).orderBy(X,"asc"),max:(X)=>new r($).max(X),min:(X)=>new r($).min(X),avg:(X)=>new r($).avg(X),sum:(X)=>new r($).sum(X),pluck(X){return new r($).pluck(X)}};return new Proxy(Z,{get(X,_){if(typeof _==="string"&&_.startsWith("where")&&_.length>5){let L=_.slice(5),j=L.charAt(0).toLowerCase()+L.slice(1);if(j in $.attributes||j==="id"||j===$.primaryKey)return(Y)=>new r($).where(j,Y)}return Reflect.get(X,_)}})}function VQ($){let Z=V0(),X=$.primaryKey||"id",_=[];if(_.push($.autoIncrement!==!1?`${X} INTEGER PRIMARY KEY AUTOINCREMENT`:`${X} INTEGER PRIMARY KEY`),$.traits?.useUuid)_.push("uuid TEXT UNIQUE");for(let[L,j]of Object.entries($.attributes)){let Y="TEXT";if(j.type==="number")Y="INTEGER";else if(j.type==="boolean")Y="INTEGER";if(L.endsWith("_id"))Y="INTEGER";let z=`${L} ${Y}`;if(j.unique)z+=" UNIQUE";if(typeof j.foreignKey==="object"&&j.foreignKey!==null){let F=j.foreignKey;if(z+=` REFERENCES ${F.table}(${F.column??"id"})`,F.onDelete)z+=` ON DELETE ${F.onDelete.toUpperCase()}`;if(F.onUpdate)z+=` ON UPDATE ${F.onUpdate.toUpperCase()}`}_.push(z)}if($.traits?.useTimestamps)_.push("created_at TEXT","updated_at TEXT");if($.traits?.useSoftDeletes)_.push("deleted_at TEXT");Z.run(`CREATE TABLE IF NOT EXISTS ${$.table} (${_.join(", ")})`)}function kF($){return new Proxy($,{get(Z,X){if(X==="location")return Z.address;if(X==="datatype"){let{random:_,number:L,string:j}=Z;return{boolean:()=>_?.boolean?.(),number:(Y)=>L?.int?.(Y),float:(Y)=>L?.float?.(Y),uuid:()=>crypto.randomUUID(),string:(Y)=>j?.alphanumeric?.(Y??10)}}return Z[X]}})}async function GQ($,Z,X){let _=V0(),L=$.traits?.useSeeder,j=Z??(typeof L==="object"&&L?L.count:10);if(!X)try{let Y=await NF().then(()=>qX);X=kF(Y.faker)}catch{console.warn("ts-mocker not found. Install it for seeding support.");return}for(let Y=0;Y<j;Y++){let z={};for(let[E,U]of Object.entries($.attributes))if(U.factory)z[E]=U.factory(X);if($.traits?.useTimestamps){let E=new Date().toISOString();z.created_at=E,z.updated_at=E}if($.traits?.useUuid)z.uuid=crypto.randomUUID();let F=Object.keys(z);_.run(`INSERT INTO ${$.table} (${F.join(", ")}) VALUES (${F.map(()=>"?").join(", ")})`,Object.values(z))}}var b1=null,r8=null,VZ,GZ,KZ,c$,PX=n(()=>{VZ=new Map,GZ=new Map,KZ=new Map,c$=new Map}),TX={};IZ(TX,{registerBrowserModels:()=>fF,hasModel:()=>yF,getModelRegistry:()=>hF,getModel:()=>xF,getAllModels:()=>BF,defineModel:()=>bF,clearModelRegistry:()=>AF});function xF($){return d9.get($)}function BF(){return[...d9.values()]}function hF(){return Object.fromEntries(d9)}function yF($){return d9.has($)}function AF(){d9.clear()}function vF(){return typeof window<"u"&&typeof document<"u"}function bF($){let Z;if(vF())Z=aX($);else{let X=TF($);Z=Object.assign(X,{definition:$,getDefinition:()=>$,getTable:()=>$.table,getName:()=>$.name})}return d9.set($.name,Z),Z}function fF($){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...$}}var d9,Y$=n(()=>{u7(),PX(),d9=new Map});class I8{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor($){this.driver=V8($.config),this.client=$.client,this.tableName=$.config.tableName??""}table($){return this.tableName=$,this}index($){return this.indexName=$,this}entity($){return this.entityType=$,this}whereKey($,Z,X){return this.keyConditions.push({attribute:$,operator:Z,value:X}),this}wherePartitionKey($,Z){return this.whereKey($,"=",Z)}whereSortKey($,Z){return this.whereKey($,"=",Z)}whereSortKeyBeginsWith($,Z){return this.keyConditions.push({attribute:$,operator:"begins_with",value:Z}),this}whereSortKeyBetween($,Z,X){return this.keyConditions.push({attribute:$,operator:"BETWEEN",values:[Z,X]}),this}where($,Z,X){return this.filterConditions.push({attribute:$,operator:Z,value:X}),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,X){return this.filterConditions.push({attribute:$,operator:"BETWEEN",values:[Z,X]}),this}whereBeginsWith($,Z){return this.filterConditions.push({attribute:$,operator:"begins_with",value:Z}),this}whereContains($,Z){return this.where($,"contains",Z)}whereExists($){return this.where($,"attribute_exists")}whereNotExists($){return this.where($,"attribute_not_exists")}whereIn($,Z){return this.filterConditions.push({attribute:$,operator:"IN",values:Z}),this}select(...$){return this.projectionAttrs.push(...$),this}limit($){return this.limitValue=$,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead($=!0){return this.consistentReadValue=$,this}startFrom($){return this.startKey=$,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 $=this.buildQueryParams(),Z={TableName:$.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if($.indexName)Z.IndexName=$.indexName;let X=0;if($.keyConditions.length>0){let _=[];for(let L of $.keyConditions){let j=`#key${X}`;if(Z.ExpressionAttributeNames[j]=L.attribute,L.operator==="begins_with"){let Y=`:keyval${X}`;Z.ExpressionAttributeValues[Y]=this.driver.marshall({v:L.value}).v,_.push(`begins_with(${j}, ${Y})`)}else if(L.operator==="BETWEEN"){let Y=`:keyval${X}a`,z=`:keyval${X}b`;Z.ExpressionAttributeValues[Y]=this.driver.marshall({v:L.values?.[0]}).v,Z.ExpressionAttributeValues[z]=this.driver.marshall({v:L.values?.[1]}).v,_.push(`${j} BETWEEN ${Y} AND ${z}`)}else{let Y=`:keyval${X}`;Z.ExpressionAttributeValues[Y]=this.driver.marshall({v:L.value}).v,_.push(`${j} ${L.operator} ${Y}`)}X++}Z.KeyConditionExpression=_.join(" AND ")}if($.filterConditions&&$.filterConditions.length>0){let _=[];for(let L of $.filterConditions){let j=`#flt${X}`;if(Z.ExpressionAttributeNames[j]=L.attribute,L.operator==="attribute_exists")_.push(`attribute_exists(${j})`);else if(L.operator==="attribute_not_exists")_.push(`attribute_not_exists(${j})`);else if(L.operator==="begins_with"||L.operator==="contains"){let Y=`:fltval${X}`;Z.ExpressionAttributeValues[Y]=this.driver.marshall({v:L.value}).v,_.push(`${L.operator}(${j}, ${Y})`)}else if(L.operator==="BETWEEN"){let Y=`:fltval${X}a`,z=`:fltval${X}b`;Z.ExpressionAttributeValues[Y]=this.driver.marshall({v:L.values?.[0]}).v,Z.ExpressionAttributeValues[z]=this.driver.marshall({v:L.values?.[1]}).v,_.push(`${j} BETWEEN ${Y} AND ${z}`)}else if(L.operator==="IN"){let Y=(L.values??[]).map((z,F)=>`:fltval${X}_${F}`);L.values?.forEach((z,F)=>{Z.ExpressionAttributeValues[`:fltval${X}_${F}`]=this.driver.marshall({v:z}).v}),_.push(`${j} IN (${Y.join(", ")})`)}else{let Y=`:fltval${X}`;Z.ExpressionAttributeValues[Y]=this.driver.marshall({v:L.value}).v,_.push(`${j} ${L.operator} ${Y}`)}X++}Z.FilterExpression=_.join(" AND ")}if($.projectionAttributes&&$.projectionAttributes.length>0){let _=[];for(let L of $.projectionAttributes){let j=`#proj${X}`;Z.ExpressionAttributeNames[j]=L,_.push(j),X++}Z.ProjectionExpression=_.join(", ")}if($.limit!==void 0)Z.Limit=$.limit;if($.scanIndexForward!==void 0)Z.ScanIndexForward=$.scanIndexForward;if($.exclusiveStartKey)Z.ExclusiveStartKey=this.driver.marshall($.exclusiveStartKey);if($.consistentRead)Z.ConsistentRead=$.consistentRead;if(Object.keys(Z.ExpressionAttributeNames).length===0)delete Z.ExpressionAttributeNames;if(Object.keys(Z.ExpressionAttributeValues).length===0)delete Z.ExpressionAttributeValues;return Z}toScanRequest(){let $=this.buildScanParams(),Z={TableName:$.tableName};if($.indexName)Z.IndexName=$.indexName;if($.filterConditions&&$.filterConditions.length>0){let{expression:X,expressionAttributeNames:_,expressionAttributeValues:L}=this.driver.buildFilterExpression($.filterConditions);Z.FilterExpression=X,Z.ExpressionAttributeNames=_,Z.ExpressionAttributeValues=L}if($.projectionAttributes&&$.projectionAttributes.length>0){let{expression:X,expressionAttributeNames:_}=this.driver.buildProjectionExpression($.projectionAttributes);Z.ProjectionExpression=X,Z.ExpressionAttributeNames={...Z.ExpressionAttributeNames,..._}}if($.limit!==void 0)Z.Limit=$.limit;if($.exclusiveStartKey)Z.ExclusiveStartKey=this.driver.marshall($.exclusiveStartKey);if($.consistentRead)Z.ConsistentRead=$.consistentRead;return Z}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 $=this.toQueryRequest(),Z=await this.client.query($);return{items:Z.Items?.map((X)=>this.driver.unmarshall(X)),count:Z.Count,scannedCount:Z.ScannedCount,lastEvaluatedKey:Z.LastEvaluatedKey?this.driver.unmarshall(Z.LastEvaluatedKey):void 0,consumedCapacity:Z.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 $=this.toScanRequest(),Z=await this.client.scan($);return{items:Z.Items?.map((X)=>this.driver.unmarshall(X)),count:Z.Count,scannedCount:Z.ScannedCount,lastEvaluatedKey:Z.LastEvaluatedKey?this.driver.unmarshall(Z.LastEvaluatedKey):void 0,consumedCapacity:Z.ConsumedCapacity}}async getAll(){let $=[],Z;do{if(Z)this.startFrom(Z);let X=this.keyConditions.length>0?await this.query():await this.scan();if(X.items)$.push(...X.items);Z=X.lastEvaluatedKey}while(Z);return $}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 $=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return $.Select="COUNT",(this.keyConditions.length>0?await this.client.query($):await this.client.scan($)).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 P9{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor($){this.driver=V8($.config),this.client=$.client,this.tableName=$.config.tableName??""}table($){return this.tableName=$,this}key($){return this.keyData=$,this}item($){return this.itemData=$,this}set($,Z){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[$]=Z,this}setMany($){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,$),this}remove($){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push($),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($){return this.conditionExpr=$,this}ifNotExists($="pk"){return this.conditionExpr=`attribute_not_exists(${$})`,this}ifExists($="pk"){return this.conditionExpr=`attribute_exists(${$})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let $={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)$.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")$.ReturnValues=this.returnValuesOption;return $}toUpdateRequest(){let $={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:Z,expressionAttributeNames:X,expressionAttributeValues:_}=this.driver.buildUpdateExpression(this.updateExpressions);if(Z)$.UpdateExpression=Z,$.ExpressionAttributeNames=X,$.ExpressionAttributeValues=_;if(this.conditionExpr)$.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")$.ReturnValues=this.returnValuesOption;return $}toDeleteRequest(){let $={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)$.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")$.ReturnValues=this.returnValuesOption;return $}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toPutRequest(),Z=await this.client.putItem($);if(Z.Attributes)return this.driver.unmarshall(Z.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toUpdateRequest(),Z=await this.client.updateItem($);if(Z.Attributes)return this.driver.unmarshall(Z.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toDeleteRequest(),Z=await this.client.deleteItem($);if(Z.Attributes)return this.driver.unmarshall(Z.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toGetRequest(),Z=await this.client.getItem($);if(Z.Item)return this.driver.unmarshall(Z.Item);return}}function KQ($){return new I8($)}function IQ($){return new P9($)}function WQ($){let Z=V8($.config);return{query:()=>new I8($),item:()=>new P9($),driver:Z,registerEntity:(X)=>Z.registerEntity(X),buildKey:(X,_)=>Z.buildPrimaryKey(X,_)}}var kZ=()=>{};class kX{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor($){this.config=$,this.pkAttribute=$.pkAttribute??"pk",this.skAttribute=$.skAttribute??"sk",this.typeAttribute=$.typeAttribute??"_type";for(let Z of $.entities)this.entities.set(Z.name,Z)}getEntity($){return this.entities.get($)}registerEntity($){this.entities.set($.name,$)}buildKey($,Z){let X=this.entities.get($);if(!X)throw Error(`Entity not found: ${$}`);let _=this.interpolatePattern(X.pkPattern,Z),L=this.interpolatePattern(X.skPattern,Z);return{pk:_,sk:L}}buildGSIKey($,Z,X){let _=this.entities.get($);if(!_)throw Error(`Entity not found: ${$}`);let L=_.indexes?.find((z)=>z.name===Z);if(!L)throw Error(`GSI not found: ${Z} for entity ${$}`);let j=this.interpolatePattern(L.pkPattern,X),Y=L.skPattern?this.interpolatePattern(L.skPattern,X):void 0;return{pk:j,sk:Y}}createItem($,Z){let{pk:X,sk:_}=this.buildKey($,Z),L=this.entities.get($),j={[this.pkAttribute]:X,[this.skAttribute]:_,[this.typeAttribute]:$,...Z};if(L.indexes)for(let Y of L.indexes){let z=this.buildGSIKey($,Y.name,Z),F=this.config.indexes?.find((E)=>E.name===Y.name);if(F){if(j[F.pkAttribute]=z.pk,F.skAttribute&&z.sk)j[F.skAttribute]=z.sk}}return j}parseEntityType($){if($[this.typeAttribute])return $[this.typeAttribute];let Z=$[this.pkAttribute];if(!Z)return;for(let[X,_]of this.entities){let L=_.pkPattern.split("${")[0];if(Z.startsWith(L))return X}return}parseItem($){let Z=this.parseEntityType($);if(!Z)return;let{[this.pkAttribute]:X,[this.skAttribute]:_,[this.typeAttribute]:L,...j}=$;return{type:Z,data:j}}getEntityPrefix($){let Z=this.entities.get($);if(!Z)throw Error(`Entity not found: ${$}`);return Z.pkPattern.split("${")[0]}generateTableDefinition(){let $=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],Z=[];if(this.config.indexes)for(let X of this.config.indexes){if(!$.find((_)=>_.name===X.pkAttribute))$.push({name:X.pkAttribute,type:"S"});if(X.skAttribute&&!$.find((_)=>_.name===X.skAttribute))$.push({name:X.skAttribute,type:"S"});Z.push({indexName:X.name,keySchema:{partitionKey:X.pkAttribute,sortKey:X.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:$,globalSecondaryIndexes:Z.length>0?Z:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern($,Z){return $.replace(/\$\{(\w+)\}/g,(X,_)=>{if(!(_ in Z))throw Error(`Missing value for pattern key: ${_}`);return String(Z[_])})}}class xX{manager;entityName;options;constructor($,Z,X){this.manager=$,this.entityName=Z,this.options=X}async create($){let Z=this.manager.createItem(this.entityName,$),X=new P9(this.options).table(this.options.config.tableName).item(Z).ifNotExists("pk");if(this.options.client)await X.put();return $}async get($){let{pk:Z,sk:X}=this.manager.buildKey(this.entityName,$),_=new P9(this.options).table(this.options.config.tableName).key({pk:Z,sk:X});if(!this.options.client)throw Error("DynamoDB client not provided");let L=await _.get();if(!L)return;return this.manager.parseItem(L)?.data}async update($,Z){let{pk:X,sk:_}=this.manager.buildKey(this.entityName,$),L=new P9(this.options).table(this.options.config.tableName).key({pk:X,sk:_}).setMany(Z).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let j=await L.update();if(!j)return;return this.manager.parseItem(j)?.data}async delete($){let{pk:Z,sk:X}=this.manager.buildKey(this.entityName,$),_=new P9(this.options).table(this.options.config.tableName).key({pk:Z,sk:X});if(!this.options.client)throw Error("DynamoDB client not provided");return await _.delete(),!0}query(){return new BX(this.manager,this.entityName,this.options)}async findAll(){let $=this.manager.typeAttribute??"_type",Z=new I8(this.options).table(this.options.config.tableName).whereEquals($,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await Z.getAll()).map((_)=>this.manager.parseItem(_)).filter((_)=>_!==void 0).map((_)=>_.data)}}class BX{manager;entityName;options;builder;pkValue;skConditions=[];constructor($,Z,X){this.manager=$,this.entityName=Z,this.options=X,this.builder=new I8(X).table(X.config.tableName)}wherePartitionKey($){let{pk:Z}=this.manager.buildKey(this.entityName,$);this.pkValue=Z;let X=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(X,Z),this}whereSortKey($){let{sk:Z}=this.manager.buildKey(this.entityName,$),X=this.manager.skAttribute??"sk";return this.builder.whereSortKey(X,Z),this}whereSortKeyBeginsWith($){let Z=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(Z,$),this}useIndex($,Z){let X=this.manager.buildGSIKey(this.entityName,$,Z),_=this.manager.config.indexes?.find((L)=>L.name===$);if(!_)throw Error(`GSI configuration not found: ${$}`);return this.builder.index($),this.builder.wherePartitionKey(_.pkAttribute,X.pk),this}where($,Z,X){return this.builder.where($,Z,X),this}select(...$){return this.builder.select(...$),this}limit($){return this.builder.limit($),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((Z)=>this.manager.parseItem(Z)).filter((Z)=>Z!==void 0).map((Z)=>Z.data)}async first(){return this.limit(1),(await this.execute())[0]}}function gF($){return new kX($)}function pF($,Z,X){return new xX($,Z,X)}var dF,hX=n(()=>{kZ(),dF={simpleEntity:($,Z="id")=>({name:$,pkPattern:`${$.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]}),oneToMany:($,Z,X="id",_="id")=>({parent:{name:$,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:"METADATA",keyFields:[X]},child:{name:Z,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:`${Z.toUpperCase()}#\${${_}}`,keyFields:[X,_]}}),manyToMany:($,Z,X="id",_="relatedId")=>({entity:{name:$,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:"METADATA",keyFields:[X]},relation:{name:Z,pkPattern:`${$.toUpperCase()}#\${${X}}`,skPattern:`${Z.toUpperCase()}#\${${_}}`,keyFields:[X,_],indexes:[{name:"GSI1",pkPattern:`${$.toUpperCase()}#\${${_}}`,skPattern:`${Z.toUpperCase()}#\${${X}}`}]}}),hierarchical:($,Z="rootId",X="path")=>({name:$,pkPattern:`ROOT#\${${Z}}`,skPattern:`PATH#\${${X}}`,keyFields:[Z,X]})}});function v7($,Z){let X={};for(let[_,L]of Object.entries($))if(L)X[_]=L.replace(/\{([^}]+)\}/g,(j,Y)=>{return Z[Y]!==void 0?String(Z[Y]):`{${Y}}`});return X}async function cF($){return{models:new Map}}function DQ($){return $}function SQ($){return $}function MQ($){return $}function RQ($){return $}class yX{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor($){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...$};let Z={region:$.region,endpoint:$.endpoint,credentials:$.credentials,tableName:$.tableName};this.driver=V8(Z);let X={tableName:$.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=gF(X),this.queryBuilderOptions={config:Z}}setClient($){return this.queryBuilderOptions.client=$,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let $=await cF({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),Z=[];for(let[,X]of $.models)this.registerParsedModel(X),Z.push(X);return Z}registerModel($){let Z=this.parseWithTooling($);return this.registerParsedModel(Z)}registerParsedModel($){this.models.set($.name,$);let Z=this.toSingleTableEntity($);this.singleTableManager.registerEntity(Z);let X=this.toEntityMapping($);return this.driver.registerEntity(X),$}registerModels($){return $.map((Z)=>this.registerModel(Z))}getModel($){return this.models.get($)}getAllModels(){return Array.from(this.models.values())}repository($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return pF(this.singleTableManager,$,this.queryBuilderOptions)}query($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return new I8(this.queryBuilderOptions).table(this.config.tableName).entity($)}item($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return new P9(this.queryBuilderOptions).table(this.config.tableName)}buildKey($,Z){let X=this.models.get($);if(!X)throw Error(`Model not found: ${$}`);let _=v7(X.keyPatterns,Z);return{pk:_.pk,sk:_.sk}}createItem($,Z){let X=this.models.get($);if(!X)throw Error(`Model not found: ${$}`);let _=v7(X.keyPatterns,Z),L=_.pk,j=_.sk,Y={[this.config.pkAttribute]:L,[this.config.skAttribute]:j,[this.config.entityTypeAttribute]:X.name,...Z};if(X.hasTimestamps){let z=new Date().toISOString();if(!Y.createdAt)Y.createdAt=z;Y.updatedAt=z}if(X.hasVersioning){if(!Y._v)Y._v=1}return Y}parseItem($){let Z=$[this.config.entityTypeAttribute];if(!Z)return;let{[this.config.pkAttribute]:X,[this.config.skAttribute]:_,[this.config.entityTypeAttribute]:L,...j}=$;return{type:Z,data:j}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns($){let Z=this.models.get($);if(!Z)throw Error(`Model not found: ${$}`);return Z.accessPatterns}parseWithTooling($){let Z=$.name.toUpperCase(),X=$.primaryKey??"id",_=this.config.keyDelimiter,L=this.parseAttributes($),j=this.parseRelationships($,X),Y={pk:`${Z}${_}{${X}}`,sk:`${Z}${_}{${X}}`,...this.deriveGSIKeyPatterns(Z,X,_,j)},z=this.deriveAccessPatterns($.name,Z,X,j);return{name:$.name,entityType:Z,primaryKey:X,attributes:L,relationships:j,keyPatterns:Y,accessPatterns:z,traits:$.traits??{},hasTimestamps:$.traits?.useTimestamps??!1,hasSoftDeletes:$.traits?.useSoftDeletes??!1,hasUuid:$.traits?.useUuid??!1,hasTtl:$.traits?.useTtl??!1,hasVersioning:$.traits?.useVersioning??!1,original:$}}parseAttributes($){let Z=[];if(Z.push({name:$.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),$.attributes)for(let[X,_]of Object.entries($.attributes))Z.push({name:X,fillable:_.fillable??!0,required:_.required??!1,nullable:_.nullable??!0,unique:_.unique??!1,hidden:_.hidden??!1,defaultValue:_.default,cast:_.cast,dynamoDbType:this.inferDynamoDBType(_)});if($.traits?.useTimestamps)Z.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($.traits?.useSoftDeletes)Z.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return Z}inferDynamoDBType($){if($.cast){let Z=$.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(Z))return"N";if(["boolean","bool"].includes(Z))return"BOOL";if(["array","list"].includes(Z))return"L";if(["object","json","map"].includes(Z))return"M"}if($.validation?.rule){let Z=String($.validation.rule);if(Z.includes("integer")||Z.includes("numeric")||Z.includes("number"))return"N";if(Z.includes("boolean"))return"BOOL";if(Z.includes("array"))return"L";if(Z.includes("object"))return"M"}return"S"}parseRelationships($,Z){let X=[];if($.hasOne)for(let _ of $.hasOne)X.push({type:"hasOne",relatedModel:_,foreignKey:`${$.name.toLowerCase()}Id`,localKey:Z,requiresGsi:!0});if($.hasMany)for(let _ of $.hasMany)X.push({type:"hasMany",relatedModel:_,foreignKey:`${$.name.toLowerCase()}Id`,localKey:Z,requiresGsi:!1});if($.belongsTo)for(let _ of $.belongsTo)X.push({type:"belongsTo",relatedModel:_,foreignKey:`${_.toLowerCase()}Id`,localKey:Z,requiresGsi:!0});if($.belongsToMany){let _=Array.isArray($.belongsToMany)?$.belongsToMany:Object.values($.belongsToMany);for(let L of _){let j=typeof L==="string"?L:L?.model;if(!j)continue;let Y=[$.name,j].sort();X.push({type:"belongsToMany",relatedModel:j,foreignKey:`${$.name.toLowerCase()}Id`,localKey:Z,pivotEntity:Y.join(""),requiresGsi:!0})}}return X}deriveGSIKeyPatterns($,Z,X,_){let L={},j=1;for(let Y of _)if(Y.requiresGsi&&j<=5)L[`gsi${j}pk`]=`${Y.relatedModel.toUpperCase()}${X}{${Y.foreignKey}}`,L[`gsi${j}sk`]=`${$}${X}{${Z}}`,Y.gsiIndex=j,j++;return L}deriveAccessPatterns($,Z,X,_){let L=[];L.push({name:`Get ${$} by ID`,description:`Retrieve a single ${$} by its primary key`,entityType:Z,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${Z}#123`,exampleSk:`${Z}#123`,efficient:!0}),L.push({name:`List all ${$}s`,description:`Scan all ${$} entities`,entityType:Z,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:Z,efficient:!1});for(let j of _){if(j.type==="hasMany")L.push({name:`Get ${j.relatedModel}s for ${$}`,description:`Query ${j.relatedModel}s related to a ${$}`,entityType:Z,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${Z}#123`,exampleSk:`${j.relatedModel.toUpperCase()}#`,efficient:!0});if(j.gsiIndex){let Y=`GSI${j.gsiIndex}`;L.push({name:`Get ${$}s by ${j.relatedModel}`,description:`Query ${$}s by their related ${j.relatedModel}`,entityType:Z,operation:"query",index:Y,keyCondition:`gsi${j.gsiIndex}pk = :pk`,examplePk:`${j.relatedModel.toUpperCase()}#123`,efficient:!0})}}return L}toSingleTableEntity($){let Z=this.extractKeyFields($.keyPatterns.pk);return{name:$.name,pkPattern:$.keyPatterns.pk,skPattern:$.keyPatterns.sk,keyFields:Z,indexes:this.extractGSIPatterns($.keyPatterns)}}extractKeyFields($){let Z=$.match(/\{([^}]+)\}/g);if(!Z)return[];return Z.map((X)=>X.slice(1,-1))}extractGSIPatterns($){let Z=[];for(let X=1;X<=5;X++){let _=`gsi${X}pk`,L=`gsi${X}sk`;if($[_])Z.push({name:`GSI${X}`,pkPattern:$[_],skPattern:$[L]})}return Z.length>0?Z:void 0}toEntityMapping($){return{entityType:$.name,pkPattern:$.keyPatterns.pk,skPattern:$.keyPatterns.sk}}buildGSIConfig(){let $=this.config.gsiConfig??{},Z=[];if($.gsi1pk)Z.push({name:"GSI1",pkAttribute:$.gsi1pk,skAttribute:$.gsi1sk});if($.gsi2pk)Z.push({name:"GSI2",pkAttribute:$.gsi2pk,skAttribute:$.gsi2sk});if($.gsi3pk)Z.push({name:"GSI3",pkAttribute:$.gsi3pk,skAttribute:$.gsi3sk});return Z}}function JQ($){return new yX($)}function CQ($){return $.accessPatterns}function wQ($,Z="#"){let X=$.name.toUpperCase(),_=$.primaryKey??"id";return{name:$.name,pkPattern:`${X}${Z}\${${_}}`,skPattern:`${X}${Z}\${${_}}`}}var mF=n(()=>{kZ(),hX()});function AX($){let Z={};for(let X of Object.keys($)){let _=$[X],L=_.definition??_.getDefinition?.()??_,j=L.table||`${String(L.name).toLowerCase()}s`,Y=L.attributes??{},z={};for(let F of Object.keys(Y))z[F]=void 0;Z[j]={columns:z,primaryKey:L.primaryKey??"id"}}return Z}async function W8($){let Z=$.cwd??sF.cwd(),X=$.modelsDir.startsWith("/")?$.modelsDir:`${Z}/${$.modelsDir}`,_={},L=uF(X);for(let j of L){let Y=`${X}/${j}`;if(nF(Y).isDirectory())continue;let F=lF(Y);if(![".ts",".mts",".cts",".js",".mjs",".cjs"].includes(F))continue;let E=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,U=await import(`${Y}${E}`),V=U.default??U,Q=V.definition??V.getDefinition?.()??V,O=iF(j,F),K=Q.name??O;_[K]={...Q,name:K}}return _}var oF=()=>{};function rF($){let Z={},X={},_={},L={},j={};for(let Y of Object.keys($)){let z=$[Y],F=z.definition??z.getDefinition?.()??z,E=F.table||`${String(F.name).toLowerCase()}s`;Z[Y]=E,X[E]=Y,_[E]=F.primaryKey??"id";let U=(O)=>{if(!O)return{};if(Array.isArray(O)){let K={};for(let I of O)K[I]=I;return K}return O},V=(O)=>{if(!O)return{};if(Array.isArray(O)){let K={};for(let I of O)if(typeof I==="string")K[I]=I;else if(I&&typeof I==="object"&&typeof I.model==="string")K[I.model]=I;return K}return O},Q=(O)=>{if(!O)return{};return O};if(L[E]={hasOne:U(F.hasOne),hasMany:U(F.hasMany),belongsTo:U(F.belongsTo),belongsToMany:V(F.belongsToMany),hasOneThrough:Q(F.hasOneThrough),hasManyThrough:Q(F.hasManyThrough),morphOne:U(F.morphOne),morphMany:U(F.morphMany),morphTo:F.morphTo,morphToMany:U(F.morphToMany),morphedByMany:U(F.morphedByMany)},F.scopes&&typeof F.scopes==="object"){j[E]={};for(let O of Object.keys(F.scopes)){let K=F.scopes[O];if(typeof K==="function")j[E][O]=K}}}return{modelToTable:Z,tableToModel:X,primaryKeys:_,relations:L,scopes:j,models:$}}function f1($){return $.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Z])/gi,"$1_$2").toLowerCase()}function eF($){let Z=$;while(Z!==b7(Z)){if(vX(xZ(Z,"package.json")))return Z;Z=b7(Z)}return bX.cwd()}function $z(){let $=eF(bX.cwd()),Z=xZ($,"database","migrations");if(!vX(Z))tF(Z,{recursive:!0}),console.log(`-- Created SQL directory: ${Z}`);return Z}function S9($,Z){if(!$)return!1;let X=$z();t8++;let L=`${yZ?String(t8).padStart(10,"0"):String(Math.floor(Date.now()/1000)+t8)}-${Z}.sql`,j=xZ(X,L);return aF(j,$),console.log(`-- Migration file created: ${L}`),R9++,!0}function f7($){if($.endsWith("_id"))return"bigint";if($.endsWith("_at"))return"datetime";if($.startsWith("is_")||$.startsWith("has_"))return"boolean";return}function g7($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="bigint"||$ instanceof Date)return $;return}function Zz($){if($&&typeof $==="object"&&"name"in $){let Z=$;if(Z.name==="enum"||Z.getRules&&Array.isArray(Z.getRules())){if(Z.enumValues&&Array.isArray(Z.enumValues))return Z.enumValues.map((X)=>String(X));if(Z._values&&Array.isArray(Z._values))return Z._values.map((X)=>String(X));if(Z.values&&Array.isArray(Z.values))return Z.values.map((X)=>String(X))}}if($&&typeof $==="object"){let Z=$,X=Z.allowedValues||Z.enumValues||Z._values||Z.values;if(Array.isArray(X)&&X.length>0)return X.map((_)=>String(_))}return}function Xz($){if(!$?.rules||!Array.isArray($.rules))return;for(let Z of $.rules)if(Z?.name==="max"||Z?.name==="maxLength"){if(Z.params&&typeof Z.params.max==="number")return Z.params.max;if(Array.isArray(Z.args)&&typeof Z.args[0]==="number")return Z.args[0];if(typeof Z.value==="number")return Z.value;if(typeof Z.expectedValue==="number")return Z.expectedValue}return}function _z($){if(!$||typeof $!=="object")return;let Z=$;if(Z.name)switch(String(Z.name).toLowerCase()){case"string":case"text":{let _=Xz(Z);return _&&_>255?"text":"string"}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"json":return"json";case"enum":return"enum"}if(Z.type){let X=String(Z.type).toLowerCase();if(X==="string"||X==="text")return"string";if(X==="integer"||X==="int")return"integer";if(X==="bigint")return"bigint";if(X==="float")return"float";if(X==="number")return"integer";if(X==="boolean")return"boolean";if(X==="date")return"date";if(X==="datetime")return"datetime";if(X==="json")return"json"}return}function Lz($){if(!$)return[];if(Array.isArray($))return $;if(typeof $==="object")return Object.values($);return[]}function BZ($,Z){let X=rF($),_=[];for(let Y of Object.keys($)){let z=$[Y],F=z.table||`${String(z.name).toLowerCase()}s`,E=z.primaryKey??"id",U=z.autoIncrement!==!1,V=z.attributes??{},Q=[],O=[];if(!V[E])Q.push({name:f1(E),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let J of Object.keys(V)){let N=V[J],T=f1(J),v=!0,b,f,p=J===E;if(b=_z(N.validation?.rule),!b||b==="enum"){let t=Zz(N.validation?.rule);if(t&&t.length>0)b="enum",f=t}if(!b)b=f7(T);if(!b){let t=g7(N.default);if(typeof t==="string")b=t.length>255?"text":"string";else if(typeof t==="number")b=Number.isInteger(t)?"integer":"float";else if(typeof t==="boolean")b="boolean";else if(typeof t==="bigint")b="bigint";else if(t instanceof Date)b="datetime"}if(!b)b=p?"bigint":"string";let g={name:T,type:b,isPrimaryKey:p,isUnique:Boolean(N.unique),isNullable:!0,hasDefault:typeof N.default<"u",defaultValue:g7(N.default),enumValues:f};if(T.endsWith("_id")&&N.foreignKey!==!1)if(typeof N.foreignKey==="object"&&N.foreignKey!==null){let t=N.foreignKey;if(g.references={table:t.table,column:t.column??"id",onDelete:t.onDelete,onUpdate:t.onUpdate},t.nullable!==void 0)g.isNullable=t.nullable}else{let c0=T.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(w9,G0,h)=>h.toUpperCase()),z9=X.modelToTable[c0];if(z9){let w9=X.primaryKeys[z9]??"id";g.references={table:z9,column:w9}}}Q.push(g)}let K=Lz(z.belongsTo);for(let J of K){let N=`${f1(J)}_id`;if(Q.some((b)=>b.name===N))continue;let T=X.modelToTable[J];if(!T)continue;let v=X.primaryKeys[T]??"id";Q.push({name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:T,column:v}})}let I=z.traits;if(I?.useTimestamps??I?.timestampable??!1){if(!Q.some((J)=>J.name==="created_at"))Q.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"});if(!Q.some((J)=>J.name==="updated_at"))Q.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(I?.useSoftDeletes??I?.softDeletable??!1){if(!Q.some((J)=>J.name==="deleted_at"))Q.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(I?.useUuid??!1){if(!Q.some((J)=>J.name==="uuid"))Q.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let J of z.indexes??[])O.push({name:J.name,columns:J.columns.map((N)=>f1(N)),type:J.unique?"unique":"index",where:J.where});for(let J of Q)if(J.isUnique&&!J.isPrimaryKey)O.push({name:`${F}_${J.name}_unique`,columns:[J.name],type:"unique"});_.push({table:F,columns:Q,indexes:O})}let L=new Set(_.map((Y)=>Y.table));function j(Y){if(!L.has(Y.table))L.add(Y.table),_.push(Y)}for(let Y of Object.keys($)){let z=$[Y],F=z?.traits??{},E=z.table||`${String(z.name).toLowerCase()}s`,U=E.replace(/s$/,"");if(F.likeable){let V=typeof F.likeable==="object"?F.likeable:{},Q=V.table||`${E}_likes`,O=V.foreignKey||`${U}_id`;j({table:Q,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:O,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:E,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${Q}_user_target_unique`,columns:["user_id",O],type:"unique"}]})}if(F.taggable)j({table:"taggable",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:!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:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(F.categorizable)j({table:"categorizable",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:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_slug_unique",columns:["slug"],type:"unique"}]}),j({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:"categorizable",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:"CURRENT_TIMESTAMP"}],indexes:[{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let Y of Object.keys($)){let z=$[Y],F=z?.belongsToMany;if(!F||typeof F!=="object"||Array.isArray(F))continue;let E=z.table||`${String(z.name).toLowerCase()}s`,U=E.replace(/s$/,"");for(let[V,Q]of Object.entries(F)){let O=Q;if(!O||typeof O!=="object")continue;if(O.through)continue;let K=O.pivot;if(!K||!K.columns&&!K.timestamps&&!K.uniques)continue;let I=O.model,D=$[I]?.table||`${String(I).toLowerCase()}s`,M=D.replace(/s$/,""),J=O.table||[U,M].sort().join("_"),N=O.foreignKey||`${U}_id`,T=O.relatedKey||`${M}_id`,v=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:E,column:"id"}},{name:T,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:D,column:"id"}}];if(K.columns)for(let[p,g]of Object.entries(K.columns)){let t=g,c0=f7(p)??"string";v.push({name:p,type:c0,isPrimaryKey:!1,isUnique:!1,isNullable:t?.nullable??!1,hasDefault:t?.default!==void 0,defaultValue:t?.default})}if(K.timestamps)v.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}),v.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let b=[],f=K.uniques&&K.uniques.length>0?K.uniques:[[N,T]];for(let p=0;p<f.length;p++){let g=f[p];b.push({name:`${J}_${g.join("_")}_unique${p>0?`_${p}`:""}`,columns:[...g],type:"unique"})}j({table:J,columns:v,indexes:b})}}return{dialect:Z.dialect,tables:_}}function hZ($){t8=0,R9=0,T9=0,yZ=!0;let Z=[],X=p9($.dialect);for(let L of $.tables){let j=[],Y=new Set;for(let E of L.columns)if(E.type==="enum"&&E.enumValues&&E.enumValues.length>0){let U=`${E.name}_type`;if(!Y.has(U)){let V=X.createEnumType(U,E.enumValues);if(V)j.push(V);Y.add(U)}}let z=X.createTable(L);j.push(z),Z.push(...j);let F=j.join(`
461
+ Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${$}': ${_}`)}}},iU=new j5,lU={email:(X)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(X)},phone:(X)=>{let $=/^\+?[1-9]\d{0,15}$/,Z=X.replace(/[\s\-()]/g,"");return Z.length>=7&&$.test(Z)},name:(X)=>{return/^[a-z\s\-']+$/i.test(X)&&X.length>=2&&X.length<=50},age:(X)=>{return Number.isInteger(X)&&X>=0&&X<=150},url:(X)=>{try{let $=new URL(X);return X.startsWith("http://")||X.startsWith("https://")}catch{return!1}},regex:(X)=>($)=>{return X.test($)},length:(X,$)=>(Z)=>{return Z.length>=X&&Z.length<=$},range:(X,$)=>(Z)=>{return Z>=X&&Z<=$}},sU={phoneByCountry:{field:"phone",dependsOn:"country",mapping:{"United States":"+1-###-###-####","United Kingdom":"+44 #### ### ###",Germany:"+49 ### ########",France:"+33 # ## ## ## ##",Spain:"+34 ### ## ## ##",Italy:"+39 ### ### ###",Japan:"+81 ##-####-####",China:"+86 ### #### ####",Australia:"+61 ### ### ###",Canada:"+1-###-###-####"}},postalCodeByCountry:{field:"postalCode",dependsOn:"country",mapping:{"United States":"#####","United Kingdom":"AA## #AA",Germany:"#####",France:"#####",Spain:"#####",Italy:"#####",Japan:"###-####",China:"######",Australia:"####",Canada:"A#A #A#"}},firstNameByGender:{field:"firstName",dependsOn:"gender",mapping:{male:["John","Michael","David","James","Robert","William","Richard","Thomas","Christopher","Daniel"],female:["Mary","Patricia","Jennifer","Linda","Elizabeth","Barbara","Susan","Jessica","Sarah","Karen"]}}},oU={commonFirstNames:{items:[{item:"John",weight:100},{item:"Michael",weight:85},{item:"David",weight:80},{item:"James",weight:75},{item:"Robert",weight:70},{item:"William",weight:65},{item:"Richard",weight:60},{item:"Thomas",weight:55},{item:"Christopher",weight:50},{item:"Daniel",weight:45}]},ageDistribution:{items:[{item:25,weight:80},{item:30,weight:90},{item:35,weight:95},{item:40,weight:100},{item:45,weight:85},{item:50,weight:70},{item:55,weight:55},{item:60,weight:40},{item:65,weight:25},{item:70,weight:15}]},countryDistribution:{items:[{item:"United States",weight:100},{item:"China",weight:95},{item:"India",weight:90},{item:"Brazil",weight:60},{item:"Russia",weight:55},{item:"Japan",weight:50},{item:"Germany",weight:45},{item:"United Kingdom",weight:40},{item:"France",weight:35},{item:"Italy",weight:30}]}},rU=[".","_","-",""],aU=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","fugiat","nulla","pariatur","excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"],tU=["Toyota","Ford","Chevrolet","Honda","Nissan","BMW","Mercedes-Benz","Audi","Volkswagen","Hyundai","Kia","Mazda","Subaru","Lexus","Tesla","Volvo","Porsche","Jeep","Ram","GMC","Dodge","Chrysler","Buick","Cadillac","Acura","Infiniti","Genesis","Land Rover","Jaguar","Mini"],eU=["Accord","Camry","Civic","Corolla","CR-V","F-150","RAV4","Silverado","Tacoma","Altima","Sentra","Rogue","Model 3","Model Y","Model S","X5","X3","3 Series","5 Series","C-Class","E-Class","A4","Q5","Golf","Jetta","Passat","Tiguan","Escape","Explorer","Mustang","Ranger","Malibu","Equinox","Traverse","Wrangler","Grand Cherokee","Cherokee","Compass"],X7=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],$7=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],Z7=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"],h1="abcdefghijklmnopqrstuvwxyz".split(""),v1=new jZ,Y7=v1}),U7={};n1(U7,{validateData:()=>A$,selectWeightedItem:()=>k$,isInWorkspace:()=>AX,installPackage:()=>pU,globalProviderRegistry:()=>iU,getConfig:()=>jL,generateRealisticData:()=>OL,faker:()=>v1,detectPackageManager:()=>dU,defaultConfig:()=>XZ,default:()=>Y7,config:()=>y1,applyRelationships:()=>d9,applyConstraints:()=>FL,WordModule:()=>M$,WeightedSelections:()=>oU,VehicleModule:()=>D$,ValidationRules:()=>lU,SystemModule:()=>R$,StringModule:()=>t8,SportModule:()=>K$,ScienceModule:()=>I$,Random:()=>e8,PhoneModule:()=>V$,PersonModule:()=>W$,NumberModule:()=>a8,MusicModule:()=>J$,LoremModule:()=>r8,LocaleLoader:()=>Y9,InternetModule:()=>O$,ImageModule:()=>o8,HelpersModule:()=>s8,HackerModule:()=>F$,GitModule:()=>l8,FoodModule:()=>G$,FinanceModule:()=>i8,Faker:()=>jZ,DateModule:()=>n8,DatabaseModule:()=>u8,DataRelationships:()=>sU,DataProviderRegistry:()=>j5,CompanyModule:()=>E$,CommerceModule:()=>j$,ColorModule:()=>L$,BookModule:()=>z$,AnimalModule:()=>Q$,AddressModule:()=>_$});var BL=e(()=>{xL()});function r9(){let X=new Date().toISOString();return J0(f.dialect)?X.slice(0,19).replace("T"," "):X}function C9(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);if(X.length>64)throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' exceeds 64 chars`);if(!E5.test(X))throw TypeError(`[bun-query-builder] ${$}: identifier '${X}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function _7(X,$){if(typeof X!=="string"||X.length===0)throw TypeError(`[bun-query-builder] ${$}: identifier must be a non-empty string, got ${typeof X}`);let Z=X.split(".");if(Z.length>2||Z.some((Y)=>Y.length===0||Y.length>64||!E5.test(Y)))throw TypeError(`[bun-query-builder] ${$}: invalid ORDER BY column '${X}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function U9(X){if(!L8)try{L8=(P8(),p7(F7)).getModel}catch{L8=()=>{return}}return L8(X)}function L6(X){let $=tX.get(X);if($!==void 0)return $;let Z=0,Y=X.replace(/\?/g,()=>`$${++Z}`);if(tX.size>=gL)tX.clear();return tX.set(X,Y),Y}function j6(X){if(X==null)return 0;if(typeof X.affectedRows==="number")return X.affectedRows;if(typeof X.count==="number")return X.count;if(Array.isArray(X))return X.length;return 0}function E6(X){if(X==null||typeof X!=="object")return null;if("insertId"in X&&X.insertId!=null)return X.insertId;if("lastInsertRowid"in X&&X.lastInsertRowid!=null)return X.lastInsertRowid;return null}class f1{sqliteDb;dialect="sqlite";constructor(X){this.sqliteDb=X}all(X,$){return Promise.resolve(this.sqliteDb.query(X).all(...$))}get(X,$){return Promise.resolve(this.sqliteDb.query(X).get(...$)??void 0)}run(X,$){let Z=this.sqliteDb.run(X,$);return Promise.resolve({changes:Z.changes,lastInsertId:Z.lastInsertRowid})}insert(X,$){return this.run(X,$)}}class Q7{dialect;constructor(X){this.dialect=X}conn(){return BX()}text(X){return this.dialect==="postgres"?L6(X):X}async all(X,$){let Z=await this.conn().unsafe(this.text(X),$);return Array.isArray(Z)?Z:[]}async get(X,$){let Z=await this.conn().unsafe(this.text(X),$);if(Array.isArray(Z))return Z[0]??void 0;return Z??void 0}async run(X,$){let Z=await this.conn().unsafe(this.text(X),$);return{changes:j6(Z),lastInsertId:E6(Z)}}async insert(X,$,Z){if(this.dialect==="postgres"){let _=await this.conn().unsafe(`${L6(X)} RETURNING ${Z}`,$),Q=Array.isArray(_)?_[0]:_;return{changes:1,lastInsertId:Q?Q[Z]??null:null}}let Y=await this.conn().unsafe(X,$),U=E6(Y);if(U==null){let _=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);U=(Array.isArray(_)?_[0]:_)?.id??null}return{changes:j6(Y)||1,lastInsertId:U}}}function z7(X){if(X.database instanceof b1)o9=X.database;else o9=new b1(X.database||":memory:",{create:!0}),t1(o9);q9=null,eX=null}function I0(){if(o9){if(!q9||eX!==o9)q9=new f1(o9),eX=o9,z1="sqlite",L1=null;return q9}let X=f.dialect,$=f.database?.database??null;if(q9&&eX===null&&z1===X&&L1===$)return q9;if(eX=null,z1=X,L1=$,X==="sqlite"){let Z=new b1($||":memory:",{create:!0});t1(Z),q9=new f1(Z)}else q9=new Q7(X);return q9}function L7(){let X=I0();if(X.sqliteDb)return X.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${X.dialect}'. Use the async model API instead.`)}function vX(X){let $=X.traits;return Boolean($?.useSoftDeletes||$?.softDeletable)}function a9(X){let $=X.traits;return Boolean($?.useTimestamps||$?.timestampable)}function yL(X){let $=g1.get(X);if($)return $;let Z=new Set,Y=X.belongsToMany;if(Y){if(Array.isArray(Y)){for(let U of Y)if(typeof U==="string")Z.add(U.toLowerCase());else if(U&&typeof U==="object"&&U.model)Z.add(U.model.toLowerCase())}else if(typeof Y==="object")for(let U of Object.keys(Y))Z.add(U)}return g1.set(X,Z),Z}function G6(X){let $={};for(let[Z,Y]of Object.entries(X))$[s0(Z)]=Y;return $}function hL(X,$){if(X[$])return X[$];let Z=s0($);if(X[Z])return X[Z];for(let Y of Object.keys(X))if(s0(Y)===Z)return X[Y];return}class t0{_attributes;_original;_definition;_hasSaved=!1;_relations={};constructor(X,$={}){this._definition=X,this._attributes=G6({...$}),this._original=null;let Z=yL(X);if(Z.size===0)return;let Y=this;return new Proxy(this,{get(U,_,Q){if(typeof _==="string"&&Z.has(_)&&!(_ in U))return()=>{let L=j7(X,_);if(!L||L.type!=="belongsToMany")throw Error(`[orm] relation '${_}' did not resolve to a belongsToMany on '${X.name}'`);let z=U9(L.relatedModelName),j=z?.getDefinition?.()||z?.definition;if(!j)throw Error(`[orm] related model '${L.relatedModelName}' is not registered`);return new E7(Y,X,L,j)};return Reflect.get(U,_,Q)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(X){let $=this._definition.get?.[X];if($)try{let Z=$(this._attributes);if(Z!==void 0)return Z}catch{}return this._attributes[s0(X)]}getAttribute(X){return this._attributes[s0(X)]}getAttributes(){return{...this._attributes}}set(X,$){if(this._original===null)this._original={...this._attributes};this._attributes[s0(X)]=$}only(X){let $={};for(let Z of X)$[Z]=this._attributes[Z];return $}except(X){let $=new Set(X.map((Y)=>Y)),Z={};for(let Y of Object.keys(this._attributes))if(!$.has(Y))Z[Y]=this._attributes[Y];return Z}getRelation(X){return this._relations[X]}setRelation(X,$){this._relations[X]=$}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let X=this._definition.primaryKey||"id";return this._attributes[X]}isDirty(X){if(this._original===null)return!1;if(X)return this._attributes[X]!==this._original[X];return Object.keys(this._attributes).some(($)=>this._attributes[$]!==this._original[$])}isClean(X){return!this.isDirty(X)}getOriginal(X){return this.getOriginalAttributes()[X]}getChanges(){if(this._original===null)return{};let X={};for(let $ of Object.keys(this._attributes))if(this._attributes[$]!==this._original[$])X[$]=this._attributes[$];return X}fill(X){let $=this._definition.attributes;for(let[Z,Y]of Object.entries(X)){let U=hL($,Z),_=!U&&s0(Z).endsWith("_id");if(U?.fillable&&!U?.guarded||_){if(this._original===null)this._original={...this._attributes};this._attributes[s0(Z)]=Y}}return this}forceFill(X){if(this._original===null)this._original={...this._attributes};return Object.assign(this._attributes,G6(X)),this}async save(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._definition.hooks,Y=this._definition.set||{};for(let[U,_]of Object.entries(Y))if(this.isDirty(U))this._attributes[U]=_(this._attributes);if(this._attributes[$]){await Z?.beforeUpdate?.(this,this.getChanges());let U=this.getChanges(),_=Object.keys(U);if(_.length>0){let Q=_.map((z)=>`${z} = ?`).join(", "),L=[...Object.values(U),this._attributes[$]];if(a9(this._definition)){let z=r9();await X.run(`UPDATE ${this._definition.table} SET ${Q}, updated_at = ? WHERE ${$} = ?`,[...Object.values(U),z,this._attributes[$]])}else await X.run(`UPDATE ${this._definition.table} SET ${Q} WHERE ${$} = ?`,L)}await Z?.afterUpdate?.(this)}else{let U=this._definition.attributes,_={};for(let[j,E]of Object.entries(U)){if(E.guarded)continue;let V=s0(j);if(this._attributes[V]!==void 0)_[V]=this._attributes[V]}for(let j of Object.keys(this._attributes))if(j.endsWith("_id")&&j!==$&&!(j in _))_[j]=this._attributes[j];if(a9(this._definition)){let j=r9();_.created_at=j,_.updated_at=j}if(this._definition.traits?.useUuid&&!_.uuid)_.uuid=crypto.randomUUID();await Z?.beforeCreate?.(_);let Q=Object.keys(_),L=Q.map(()=>"?").join(", "),z=await X.insert(`INSERT INTO ${this._definition.table} (${Q.join(", ")}) VALUES (${L})`,Object.values(_),$);for(let[j,E]of Object.entries(_))this._attributes[j]=E;if(z.lastInsertId!=null)this._attributes[$]=z.lastInsertId;await Z?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update(X){return this.fill(X),this.save()}async fresh(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._attributes[$];if(Z==null)return null;let Y=await X.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);if(!Y)return null;return new t0(this._definition,Y)}async delete(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._attributes[$],Y=this._definition.hooks;if(!Z)throw Error("Cannot delete a model without a primary key");if(await Y?.beforeDelete?.(this),vX(this._definition)){let U=r9();await X.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${$} = ?`,[U,Z]),this._attributes[v9]=U}else await X.run(`DELETE FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);return await Y?.afterDelete?.(this),!0}async restore(){if(!vX(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let X=this._definition.primaryKey||"id",$=this._attributes[X];if(!$)throw Error("Cannot restore a model without a primary key");return await I0().run(`UPDATE ${this._definition.table} SET ${v9} = ? WHERE ${X} = ?`,[null,$]),this._attributes[v9]=null,this._original=null,this}trashed(){return this._attributes[v9]!=null}async refresh(){let X=I0(),$=this._definition.primaryKey||"id",Z=this._attributes[$];if(!Z)throw Error("Cannot refresh a model without a primary key");let Y=await X.get(`SELECT * FROM ${this._definition.table} WHERE ${$} = ?`,[Z]);if(!Y)return null;return this._attributes=Y,this._original=null,this}replicate(){let X=this._definition.primaryKey||"id",$={...this._attributes};return delete $[X],delete $.uuid,delete $.created_at,delete $.updated_at,new t0(this._definition,$)}toArray(){let X={...this._attributes};for(let[$,Z]of Object.entries(this._relations))if(Array.isArray(Z))X[$]=Z.map((Y)=>Y.toArray());else if(Z)X[$]=Z.toArray();else X[$]=null;return X}toJSON(){let X=new Set;for(let[Z,Y]of Object.entries(this._definition.attributes))if(Y.hidden)X.add(Z);let $={};for(let[Z,Y]of Object.entries(this._attributes))if(!X.has(Z))$[Z]=Y;for(let[Z,Y]of Object.entries(this._relations))if(Array.isArray(Y))$[Z]=Y.map((U)=>U.toJSON());else if(Y)$[Z]=Y.toJSON();else $[Z]=null;return $}}function s0(X){let $=d1.get(X);if($!==void 0)return $;return $=X.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),d1.set(X,$),$}function i9(X){let $=p1.get(X);if($!==void 0)return $;let Z=s0(X);if(Z.endsWith("y")&&!Z.endsWith("ay")&&!Z.endsWith("ey")&&!Z.endsWith("oy")&&!Z.endsWith("uy"))$=Z.slice(0,-1)+"ies";else if(Z.endsWith("s")||Z.endsWith("x")||Z.endsWith("ch")||Z.endsWith("sh"))$=`${Z}es`;else $=`${Z}s`;return p1.set(X,$),$}function j7(X,$){let{name:Z,table:Y}=X,U=X.primaryKey||"id";function _(W){if(!W)return null;if(Array.isArray(W)){for(let F of W){let K=typeof F==="string"?F:F?.model||"";if(K&&K.toLowerCase()===$.toLowerCase())return K}return null}if(typeof W==="object"){for(let[F,K]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||F}return null}function Q(){let W=X.belongsToMany;if(!W)return null;if(Array.isArray(W)){for(let F of W)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 W==="object"){for(let[F,K]of Object.entries(W))if(F===$||F.toLowerCase()===$.toLowerCase())return{entry:K}}return null}let L=_(X.hasMany);if(L){let F=U9(L)?.getTable?.()||i9(L),K=s0(Z)+"_id";return{type:"hasMany",relatedModelName:L,relatedTable:F,foreignKey:K,localKey:U}}let z=_(X.hasOne);if(z){let F=U9(z)?.getTable?.()||i9(z),K=s0(Z)+"_id";return{type:"hasOne",relatedModelName:z,relatedTable:F,foreignKey:K,localKey:U}}let j=_(X.belongsTo);if(j){let W=U9(j),F=W?.getTable?.()||i9(j),K=W?.getDefinition?.()?.primaryKey||"id",D=s0(j)+"_id";return{type:"belongsTo",relatedModelName:j,relatedTable:F,foreignKey:D,localKey:K}}let E=Q();if(E){let W=typeof E.entry==="object",F=W?E.entry.model:E.entry,D=U9(F)?.getTable?.()||i9(F),w=W?E.entry:null,T,N;if(w?.table)T=w.table;else if(w?.through){N=w.through;let h=U9(w.through);if(!h)throw Error(`[orm] belongsToMany relation '${$}' on '${Z}' references unknown through model '${w.through}'. Make sure '${w.through}' is registered.`);T=h.getTable?.()||h.getDefinition?.()?.table||i9(w.through)}else{let h=Y.endsWith("s")?Y.slice(0,-1):Y,c=D.endsWith("s")?D.slice(0,-1):D;T=[h,c].sort().join("_")}let q=w?.foreignKey||`${Y.endsWith("s")?Y.slice(0,-1):Y}_id`,H=w?.relatedKey||`${D.endsWith("s")?D.slice(0,-1):D}_id`,x=[];if(w?.pivot?.columns)for(let h of Object.keys(w.pivot.columns))x.push(h);if(N){let h=U9(N),c=h?.getDefinition?.()||h?.definition,y=c?.attributes??{},g=c?.primaryKey??"id";for(let v of Object.keys(y)){if(v===q||v===H||v===g)continue;if(!x.includes(v))x.push(v)}}return{type:"belongsToMany",relatedModelName:F,relatedTable:D,foreignKey:q,localKey:U,pivotTable:T,pivotFkParent:q,pivotFkRelated:H,pivotColumns:x,pivotModelName:N,pivotTimestamps:Boolean(w?.pivot?.timestamps)}}let V=(W,F)=>{if(!W||typeof W!=="object"||Array.isArray(W))return null;let K=W[$]??W[Object.keys(W).find((c)=>c.toLowerCase()===$.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:D,target:w}=K;if(!D||!w)return null;let T=U9(D),N=T?.getDefinition?.()||T?.definition,q=T?.getTable?.()||N?.table||i9(D),H=N?.primaryKey||"id",h=U9(w)?.getTable?.()||i9(w);return{type:F,relatedModelName:w,relatedTable:h,foreignKey:`${s0(Z)}_id`,localKey:U,throughTable:q,throughForeignKey:`${s0(Z)}_id`,throughLocalKey:H,targetForeignKey:`${vL(q)}_id`}},G=V(X.hasManyThrough,"hasManyThrough");if(G)return G;let J=V(X.hasOneThrough,"hasOneThrough");if(J)return J;return null}function vL(X){return X.endsWith("s")?X.slice(0,-1):X}class E7{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(X,$,Z,Y){this._parent=X,this._parentDef=$,this._resolved=Z,this._relatedDef=Y}get parentId(){let X=this._parentDef.primaryKey||"id";return this._parent.get(X)}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(X,$,Z){if(Z===void 0)this._wheres.push({sql:`${this.relatedTable}.${X} = ?`,params:[$]});else this._wheres.push({sql:`${this.relatedTable}.${X} ${String($)} ?`,params:[Z]});return this}wherePivot(X,$,Z){if(Z===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${X} = ?`,params:[$]});else this._pivotWheres.push({sql:`${this.pivotTable}.${X} ${String($)} ?`,params:[Z]});return this}wherePivotIn(X,$){if(!$.length)return this;let Z=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IN (${Z})`,params:[...$]}),this}wherePivotNotIn(X,$){if(!$.length)return this;let Z=$.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${X} NOT IN (${Z})`,params:[...$]}),this}wherePivotNull(X){return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IS NULL`,params:[]}),this}wherePivotNotNull(X){return this._pivotWheres.push({sql:`${this.pivotTable}.${X} IS NOT NULL`,params:[]}),this}orderBy(X,$="asc"){if(_7(X,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push(`${X} ${$.toUpperCase()}`),this}limit(X){if(!Number.isFinite(X)||X<0||!Number.isInteger(X))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${X}`);return this._limit=X,this}offset(X){if(!Number.isFinite(X)||X<0||!Number.isInteger(X))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${X}`);return this._offset=X,this}relatedSelectColumns(){let X=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),$=this._relatedDef.traits;if($?.useTimestamps||$?.timestampable)X.add("created_at"),X.add("updated_at");if($?.useSoftDeletes||$?.softDeletable)X.add("deleted_at");if($?.useUuid)X.add("uuid");return[...X]}buildSelect(){let X=[],Z=`SELECT ${this.relatedSelectColumns().map((Y)=>`${this.relatedTable}.${Y} AS ${j1}${Y}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;Z+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,Z+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,X.push(this.parentId);for(let Y of this._pivotWheres)Z+=` AND ${Y.sql}`,X.push(...Y.params);for(let Y of this._wheres)Z+=` AND ${Y.sql}`,X.push(...Y.params);if(this._orderBy.length>0)Z+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)Z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Z+=` OFFSET ${this._offset}`;return{sql:Z,params:X}}hydrateRows(X){let $=this.fkParent,Z=this.fkRelated;return X.map((Y)=>{let U={},_={};for(let[L,z]of Object.entries(Y))if(L.startsWith(j1))U[L.slice(j1.length)]=z;else if(L!==$&&L!==Z)_[L]=z;let Q=new t0(this._relatedDef,U);return Q.pivot=_,Q})}async get(){let X=I0(),{sql:$,params:Z}=this.buildSelect(),Y=await X.all($,Z);return this.hydrateRows(Y)}async first(){return this._limit=1,(await this.get())[0]}async count(){let X=I0(),$=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Z=[this.parentId];for(let U of this._pivotWheres)$+=` AND ${U.sql}`,Z.push(...U.params);let Y=await X.get($,Z);return Number(Y?.count??0)}async exists(){return await this.count()>0}now(){return r9()}async attach(X,$={}){let Z=I0(),Y=Array.isArray(X)?X:[X];if(Y.length===0)return 0;let U=this._resolved.pivotTimestamps?this.now():null,_=0;for(let Q of Y){let L={[this.fkParent]:this.parentId,[this.fkRelated]:Q,...$};if(U){if(L.created_at===void 0)L.created_at=U;if(L.updated_at===void 0)L.updated_at=U}let z=Object.keys(L),j=z.map(()=>"?").join(", "),E=`INSERT INTO ${this.pivotTable} (${z.join(", ")}) VALUES (${j})`,V=z.map((G)=>L[G]);await Z.run(E,V),_++}return _}async detach(X){let $=I0(),Z=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,Y=[this.parentId];if(X!==void 0&&X!==null){let U=Array.isArray(X)?X:[X];if(U.length===0)return 0;let _=U.map(()=>"?").join(", ");Z+=` AND ${this.fkRelated} IN (${_})`,Y.push(...U)}return(await $.run(Z,Y)).changes}async updateExistingPivot(X,$){let Z=I0(),Y={...$};if(this._resolved.pivotTimestamps&&Y.updated_at===void 0)Y.updated_at=this.now();let U=Object.keys(Y);if(U.length===0)return 0;let _=U.map((z)=>`${z} = ?`).join(", "),Q=`UPDATE ${this.pivotTable} SET ${_} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,L=[...U.map((z)=>Y[z]),this.parentId,X];return(await Z.run(Q,L)).changes}async sync(X){let $=I0(),Z=new Map;for(let j of X)if(j!=null&&typeof j==="object"&&"id"in j){let{id:E,...V}=j;Z.set(E,V)}else Z.set(j,{});let Y=await $.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),U=new Set(Y.map((j)=>j[this.fkRelated])),_=[],Q=[],L=[],z=[...U].filter((j)=>!Z.has(j));if(z.length>0)await this.detach(z),Q.push(...z);for(let[j,E]of Z)if(!U.has(j))await this.attach(j,E),_.push(j);else if(Object.keys(E).length>0)await this.updateExistingPivot(j,E),L.push(j);return{attached:_,detached:Q,updated:L}}async toggle(X){let $=I0(),Z=Array.isArray(X)?X:[X];if(Z.length===0)return{attached:[],detached:[]};let Y=Z.map(()=>"?").join(", "),U=await $.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${Y})`,[this.parentId,...Z]),_=new Set(U.map((z)=>z[this.fkRelated])),Q=Z.filter((z)=>!_.has(z)),L=Z.filter((z)=>_.has(z));if(Q.length>0)await this.attach(Q);if(L.length>0)await this.detach(L);return{attached:Q,detached:L}}}class Y0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(X){this._definition=X}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"and"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"and"});return this}orWhere(X,$,Z){if(Z===void 0)this._wheres.push({column:X,operator:"=",value:$,boolean:"or"});else this._wheres.push({column:X,operator:$,value:Z,boolean:"or"});return this}whereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"and"}),this}orWhereIn(X,$){return this._wheres.push({column:X,operator:"in",value:$,boolean:"or"}),this}whereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"and"}),this}orWhereNotIn(X,$){return this._wheres.push({column:X,operator:"not in",value:$,boolean:"or"}),this}whereNull(X){return C9(X,"whereNull(column)"),this._wheres.push({column:X,operator:"=",value:null,boolean:"and"}),this}orWhereNull(X){return C9(X,"orWhereNull(column)"),this._wheres.push({column:X,operator:"=",value:null,boolean:"or"}),this}whereNotNull(X){return C9(X,"whereNotNull(column)"),this._wheres.push({column:X,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(X){return C9(X,"orWhereNotNull(column)"),this._wheres.push({column:X,operator:"!=",value:null,boolean:"or"}),this}whereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"and"}),this}orWhereLike(X,$){return this._wheres.push({column:X,operator:"like",value:$,boolean:"or"}),this}whereNotLike(X,$){return this._wheres.push({column:X,operator:"not like",value:$,boolean:"and"}),this}orWhereNotLike(X,$){return this._wheres.push({column:X,operator:"not like",value:$,boolean:"or"}),this}whereRaw(X,...$){return this._wheres.push({raw:X,rawParams:$,boolean:"and"}),this}orWhereRaw(X,...$){return this._wheres.push({raw:X,rawParams:$,boolean:"or"}),this}whereGroup(X){return this._addGroup("and",X)}orWhereGroup(X){return this._addGroup("or",X)}_addGroup(X,$){let Z=new Y0(this._definition);if($(Z),Z._wheres.length===0)return this;let Y=[],U=Z.buildWhereClauses(Y);if(!U)return this;return this._wheres.push({raw:`(${U})`,rawParams:Y,boolean:X}),this}whereBetween(X,$){return C9(X,"whereBetween(column)"),this._wheres.push({column:X,operator:">=",value:$[0],boolean:"and"}),this._wheres.push({column:X,operator:"<=",value:$[1],boolean:"and"}),this}whereNotBetween(X,$){C9(X,"whereNotBetween(column)");let Z=X;return this._wheres.push({raw:`(${Z} < ? OR ${Z} > ?)`,rawParams:[$[0],$[1]],boolean:"and"}),this}when(X,$){if(X)return $(this);return this}orderBy(X,$="asc"){if(_7(X,"orderBy(column)"),$!=="asc"&&$!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${$}'`);return this._orderBy.push({column:X,direction:$}),this}orderByDesc(X){return this.orderBy(X,"desc")}orderByAsc(X){return this.orderBy(X,"asc")}limit(X){return this._limit=X,this}take(X){return this.limit(X)}offset(X){return this._offset=X,this}skip(X){return this.offset(X)}select(...X){return this._select=X,this}with(...X){return this._withRelations=X,this}getWithRelations(){return this._withRelations}buildWhereClauses(X){let $=[];for(let Z=0;Z<this._wheres.length;Z++){let Y=this._wheres[Z],U;if(Y.raw){if(U=Y.raw,Y.rawParams&&Y.rawParams.length>0)X.push(...Y.rawParams)}else if(Y.value===null)U=Y.operator==="="?`${Y.column} IS NULL`:`${Y.column} IS NOT NULL`;else if(Y.operator==="in"||Y.operator==="not in"){let _=Y.value;U=`${Y.column} ${Y.operator.toUpperCase()} (${_.map(()=>"?").join(", ")})`,X.push(..._)}else U=`${Y.column} ${Y.operator} ?`,X.push(Y.value);$.push(Z===0?U:`${Y.boolean.toUpperCase()} ${U}`)}return $.join(" ")}softDeleteClause(){if(this._trashed==="include"||!vX(this._definition))return"";return this._trashed==="only"?`${v9} IS NOT NULL`:`${v9} IS NULL`}composeWhere(X){let $=this._wheres.length>0?this.buildWhereClauses(X):"",Z=this.softDeleteClause();if($&&Z)return`(${$}) AND ${Z}`;return $||Z}buildQuery(){let X=[],$=`SELECT ${this._select.join(", ")} FROM ${this._definition.table}`,Z=this.composeWhere(X);if(Z)$+=` WHERE ${Z}`;if(this._orderBy.length>0)$+=` ORDER BY ${this._orderBy.map((Y)=>`${Y.column} ${Y.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)$+=` LIMIT ${this._limit}`;if(this._offset!==void 0)$+=` OFFSET ${this._offset}`;return{sql:$,params:X}}toSql(){return this.buildQuery()}async eagerLoadRelations(X){if(X.length===0||this._withRelations.length===0)return;let $=I0(),Z=this._definition.primaryKey||"id";for(let Y of this._withRelations){let U=`${this._definition.name}:${Y}`,_=X$.get(U);if(_===void 0){if(_=j7(this._definition,Y),X$.size>=dL)X$.clear();X$.set(U,_)}if(!_)continue;if(_.type==="hasMany"||_.type==="hasOne"){let Q=X.map((V)=>V.get(Z)).filter((V)=>V!=null);if(Q.length===0)continue;let L=Q.map(()=>"?").join(", "),z=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.foreignKey} IN (${L})`,Q),j=U9(_.relatedModelName),E=j?.getDefinition?.()||j?.definition||this._definition;if(_.type==="hasMany"){let V=new Map;for(let G of z){let J=G[_.foreignKey];if(!V.has(J))V.set(J,[]);V.get(J).push(G)}for(let G of X){let J=V.get(G.get(Z))||[];G.setRelation(Y,J.map((W)=>new t0(E,W)))}}else{let V=new Map;for(let G of z)V.set(G[_.foreignKey],G);for(let G of X){let J=V.get(G.get(Z));G.setRelation(Y,J?new t0(E,J):null)}}}if(_.type==="belongsTo"){let Q=new Set;for(let J of X){let W=J._attributes[_.foreignKey];if(W!=null)Q.add(W)}let L=[...Q];if(L.length===0)continue;let z=L.map(()=>"?").join(", "),j=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.localKey} IN (${z})`,L),E=U9(_.relatedModelName),V=E?.getDefinition?.()||E?.definition||this._definition,G=new Map;for(let J of j)G.set(J[_.localKey],J);for(let J of X){let W=J._attributes[_.foreignKey],F=G.get(W);J.setRelation(Y,F?new t0(V,F):null)}}if(_.type==="belongsToMany"){let Q=X.map((w)=>w.get(Z)).filter((w)=>w!=null);if(Q.length===0)continue;if(!_.pivotTable||!_.pivotFkParent||!_.pivotFkRelated)continue;let L=Q.map(()=>"?").join(", "),z=await $.all(`SELECT * FROM ${_.pivotTable} WHERE ${_.pivotFkParent} IN (${L})`,Q);if(z.length===0){for(let w of X)w.setRelation(Y,[]);continue}let j=new Set;for(let w of z){let T=w[_.pivotFkRelated];if(T!=null)j.add(T)}let E=[...j],V=U9(_.relatedModelName),G=V?.getDefinition?.()||V?.definition||this._definition,J=G?.primaryKey||"id",W=[];if(E.length>0){let w=E.map(()=>"?").join(", ");W=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${J} IN (${w})`,E)}let F=new Map;for(let w of W)F.set(w[J],w);let K=new Map;for(let w of z){let T=w[_.pivotFkParent];if(!K.has(T))K.set(T,[]);K.get(T).push(w)}let D=new Set([_.pivotFkParent,_.pivotFkRelated]);for(let w of X){let T=w.get(Z),q=(K.get(T)||[]).map((H)=>{let x=F.get(H[_.pivotFkRelated]);if(!x)return null;let h=new t0(G,x),c={};for(let[y,g]of Object.entries(H))if(!D.has(y))c[y]=g;return h.pivot=c,h}).filter((H)=>H!==null);w.setRelation(Y,q)}}if(_.type==="hasManyThrough"||_.type==="hasOneThrough"){let Q=X.map((D)=>D.get(Z)).filter((D)=>D!=null);if(Q.length===0)continue;let L=_.throughLocalKey||"id",z=Q.map(()=>"?").join(", "),j=await $.all(`SELECT ${L}, ${_.throughForeignKey} FROM ${_.throughTable} WHERE ${_.throughForeignKey} IN (${z})`,Q);if(j.length===0){for(let D of X)D.setRelation(Y,_.type==="hasManyThrough"?[]:null);continue}let E=new Map;for(let D of j)E.set(D[L],D[_.throughForeignKey]);let V=[...new Set(j.map((D)=>D[L]))],G=V.map(()=>"?").join(", "),J=await $.all(`SELECT * FROM ${_.relatedTable} WHERE ${_.targetForeignKey} IN (${G})`,V),W=U9(_.relatedModelName),F=W?.getDefinition?.()||W?.definition||this._definition,K=new Map;for(let D of J){let w=E.get(D[_.targetForeignKey]);if(w==null)continue;if(!K.has(w))K.set(w,[]);K.get(w).push(new t0(F,D))}for(let D of X){let w=K.get(D.get(Z))||[];D.setRelation(Y,_.type==="hasManyThrough"?w:w[0]??null)}}}}async get(){let X=I0(),{sql:$,params:Z}=this.buildQuery(),U=(await X.all($,Z)).map((_)=>new t0(this._definition,_));if(this._withRelations.length>0)await this.eagerLoadRelations(U);return U}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let X=await this.first();if(!X)throw Error(`No ${this._definition.name} found`);return X}async last(){let X=this._definition.primaryKey||"id";return this._orderBy=[{column:X,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let X=I0(),$=[],Z=`SELECT COUNT(*) as count FROM ${this._definition.table}`,Y=this.composeWhere($);if(Y)Z+=` WHERE ${Y}`;let U=await X.get(Z,$);return Number(U?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let X=await this.get();if(X.length===0)throw Error(`No ${this._definition.name} found`);if(X.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return X[0]}async increment(X,$=1){C9(X,"increment(column)");let Z=I0(),Y=[$],U=`UPDATE ${this._definition.table} SET ${X} = ${X} + ?`;if(a9(this._definition))U+=", updated_at = ?",Y.push(r9());if(this._wheres.length>0){let _=this.buildWhereClauses(Y);U+=` WHERE ${_}`}return(await Z.run(U,Y)).changes}decrement(X,$=1){return this.increment(X,-$)}async chunk(X,$){let Z=0;while(!0){let Y=new Y0(this._definition);Y._wheres=[...this._wheres],Y._orderBy=[...this._orderBy],Y._select=[...this._select],Y._withRelations=[...this._withRelations],Y._trashed=this._trashed,Y._limit=X,Y._offset=Z*X;let U=await Y.get();if(U.length===0)break;if(await $(U)===!1)break;if(U.length<X)break;Z++}}async paginate(X=1,$=15){let Z=await this.count(),Y=Math.ceil(Z/$);this._limit=$,this._offset=(X-1)*$;let U=await this.get();return{data:U,total:Z,page:X,perPage:$,lastPage:Y,hasMorePages:X<Y,isEmpty:U.length===0,from:U.length>0?(X-1)*$+1:null,to:U.length>0?(X-1)*$+U.length:null}}async pluck(X){C9(X,"pluck(column)");let $=I0(),Z=[],Y=`SELECT ${X} FROM ${this._definition.table}`,U=this.composeWhere(Z);if(U)Y+=` WHERE ${U}`;if(this._orderBy.length>0)Y+=` ORDER BY ${this._orderBy.map((Q)=>`${Q.column} ${Q.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)Y+=` LIMIT ${this._limit}`;if(this._offset!==void 0)Y+=` OFFSET ${this._offset}`;return(await $.all(Y,Z)).map((Q)=>Q[X])}async aggregate(X,$){C9($,`${X}(column)`);let Z=I0(),Y=[],U=`SELECT ${X}(${$}) as v FROM ${this._definition.table}`,_=this.composeWhere(Y);if(_)U+=` WHERE ${_}`;let L=(await Z.get(U,Y))?.v;if(L==null)return null;if(typeof L==="string"){let z=Number(L);return L.trim()!==""&&!Number.isNaN(z)?z:L}return L}max(X){return this.aggregate("MAX",X)}min(X){return this.aggregate("MIN",X)}async avg(X){return Number(await this.aggregate("AVG",X)??0)||0}async sum(X){return Number(await this.aggregate("SUM",X)??0)||0}async delete(){let X=I0(),$=[],Z=`DELETE FROM ${this._definition.table}`;if(this._wheres.length>0)Z+=` WHERE ${this.buildWhereClauses($)}`;return(await X.run(Z,$)).changes}async update(X){let $=I0(),Z=Object.entries(X),Y=Z.map(([Q])=>`${Q} = ?`).join(", "),U=Z.map(([,Q])=>Q);if(a9(this._definition))U.push(r9());let _=`UPDATE ${this._definition.table} SET ${Y}${a9(this._definition)?", updated_at = ?":""}`;if(this._wheres.length>0)_+=` WHERE ${this.buildWhereClauses(U)}`;return(await $.run(_,U)).changes}}function bL(X){let $={query:()=>new Y0(X),where(Z,Y,U){return new Y0(X).where(Z,Y,U)},orWhere(Z,Y,U){return new Y0(X).orWhere(Z,Y,U)},whereIn(Z,Y){return new Y0(X).whereIn(Z,Y)},whereNotIn(Z,Y){return new Y0(X).whereNotIn(Z,Y)},whereNull(Z){return new Y0(X).whereNull(Z)},whereNotNull(Z){return new Y0(X).whereNotNull(Z)},whereLike(Z,Y){return new Y0(X).whereLike(Z,Y)},orderBy(Z,Y="asc"){return new Y0(X).orderBy(Z,Y)},orderByDesc(Z){return new Y0(X).orderByDesc(Z)},select(...Z){return new Y0(X).select(...Z)},with(...Z){return new Y0(X).with(...Z)},limit:(Z)=>new Y0(X).limit(Z),take:(Z)=>new Y0(X).take(Z),skip:(Z)=>new Y0(X).skip(Z),withTrashed:()=>new Y0(X).withTrashed(),onlyTrashed:()=>new Y0(X).onlyTrashed(),async find(Z){let Y=I0(),U=X.primaryKey||"id",_=vX(X)?` AND ${v9} IS NULL`:"",Q=await Y.get(`SELECT * FROM ${X.table} WHERE ${U} = ?${_}`,[Z]);return Q?new t0(X,Q):void 0},async findOrFail(Z){let Y=await $.find(Z);if(!Y)throw Error(`${X.name} with id ${Z} not found`);return Y},async findMany(Z){let Y=I0(),U=X.primaryKey||"id",_=vX(X)?` AND ${v9} IS NULL`:"";return(await Y.all(`SELECT * FROM ${X.table} WHERE ${U} IN (${Z.map(()=>"?").join(", ")})${_}`,Z)).map((L)=>new t0(X,L))},all:()=>new Y0(X).get(),first:()=>new Y0(X).first(),firstOrFail:()=>new Y0(X).firstOrFail(),last:()=>new Y0(X).last(),count:()=>new Y0(X).count(),exists:()=>new Y0(X).exists(),doesntExist:()=>new Y0(X).doesntExist(),paginate:(Z,Y)=>new Y0(X).paginate(Z,Y),whereBetween(Z,Y){return new Y0(X).whereBetween(Z,Y)},whereNotBetween(Z,Y){return new Y0(X).whereNotBetween(Z,Y)},async create(Z){let Y=new t0(X,Z);return await Y.save(),Y},async createMany(Z){let Y=[];for(let U of Z)Y.push(await this.create(U));return Y},async updateOrCreate(Z,Y){let U=new Y0(X);for(let[Q,L]of Object.entries(Z))U=U.where(Q,L);let _=await U.first();if(_)return await _.update(Y),_;return this.create({...Z,...Y})},async firstOrCreate(Z,Y){let U=new Y0(X);for(let[Q,L]of Object.entries(Z))U=U.where(Q,L);return await U.first()||this.create({...Z,...Y})},async destroy(Z){let Y=I0(),U=X.primaryKey||"id";return(await Y.run(`DELETE FROM ${X.table} WHERE ${U} = ?`,[Z])).changes>0},remove(Z){return this.destroy(Z)},async truncate(){await I0().run(`DELETE FROM ${X.table}`,[])},getDefinition:()=>X,getTable:()=>X.table,make(Z={}){return new t0(X,Z)},latest:(Z="created_at")=>new Y0(X).orderByDesc(Z),oldest:(Z="created_at")=>new Y0(X).orderBy(Z,"asc"),max:(Z)=>new Y0(X).max(Z),min:(Z)=>new Y0(X).min(Z),avg:(Z)=>new Y0(X).avg(Z),sum:(Z)=>new Y0(X).sum(Z),pluck(Z){return new Y0(X).pluck(Z)}};return new Proxy($,{get(Z,Y){if(typeof Y==="string"&&Y.startsWith("where")&&Y.length>5){let U=Y.slice(5),_=U.charAt(0).toLowerCase()+U.slice(1);if(_ in X.attributes||_==="id"||_===X.primaryKey)return(Q)=>new Y0(X).where(_,Q)}return Reflect.get(Z,Y)}})}async function _O(X){let $=I0(),Z=X.primaryKey||"id",Y=[];if(Y.push(X.autoIncrement!==!1?`${Z} INTEGER PRIMARY KEY AUTOINCREMENT`:`${Z} INTEGER PRIMARY KEY`),X.traits?.useUuid)Y.push("uuid TEXT UNIQUE");for(let[U,_]of Object.entries(X.attributes)){let Q="TEXT";if(_.type==="number")Q="INTEGER";else if(_.type==="boolean")Q="INTEGER";if(U.endsWith("_id"))Q="INTEGER";let L=`${U} ${Q}`;if(_.unique)L+=" UNIQUE";if(typeof _.foreignKey==="object"&&_.foreignKey!==null){let z=_.foreignKey;if(L+=` REFERENCES ${z.table}(${z.column??"id"})`,z.onDelete)L+=` ON DELETE ${z.onDelete.toUpperCase()}`;if(z.onUpdate)L+=` ON UPDATE ${z.onUpdate.toUpperCase()}`}Y.push(L)}if(a9(X))Y.push("created_at TEXT","updated_at TEXT");if(vX(X))Y.push("deleted_at TEXT");await $.run(`CREATE TABLE IF NOT EXISTS ${X.table} (${Y.join(", ")})`,[])}function fL(X){return new Proxy(X,{get($,Z){if(Z==="location")return $.address;if(Z==="datatype"){let{random:Y,number:U,string:_}=$;return{boolean:()=>Y?.boolean?.(),number:(Q)=>U?.int?.(Q),float:(Q)=>U?.float?.(Q),uuid:()=>crypto.randomUUID(),string:(Q)=>_?.alphanumeric?.(Q??10)}}return $[Z]}})}async function QO(X,$,Z){let Y=I0(),U=X.traits?.useSeeder,_=$??(typeof U==="object"&&U?U.count:10);if(!Z)try{let Q=await Promise.resolve().then(()=>(BL(),U7));Z=fL(Q.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let Q=0;Q<_;Q++){let L={};for(let[j,E]of Object.entries(X.attributes))if(E.factory)L[j]=E.factory(Z);if(a9(X)){let j=r9();L.created_at=j,L.updated_at=j}if(X.traits?.useUuid)L.uuid=crypto.randomUUID();let z=Object.keys(L);await Y.run(`INSERT INTO ${X.table} (${z.join(", ")}) VALUES (${z.map(()=>"?").join(", ")})`,Object.values(L))}}var E5,L8=null,tX,gL=500,o9=null,q9=null,eX=null,z1=null,L1=null,v9="deleted_at",j1="__btm_rel__",g1,d1,p1,X$,dL=1000,G7=e(()=>{d0(),$X(),e1(),E5=/^[A-Z_][A-Z0-9_]*$/i,tX=new Map,g1=new WeakMap,d1=new Map,p1=new Map,X$=new Map}),F7={};n1(F7,{registerModel:()=>EZ,registerBrowserModels:()=>lL,hasModel:()=>uL,getModelRegistry:()=>mL,getModel:()=>pL,getAllModels:()=>cL,defineModel:()=>G5,clearModelRegistry:()=>nL});function pL(X){return YX.get(X)}function cL(){return[...YX.values()]}function mL(){return Object.fromEntries(YX)}function uL(X){return YX.has(X)}function nL(){YX.clear()}function EZ(X,$){return YX.set(X,$),$}function iL(){return typeof window<"u"&&typeof document<"u"}function G5(X){let $;if(iL())$=n7(X);else{let Z=bL(X);$=Object.assign(Z,{definition:X,getDefinition:()=>X,getTable:()=>X.table,getName:()=>X.name})}return EZ(X.name,$),$}function lL(X){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...X}}var YX,P8=e(()=>{M6(),G7(),YX=new Map});class gX{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor(X){this.driver=bX(X.config),this.client=X.client,this.tableName=X.config.tableName??""}table(X){return this.tableName=X,this}index(X){return this.indexName=X,this}entity(X){return this.entityType=X,this}whereKey(X,$,Z){return this.keyConditions.push({attribute:X,operator:$,value:Z}),this}wherePartitionKey(X,$){return this.whereKey(X,"=",$)}whereSortKey(X,$){return this.whereKey(X,"=",$)}whereSortKeyBeginsWith(X,$){return this.keyConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereSortKeyBetween(X,$,Z){return this.keyConditions.push({attribute:X,operator:"BETWEEN",values:[$,Z]}),this}where(X,$,Z){return this.filterConditions.push({attribute:X,operator:$,value:Z}),this}whereEquals(X,$){return this.where(X,"=",$)}whereLessThan(X,$){return this.where(X,"<",$)}whereLessThanOrEqual(X,$){return this.where(X,"<=",$)}whereGreaterThan(X,$){return this.where(X,">",$)}whereGreaterThanOrEqual(X,$){return this.where(X,">=",$)}whereBetween(X,$,Z){return this.filterConditions.push({attribute:X,operator:"BETWEEN",values:[$,Z]}),this}whereBeginsWith(X,$){return this.filterConditions.push({attribute:X,operator:"begins_with",value:$}),this}whereContains(X,$){return this.where(X,"contains",$)}whereExists(X){return this.where(X,"attribute_exists")}whereNotExists(X){return this.where(X,"attribute_not_exists")}whereIn(X,$){return this.filterConditions.push({attribute:X,operator:"IN",values:$}),this}select(...X){return this.projectionAttrs.push(...X),this}limit(X){return this.limitValue=X,this}ascending(){return this.scanForward=!0,this}descending(){return this.scanForward=!1,this}consistentRead(X=!0){return this.consistentReadValue=X,this}startFrom(X){return this.startKey=X,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 X=this.buildQueryParams(),$={TableName:X.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if(X.indexName)$.IndexName=X.indexName;let Z=0;if(X.keyConditions.length>0){let Y=[];for(let U of X.keyConditions){let _=`#key${Z}`;if($.ExpressionAttributeNames[_]=U.attribute,U.operator==="begins_with"){let Q=`:keyval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`begins_with(${_}, ${Q})`)}else if(U.operator==="BETWEEN"){let Q=`:keyval${Z}a`,L=`:keyval${Z}b`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.values?.[0]}).v,$.ExpressionAttributeValues[L]=this.driver.marshall({v:U.values?.[1]}).v,Y.push(`${_} BETWEEN ${Q} AND ${L}`)}else{let Q=`:keyval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${_} ${U.operator} ${Q}`)}Z++}$.KeyConditionExpression=Y.join(" AND ")}if(X.filterConditions&&X.filterConditions.length>0){let Y=[];for(let U of X.filterConditions){let _=`#flt${Z}`;if($.ExpressionAttributeNames[_]=U.attribute,U.operator==="attribute_exists")Y.push(`attribute_exists(${_})`);else if(U.operator==="attribute_not_exists")Y.push(`attribute_not_exists(${_})`);else if(U.operator==="begins_with"||U.operator==="contains"){let Q=`:fltval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${U.operator}(${_}, ${Q})`)}else if(U.operator==="BETWEEN"){let Q=`:fltval${Z}a`,L=`:fltval${Z}b`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.values?.[0]}).v,$.ExpressionAttributeValues[L]=this.driver.marshall({v:U.values?.[1]}).v,Y.push(`${_} BETWEEN ${Q} AND ${L}`)}else if(U.operator==="IN"){let Q=(U.values??[]).map((L,z)=>`:fltval${Z}_${z}`);U.values?.forEach((L,z)=>{$.ExpressionAttributeValues[`:fltval${Z}_${z}`]=this.driver.marshall({v:L}).v}),Y.push(`${_} IN (${Q.join(", ")})`)}else{let Q=`:fltval${Z}`;$.ExpressionAttributeValues[Q]=this.driver.marshall({v:U.value}).v,Y.push(`${_} ${U.operator} ${Q}`)}Z++}$.FilterExpression=Y.join(" AND ")}if(X.projectionAttributes&&X.projectionAttributes.length>0){let Y=[];for(let U of X.projectionAttributes){let _=`#proj${Z}`;$.ExpressionAttributeNames[_]=U,Y.push(_),Z++}$.ProjectionExpression=Y.join(", ")}if(X.limit!==void 0)$.Limit=X.limit;if(X.scanIndexForward!==void 0)$.ScanIndexForward=X.scanIndexForward;if(X.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(X.exclusiveStartKey);if(X.consistentRead)$.ConsistentRead=X.consistentRead;if(Object.keys($.ExpressionAttributeNames).length===0)delete $.ExpressionAttributeNames;if(Object.keys($.ExpressionAttributeValues).length===0)delete $.ExpressionAttributeValues;return $}toScanRequest(){let X=this.buildScanParams(),$={TableName:X.tableName};if(X.indexName)$.IndexName=X.indexName;if(X.filterConditions&&X.filterConditions.length>0){let{expression:Z,expressionAttributeNames:Y,expressionAttributeValues:U}=this.driver.buildFilterExpression(X.filterConditions);$.FilterExpression=Z,$.ExpressionAttributeNames=Y,$.ExpressionAttributeValues=U}if(X.projectionAttributes&&X.projectionAttributes.length>0){let{expression:Z,expressionAttributeNames:Y}=this.driver.buildProjectionExpression(X.projectionAttributes);$.ProjectionExpression=Z,$.ExpressionAttributeNames={...$.ExpressionAttributeNames,...Y}}if(X.limit!==void 0)$.Limit=X.limit;if(X.exclusiveStartKey)$.ExclusiveStartKey=this.driver.marshall(X.exclusiveStartKey);if(X.consistentRead)$.ConsistentRead=X.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 X=this.toQueryRequest(),$=await this.client.query(X);return{items:$.Items?.map((Z)=>this.driver.unmarshall(Z)),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 X=this.toScanRequest(),$=await this.client.scan(X);return{items:$.Items?.map((Z)=>this.driver.unmarshall(Z)),count:$.Count,scannedCount:$.ScannedCount,lastEvaluatedKey:$.LastEvaluatedKey?this.driver.unmarshall($.LastEvaluatedKey):void 0,consumedCapacity:$.ConsumedCapacity}}async getAll(){let X=[],$;do{if($)this.startFrom($);let Z=this.keyConditions.length>0?await this.query():await this.scan();if(Z.items)X.push(...Z.items);$=Z.lastEvaluatedKey}while($);return X}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 X=this.keyConditions.length>0?this.toQueryRequest():this.toScanRequest();return X.Select="COUNT",(this.keyConditions.length>0?await this.client.query(X):await this.client.scan(X)).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 b9{driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor(X){this.driver=bX(X.config),this.client=X.client,this.tableName=X.config.tableName??""}table(X){return this.tableName=X,this}key(X){return this.keyData=X,this}item(X){return this.itemData=X,this}set(X,$){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[X]=$,this}setMany(X){if(!this.updateExpressions.set)this.updateExpressions.set={};return Object.assign(this.updateExpressions.set,X),this}remove(X){if(!this.updateExpressions.remove)this.updateExpressions.remove=[];return this.updateExpressions.remove.push(X),this}add(X,$){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[X]=$,this}deleteFromSet(X,$){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[X]=$,this}condition(X){return this.conditionExpr=X,this}ifNotExists(X="pk"){return this.conditionExpr=`attribute_not_exists(${X})`,this}ifExists(X="pk"){return this.conditionExpr=`attribute_exists(${X})`,this}returnOld(){return this.returnValuesOption="ALL_OLD",this}returnNew(){return this.returnValuesOption="ALL_NEW",this}toPutRequest(){let X={TableName:this.tableName,Item:this.driver.marshall(this.itemData)};if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toUpdateRequest(){let X={TableName:this.tableName,Key:this.driver.marshall(this.keyData)},{expression:$,expressionAttributeNames:Z,expressionAttributeValues:Y}=this.driver.buildUpdateExpression(this.updateExpressions);if($)X.UpdateExpression=$,X.ExpressionAttributeNames=Z,X.ExpressionAttributeValues=Y;if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toDeleteRequest(){let X={TableName:this.tableName,Key:this.driver.marshall(this.keyData)};if(this.conditionExpr)X.ConditionExpression=this.conditionExpr;if(this.returnValuesOption!=="NONE")X.ReturnValues=this.returnValuesOption;return X}toGetRequest(){return{TableName:this.tableName,Key:this.driver.marshall(this.keyData)}}async put(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toPutRequest(),$=await this.client.putItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toUpdateRequest(),$=await this.client.updateItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toDeleteRequest(),$=await this.client.deleteItem(X);if($.Attributes)return this.driver.unmarshall($.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let X=this.toGetRequest(),$=await this.client.getItem(X);if($.Item)return this.driver.unmarshall($.Item);return}}function zO(X){return new gX(X)}function LO(X){return new b9(X)}function jO(X){let $=bX(X.config);return{query:()=>new gX(X),item:()=>new b9(X),driver:$,registerEntity:(Z)=>$.registerEntity(Z),buildKey:(Z,Y)=>$.buildPrimaryKey(Z,Y)}}var F5=()=>{};class O7{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor(X){this.config=X,this.pkAttribute=X.pkAttribute??"pk",this.skAttribute=X.skAttribute??"sk",this.typeAttribute=X.typeAttribute??"_type";for(let $ of X.entities)this.entities.set($.name,$)}getEntity(X){return this.entities.get(X)}registerEntity(X){this.entities.set(X.name,X)}buildKey(X,$){let Z=this.entities.get(X);if(!Z)throw Error(`Entity not found: ${X}`);let Y=this.interpolatePattern(Z.pkPattern,$),U=this.interpolatePattern(Z.skPattern,$);return{pk:Y,sk:U}}buildGSIKey(X,$,Z){let Y=this.entities.get(X);if(!Y)throw Error(`Entity not found: ${X}`);let U=Y.indexes?.find((L)=>L.name===$);if(!U)throw Error(`GSI not found: ${$} for entity ${X}`);let _=this.interpolatePattern(U.pkPattern,Z),Q=U.skPattern?this.interpolatePattern(U.skPattern,Z):void 0;return{pk:_,sk:Q}}createItem(X,$){let{pk:Z,sk:Y}=this.buildKey(X,$),U=this.entities.get(X),_={[this.pkAttribute]:Z,[this.skAttribute]:Y,[this.typeAttribute]:X,...$};if(U.indexes)for(let Q of U.indexes){let L=this.buildGSIKey(X,Q.name,$),z=this.config.indexes?.find((j)=>j.name===Q.name);if(z){if(_[z.pkAttribute]=L.pk,z.skAttribute&&L.sk)_[z.skAttribute]=L.sk}}return _}parseEntityType(X){if(X[this.typeAttribute])return X[this.typeAttribute];let $=X[this.pkAttribute];if(!$)return;for(let[Z,Y]of this.entities){let U=Y.pkPattern.split("${")[0];if($.startsWith(U))return Z}return}parseItem(X){let $=this.parseEntityType(X);if(!$)return;let{[this.pkAttribute]:Z,[this.skAttribute]:Y,[this.typeAttribute]:U,..._}=X;return{type:$,data:_}}getEntityPrefix(X){let $=this.entities.get(X);if(!$)throw Error(`Entity not found: ${X}`);return $.pkPattern.split("${")[0]}generateTableDefinition(){let X=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],$=[];if(this.config.indexes)for(let Z of this.config.indexes){if(!X.find((Y)=>Y.name===Z.pkAttribute))X.push({name:Z.pkAttribute,type:"S"});if(Z.skAttribute&&!X.find((Y)=>Y.name===Z.skAttribute))X.push({name:Z.skAttribute,type:"S"});$.push({indexName:Z.name,keySchema:{partitionKey:Z.pkAttribute,sortKey:Z.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:X,globalSecondaryIndexes:$.length>0?$:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern(X,$){return X.replace(/\$\{(\w+)\}/g,(Z,Y)=>{if(!(Y in $))throw Error(`Missing value for pattern key: ${Y}`);return String($[Y])})}}class J7{manager;entityName;options;constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z}async create(X){let $=this.manager.createItem(this.entityName,X),Z=new b9(this.options).table(this.options.config.tableName).item($).ifNotExists("pk");if(this.options.client)await Z.put();return X}async get(X){let{pk:$,sk:Z}=this.manager.buildKey(this.entityName,X),Y=new b9(this.options).table(this.options.config.tableName).key({pk:$,sk:Z});if(!this.options.client)throw Error("DynamoDB client not provided");let U=await Y.get();if(!U)return;return this.manager.parseItem(U)?.data}async update(X,$){let{pk:Z,sk:Y}=this.manager.buildKey(this.entityName,X),U=new b9(this.options).table(this.options.config.tableName).key({pk:Z,sk:Y}).setMany($).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let _=await U.update();if(!_)return;return this.manager.parseItem(_)?.data}async delete(X){let{pk:$,sk:Z}=this.manager.buildKey(this.entityName,X),Y=new b9(this.options).table(this.options.config.tableName).key({pk:$,sk:Z});if(!this.options.client)throw Error("DynamoDB client not provided");return await Y.delete(),!0}query(){return new W7(this.manager,this.entityName,this.options)}async findAll(){let X=this.manager.typeAttribute??"_type",$=new gX(this.options).table(this.options.config.tableName).whereEquals(X,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await $.getAll()).map((Y)=>this.manager.parseItem(Y)).filter((Y)=>Y!==void 0).map((Y)=>Y.data)}}class W7{manager;entityName;options;builder;pkValue;skConditions=[];constructor(X,$,Z){this.manager=X,this.entityName=$,this.options=Z,this.builder=new gX(Z).table(Z.config.tableName)}wherePartitionKey(X){let{pk:$}=this.manager.buildKey(this.entityName,X);this.pkValue=$;let Z=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(Z,$),this}whereSortKey(X){let{sk:$}=this.manager.buildKey(this.entityName,X),Z=this.manager.skAttribute??"sk";return this.builder.whereSortKey(Z,$),this}whereSortKeyBeginsWith(X){let $=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith($,X),this}useIndex(X,$){let Z=this.manager.buildGSIKey(this.entityName,X,$),Y=this.manager.config.indexes?.find((U)=>U.name===X);if(!Y)throw Error(`GSI configuration not found: ${X}`);return this.builder.index(X),this.builder.wherePartitionKey(Y.pkAttribute,Z.pk),this}where(X,$,Z){return this.builder.where(X,$,Z),this}select(...X){return this.builder.select(...X),this}limit(X){return this.builder.limit(X),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 sL(X){return new O7(X)}function oL(X,$,Z){return new J7(X,$,Z)}var rL,V7=e(()=>{F5(),rL={simpleEntity:(X,$="id")=>({name:X,pkPattern:`${X.toUpperCase()}#\${${$}}`,skPattern:"METADATA",keyFields:[$]}),oneToMany:(X,$,Z="id",Y="id")=>({parent:{name:X,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]},child:{name:$,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`,keyFields:[Z,Y]}}),manyToMany:(X,$,Z="id",Y="relatedId")=>({entity:{name:X,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:"METADATA",keyFields:[Z]},relation:{name:$,pkPattern:`${X.toUpperCase()}#\${${Z}}`,skPattern:`${$.toUpperCase()}#\${${Y}}`,keyFields:[Z,Y],indexes:[{name:"GSI1",pkPattern:`${X.toUpperCase()}#\${${Y}}`,skPattern:`${$.toUpperCase()}#\${${Z}}`}]}}),hierarchical:(X,$="rootId",Z="path")=>({name:X,pkPattern:`ROOT#\${${$}}`,skPattern:`PATH#\${${Z}}`,keyFields:[$,Z]})}});function F6(X,$){let Z={};for(let[Y,U]of Object.entries(X))if(U)Z[Y]=U.replace(/\{([^}]+)\}/g,(_,Q)=>{return $[Q]!==void 0?String($[Q]):`{${Q}}`});return Z}async function aL(X){return{models:new Map}}function EO(X){return X}function GO(X){return X}function FO(X){return X}function OO(X){return X}class I7{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor(X){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...X};let $={region:X.region,endpoint:X.endpoint,credentials:X.credentials,tableName:X.tableName};this.driver=bX($);let Z={tableName:X.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=sL(Z),this.queryBuilderOptions={config:$}}setClient(X){return this.queryBuilderOptions.client=X,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let X=await aL({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),$=[];for(let[,Z]of X.models)this.registerParsedModel(Z),$.push(Z);return $}registerModel(X){let $=this.parseWithTooling(X);return this.registerParsedModel($)}registerParsedModel(X){this.models.set(X.name,X);let $=this.toSingleTableEntity(X);this.singleTableManager.registerEntity($);let Z=this.toEntityMapping(X);return this.driver.registerEntity(Z),X}registerModels(X){return X.map(($)=>this.registerModel($))}getModel(X){return this.models.get(X)}getAllModels(){return Array.from(this.models.values())}repository(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return oL(this.singleTableManager,X,this.queryBuilderOptions)}query(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new gX(this.queryBuilderOptions).table(this.config.tableName).entity(X)}item(X){if(!this.models.get(X))throw Error(`Model not found: ${X}`);return new b9(this.queryBuilderOptions).table(this.config.tableName)}buildKey(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=F6(Z.keyPatterns,$);return{pk:Y.pk,sk:Y.sk}}createItem(X,$){let Z=this.models.get(X);if(!Z)throw Error(`Model not found: ${X}`);let Y=F6(Z.keyPatterns,$),U=Y.pk,_=Y.sk,Q={[this.config.pkAttribute]:U,[this.config.skAttribute]:_,[this.config.entityTypeAttribute]:Z.name,...$};if(Z.hasTimestamps){let L=new Date().toISOString();if(!Q.createdAt)Q.createdAt=L;Q.updatedAt=L}if(Z.hasVersioning){if(!Q._v)Q._v=1}return Q}parseItem(X){let $=X[this.config.entityTypeAttribute];if(!$)return;let{[this.config.pkAttribute]:Z,[this.config.skAttribute]:Y,[this.config.entityTypeAttribute]:U,..._}=X;return{type:$,data:_}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns(X){let $=this.models.get(X);if(!$)throw Error(`Model not found: ${X}`);return $.accessPatterns}parseWithTooling(X){let $=X.name.toUpperCase(),Z=X.primaryKey??"id",Y=this.config.keyDelimiter,U=this.parseAttributes(X),_=this.parseRelationships(X,Z),Q={pk:`${$}${Y}{${Z}}`,sk:`${$}${Y}{${Z}}`,...this.deriveGSIKeyPatterns($,Z,Y,_)},L=this.deriveAccessPatterns(X.name,$,Z,_);return{name:X.name,entityType:$,primaryKey:Z,attributes:U,relationships:_,keyPatterns:Q,accessPatterns:L,traits:X.traits??{},hasTimestamps:X.traits?.useTimestamps??!1,hasSoftDeletes:X.traits?.useSoftDeletes??!1,hasUuid:X.traits?.useUuid??!1,hasTtl:X.traits?.useTtl??!1,hasVersioning:X.traits?.useVersioning??!1,original:X}}parseAttributes(X){let $=[];if($.push({name:X.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),X.attributes)for(let[Z,Y]of Object.entries(X.attributes))$.push({name:Z,fillable:Y.fillable??!0,required:Y.required??!1,nullable:Y.nullable??!0,unique:Y.unique??!1,hidden:Y.hidden??!1,defaultValue:Y.default,cast:Y.cast,dynamoDbType:this.inferDynamoDBType(Y)});if(X.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(X.traits?.useSoftDeletes)$.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return $}inferDynamoDBType(X){if(X.cast){let $=X.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(X.validation?.rule){let $=String(X.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(X,$){let Z=[];if(X.hasOne)for(let Y of X.hasOne)Z.push({type:"hasOne",relatedModel:Y,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(X.hasMany)for(let Y of X.hasMany)Z.push({type:"hasMany",relatedModel:Y,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,requiresGsi:!1});if(X.belongsTo)for(let Y of X.belongsTo)Z.push({type:"belongsTo",relatedModel:Y,foreignKey:`${Y.toLowerCase()}Id`,localKey:$,requiresGsi:!0});if(X.belongsToMany){let Y=Array.isArray(X.belongsToMany)?X.belongsToMany:Object.values(X.belongsToMany);for(let U of Y){let _=typeof U==="string"?U:U?.model;if(!_)continue;let Q=[X.name,_].sort();Z.push({type:"belongsToMany",relatedModel:_,foreignKey:`${X.name.toLowerCase()}Id`,localKey:$,pivotEntity:Q.join(""),requiresGsi:!0})}}return Z}deriveGSIKeyPatterns(X,$,Z,Y){let U={},_=1;for(let Q of Y)if(Q.requiresGsi&&_<=5)U[`gsi${_}pk`]=`${Q.relatedModel.toUpperCase()}${Z}{${Q.foreignKey}}`,U[`gsi${_}sk`]=`${X}${Z}{${$}}`,Q.gsiIndex=_,_++;return U}deriveAccessPatterns(X,$,Z,Y){let U=[];U.push({name:`Get ${X} by ID`,description:`Retrieve a single ${X} by its primary key`,entityType:$,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${$}#123`,exampleSk:`${$}#123`,efficient:!0}),U.push({name:`List all ${X}s`,description:`Scan all ${X} entities`,entityType:$,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:$,efficient:!1});for(let _ of Y){if(_.type==="hasMany")U.push({name:`Get ${_.relatedModel}s for ${X}`,description:`Query ${_.relatedModel}s related to a ${X}`,entityType:$,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${$}#123`,exampleSk:`${_.relatedModel.toUpperCase()}#`,efficient:!0});if(_.gsiIndex){let Q=`GSI${_.gsiIndex}`;U.push({name:`Get ${X}s by ${_.relatedModel}`,description:`Query ${X}s by their related ${_.relatedModel}`,entityType:$,operation:"query",index:Q,keyCondition:`gsi${_.gsiIndex}pk = :pk`,examplePk:`${_.relatedModel.toUpperCase()}#123`,efficient:!0})}}return U}toSingleTableEntity(X){let $=this.extractKeyFields(X.keyPatterns.pk);return{name:X.name,pkPattern:X.keyPatterns.pk,skPattern:X.keyPatterns.sk,keyFields:$,indexes:this.extractGSIPatterns(X.keyPatterns)}}extractKeyFields(X){let $=X.match(/\{([^}]+)\}/g);if(!$)return[];return $.map((Z)=>Z.slice(1,-1))}extractGSIPatterns(X){let $=[];for(let Z=1;Z<=5;Z++){let Y=`gsi${Z}pk`,U=`gsi${Z}sk`;if(X[Y])$.push({name:`GSI${Z}`,pkPattern:X[Y],skPattern:X[U]})}return $.length>0?$:void 0}toEntityMapping(X){return{entityType:X.name,pkPattern:X.keyPatterns.pk,skPattern:X.keyPatterns.sk}}buildGSIConfig(){let X=this.config.gsiConfig??{},$=[];if(X.gsi1pk)$.push({name:"GSI1",pkAttribute:X.gsi1pk,skAttribute:X.gsi1sk});if(X.gsi2pk)$.push({name:"GSI2",pkAttribute:X.gsi2pk,skAttribute:X.gsi2sk});if(X.gsi3pk)$.push({name:"GSI3",pkAttribute:X.gsi3pk,skAttribute:X.gsi3sk});return $}}function JO(X){return new I7(X)}function WO(X){return X.accessPatterns}function VO(X,$="#"){let Z=X.name.toUpperCase(),Y=X.primaryKey??"id";return{name:X.name,pkPattern:`${Z}${$}\${${Y}}`,skPattern:`${Z}${$}\${${Y}}`}}var tL=e(()=>{F5(),V7()});function K7(X){let $={};for(let Z of Object.keys(X)){let Y=X[Z],U=Y.definition??Y.getDefinition?.()??Y,_=U.table||`${String(U.name).toLowerCase()}s`,Q=U.attributes??{},L={};for(let z of Object.keys(Q))L[z]=void 0;$[_]={columns:L,primaryKey:U.primaryKey??"id"}}return $}async function dX(X){let $=X.cwd??Yj.cwd(),Z=X.modelsDir.startsWith("/")?X.modelsDir:`${$}/${X.modelsDir}`,Y={},U=eL(Z);for(let _ of U){let Q=`${Z}/${_}`;if(Xj(Q).isDirectory())continue;let z=Zj(Q);if(![".ts",".mts",".cts",".js",".mjs",".cjs"].includes(z))continue;let j=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,E=await import(`${Q}${j}`),V=E.default??E,G=V.definition??V.getDefinition?.()??V,J=$j(_,z),W=G.name??J;Y[W]={...G,name:W}}return Y}var Uj=()=>{};function c1(X){if(typeof X==="string")return{model:X};if(X&&typeof X==="object"&&typeof X.model==="string"){let $=X;return{model:$.model,foreignKey:$.foreignKey,onDelete:$.onDelete}}return null}function _j(X){if(!X)return[];return(Array.isArray(X)?X:typeof X==="object"?Object.values(X):[]).map(c1).filter((Z)=>Z!==null)}function Qj(X){let $={},Z={},Y={},U={},_={};for(let Q of Object.keys(X)){let L=X[Q],z=L.definition??L.getDefinition?.()??L,j=z.table||`${String(z.name).toLowerCase()}s`;$[Q]=j,Z[j]=Q,Y[j]=z.primaryKey??"id";let E=(J)=>{if(!J)return{};let W={};if(Array.isArray(J)){for(let F of J){let K=c1(F);if(K)W[K.model]=K.model}return W}if(typeof J==="object"){for(let[F,K]of Object.entries(J)){let D=c1(K);if(D)W[F]=D.model}return W}return{}},V=(J)=>{if(!J)return{};if(Array.isArray(J)){let W={};for(let F of J)if(typeof F==="string")W[F]=F;else if(F&&typeof F==="object"&&typeof F.model==="string")W[F.model]=F;return W}return J},G=(J)=>{if(!J)return{};return J};if(U[j]={hasOne:E(z.hasOne),hasMany:E(z.hasMany),belongsTo:E(z.belongsTo),belongsToMany:V(z.belongsToMany),hasOneThrough:G(z.hasOneThrough),hasManyThrough:G(z.hasManyThrough),morphOne:E(z.morphOne),morphMany:E(z.morphMany),morphTo:z.morphTo,morphToMany:E(z.morphToMany),morphedByMany:E(z.morphedByMany)},z.scopes&&typeof z.scopes==="object"){_[j]={};for(let J of Object.keys(z.scopes)){let W=z.scopes[J];if(typeof W==="function")_[j][J]=W}}}return{modelToTable:$,tableToModel:Z,primaryKeys:Y,relations:U,scopes:_,models:X}}var R7=()=>{};function n0(X){if(f.verbose)console.log(X)}function qX(X){return X.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/(\d)([A-Z])/gi,"$1_$2").toLowerCase()}function jj(X){let $=X;while($!==O6($)){if(D7(O5($,"package.json")))return $;$=O6($)}return M7.cwd()}function Ej(){let X=jj(M7.cwd()),$=O5(X,"database","migrations");if(!D7($))zj($,{recursive:!0}),n0(`-- Created SQL directory: ${$}`);return $}function H7(X,$){if(!X)return!1;let Z=Ej();q$++;let U=`${V5?String(q$).padStart(10,"0"):String(Math.floor(Date.now()/1000)+q$)}-${$}.sql`,_=O5(Z,U);return Lj(_,X),n0(`-- Migration file created: ${U}`),x9++,!0}function J6(X){if(X.endsWith("_id"))return"bigint";if(X.endsWith("_at"))return"datetime";if(X.startsWith("is_")||X.startsWith("has_"))return"boolean";return}function W6(X){if(typeof X==="string"||typeof X==="number"||typeof X==="boolean"||typeof X==="bigint"||X instanceof Date)return X;return}function Gj(X){if(X&&typeof X==="object"&&"name"in X){let $=X;if($.name==="enum"||$.getRules&&Array.isArray($.getRules())){if($.enumValues&&Array.isArray($.enumValues))return $.enumValues.map((Z)=>String(Z));if($._values&&Array.isArray($._values))return $._values.map((Z)=>String(Z));if($.values&&Array.isArray($.values))return $.values.map((Z)=>String(Z))}}if(X&&typeof X==="object"){let $=X,Z=$.allowedValues||$.enumValues||$._values||$.values;if(Array.isArray(Z)&&Z.length>0)return Z.map((Y)=>String(Y))}return}function C7(X){if(!X?.rules||!Array.isArray(X.rules))return;for(let $ of X.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}function Fj(X){if(!X||typeof X!=="object")return;let $=X;if($.name)switch(String($.name).toLowerCase()){case"string":case"text":{let Y=C7($);return Y&&Y>255?"text":"string"}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"json":return"json";case"enum":return"enum"}if($.type){let Z=String($.type).toLowerCase();if(Z==="string"||Z==="text")return"string";if(Z==="integer"||Z==="int")return"integer";if(Z==="bigint")return"bigint";if(Z==="float")return"float";if(Z==="number")return"integer";if(Z==="boolean")return"boolean";if(Z==="date")return"date";if(Z==="datetime")return"datetime";if(Z==="json")return"json"}return}function J5(X,$){let Z=Qj(X),Y=[];for(let Q of Object.keys(X)){let L=X[Q],z=L.table||`${String(L.name).toLowerCase()}s`,j=L.primaryKey??"id",E=L.autoIncrement!==!1,V=L.attributes??{},G=[],J=[];if(!V[j])G.push({name:qX(j),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});for(let H of Object.keys(V)){let x=V[H],h=qX(H),c=!0,y,g,v=H===j;if(y=Fj(x.validation?.rule),!y||y==="enum"){let o=Gj(x.validation?.rule);if(o&&o.length>0)y="enum",g=o}if(!y)y=J6(h);if(!y){let o=W6(x.default);if(typeof o==="string")y=o.length>255?"text":"string";else if(typeof o==="number")y=Number.isInteger(o)?"integer":"float";else if(typeof o==="boolean")y="boolean";else if(typeof o==="bigint")y="bigint";else if(o instanceof Date)y="datetime"}if(!y)y=v?"bigint":"string";let n=y==="string"?C7(x.validation?.rule):void 0,p={name:h,type:y,isPrimaryKey:v,isUnique:Boolean(x.unique),isNullable:!0,hasDefault:typeof x.default<"u",defaultValue:W6(x.default),enumValues:g,maxLength:typeof n==="number"&&n>0&&n<=255?n:void 0};if(h.endsWith("_id")&&x.foreignKey!==!1)if(typeof x.foreignKey==="object"&&x.foreignKey!==null){let o=x.foreignKey;if(p.references={table:o.table,column:o.column??"id",onDelete:o.onDelete,onUpdate:o.onUpdate},o.nullable!==void 0)p.isNullable=o.nullable}else{let D0=h.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(o0,a,B)=>B.toUpperCase()),M0=Z.modelToTable[D0];if(M0){let o0=Z.primaryKeys[M0]??"id";p.references={table:M0,column:o0}}}G.push(p)}let W=_j(L.belongsTo);for(let H of W){let x=H.foreignKey??`${qX(H.model)}_id`;if(G.some((y)=>y.name===x))continue;let h=Z.modelToTable[H.model];if(!h)continue;let c=Z.primaryKeys[h]??"id";G.push({name:x,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:{table:h,column:c,onDelete:H.onDelete}})}let F=L.traits;if(F?.useTimestamps??F?.timestampable??!1){if(!G.some((H)=>H.name==="created_at"))G.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"});if(!G.some((H)=>H.name==="updated_at"))G.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(F?.useSoftDeletes??F?.softDeletable??!1){if(!G.some((H)=>H.name==="deleted_at"))G.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(F?.useUuid??!1){if(!G.some((H)=>H.name==="uuid"))G.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let H of L.indexes??[])J.push({name:H.name,columns:H.columns.map((x)=>qX(x)),type:H.unique?"unique":"index",where:H.where});for(let H of G)if(H.isUnique&&!H.isPrimaryKey)J.push({name:`${z}_${H.name}_unique`,columns:[H.name],type:"unique"});let T=Array.isArray(L.shardKey)?L.shardKey.map(qX):void 0,N=Array.isArray(L.sortKey)?L.sortKey.map(qX):void 0,q=L.tableKind;Y.push({table:z,columns:G,indexes:J,shardKey:T,sortKey:N,tableKind:q})}let U=new Set(Y.map((Q)=>Q.table));function _(Q){if(!U.has(Q.table))U.add(Q.table),Y.push(Q)}for(let Q of Object.keys(X)){let L=X[Q],z=L?.traits??{},j=L.table||`${String(L.name).toLowerCase()}s`,E=j.replace(/s$/,"");if(z.likeable){let V=typeof z.likeable==="object"?z.likeable:{},G=V.table||`${j}_likes`,J=V.foreignKey||`${E}_id`;_({table:G,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:J,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${G}_user_target_unique`,columns:["user_id",J],type:"unique"}]})}if(z.taggable)_({table:"taggable",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:!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:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(z.categorizable)_({table:"categorizable",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:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_slug_unique",columns:["slug"],type:"unique"}]}),_({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:"categorizable",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:"CURRENT_TIMESTAMP"}],indexes:[{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let Q of Object.keys(X)){let L=X[Q],z=L?.belongsToMany;if(!z||typeof z!=="object"||Array.isArray(z))continue;let j=L.table||`${String(L.name).toLowerCase()}s`,E=j.replace(/s$/,"");for(let[V,G]of Object.entries(z)){let J=G;if(!J||typeof J!=="object")continue;if(J.through)continue;let W=J.pivot;if(!W||!W.columns&&!W.timestamps&&!W.uniques)continue;let F=J.model,D=X[F]?.table||`${String(F).toLowerCase()}s`,w=D.replace(/s$/,""),T=J.table||[E,w].sort().join("_"),N=J.foreignKey||`${E}_id`,q=J.relatedKey||`${w}_id`,H=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:N,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:j,column:"id"}},{name:q,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:D,column:"id"}}];if(W.columns)for(let[c,y]of Object.entries(W.columns)){let g=y,v=J6(c)??"string";H.push({name:c,type:v,isPrimaryKey:!1,isUnique:!1,isNullable:g?.nullable??!1,hasDefault:g?.default!==void 0,defaultValue:g?.default})}if(W.timestamps)H.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:"CURRENT_TIMESTAMP"}),H.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let x=[],h=W.uniques&&W.uniques.length>0?W.uniques:[[N,q]];for(let c=0;c<h.length;c++){let y=h[c];x.push({name:`${T}_${y.join("_")}_unique${c>0?`_${c}`:""}`,columns:[...y],type:"unique"})}_({table:T,columns:H,indexes:x})}}return{dialect:$.dialect,tables:Y}}function W5(X,$={}){q$=0,x9=0,f9=0,V5=!0;let Z=$.dryRun?()=>!1:H7,Y=[],U=ZX(X.dialect);for(let Q of X.tables){let L=[],z=new Set;for(let V of Q.columns)if(V.type==="enum"&&V.enumValues&&V.enumValues.length>0){let G=`${Q.table}_${V.name}_type`;if(V.enumTypeName=G,!z.has(G)){let J=U.createEnumType(G,V.enumValues);if(J)L.push(J);z.add(G)}}let j=U.createTable(Q);L.push(j),Y.push(...L);let E=L.join(`
401
462
 
402
- `);S9(F,`create-${L.table}-table`)}for(let L of $.tables)for(let j of L.columns)if(j.references){let Y=X.addForeignKey(L.table,j.name,j.references.table,j.references.column,j.references.onDelete,j.references.onUpdate);Z.push(Y),S9(Y,`alter-${L.table}-${j.name}`)}for(let L of $.tables)for(let j of L.indexes){let Y=X.createIndex(L.table,j);Z.push(Y),S9(Y,`create-${j.name}-index-in-${L.table}`)}if(R9+T9===0)console.log("-- Nothing to migrate");else{let L=[];if(R9>0)L.push(`${R9} created`);if(T9>0)L.push(`${T9} updated`);console.log(`-- Migration files: ${L.join(", ")}`)}return Z}function xQ($){return hZ($).join(`
403
- `)}function BQ($,Z){return fX($,Z).join(`
404
- `)}function jz($){let Z=tX("crypto");function X(L){if(L==null||typeof L!=="object"||L instanceof Date)return L;if(Array.isArray(L))return L.map((Y)=>X(Y));let j={};for(let Y of Object.keys(L).sort())j[Y]=X(L[Y]);return j}let _=JSON.stringify(X($));return Z.createHash("sha256").update(_).digest("hex")}function p7($){let Z={};for(let X of $)Z[X.table]=X;return Z}function g1($){let Z={};for(let X of $)Z[X.name]=X;return Z}function Yz($,Z){if($.type!==Z.type)return!0;if($.isNullable!==Z.isNullable)return!0;if($.hasDefault!==Z.hasDefault)return!0;if($.defaultValue!==Z.defaultValue)return!0;if($.isUnique!==Z.isUnique)return!0;if($.type==="enum"&&Z.type==="enum"){let X=($.enumValues||[]).sort().join(","),_=(Z.enumValues||[]).sort().join(",");if(X!==_)return!0}return!1}function d7($){let Z={};for(let X of $){let _=`${X.type}:${X.name}:${X.columns.join(",")}`;Z[_]=X}return Z}function fX($,Z){if(!$||$.dialect!==Z.dialect)return hZ(Z);t8=0,R9=0,T9=0,yZ=!1;let X=[],_=p9(Z.dialect),L=p7($.tables),j=p7(Z.tables);for(let F of Object.keys(L))if(!j[F]){let E=_.dropTable(F);X.push(E),S9(E,`drop-${F}-table`),console.log(`-- Detected dropped table: ${F}`)}for(let F of Object.keys(j))if(!L[F]){let E=j[F],U=[],V=new Set;for(let K of E.columns)if(K.type==="enum"&&K.enumValues&&K.enumValues.length>0){let I=`${K.name}_type`;if(!V.has(I)){let C=_.createEnumType(I,K.enumValues);if(C)U.push(C);V.add(I)}}let Q=_.createTable(E);U.push(Q),X.push(...U);let O=U.join(`
463
+ `);Z(E,`create-${Q.table}-table`)}for(let Q of X.tables)for(let L of Q.columns)if(L.references){let z=U.addForeignKey(Q.table,L.name,L.references.table,L.references.column,L.references.onDelete,L.references.onUpdate);if(!z)continue;Y.push(z),Z(z,`alter-${Q.table}-${L.name}`)}for(let Q of X.tables)for(let L of Q.indexes){let z=U.createIndex(Q.table,L);Y.push(z),Z(z,`create-${L.name}-index-in-${Q.table}`)}if(x9+f9===0)n0("-- Nothing to migrate");else{let Q=[];if(x9>0)Q.push(`${x9} created`);if(f9>0)Q.push(`${f9} updated`);n0(`-- Migration files: ${Q.join(", ")}`)}return Y}function CO(X){return W5(X).join(`
464
+ `)}function wO(X,$){return Kj(X,$).join(`
465
+ `)}function Oj(X){let $=u7("crypto");function Z(U){if(U==null||typeof U!=="object"||U instanceof Date)return U;if(Array.isArray(U))return U.map((Q)=>Z(Q));let _={};for(let Q of Object.keys(U).sort())_[Q]=Z(U[Q]);return _}let Y=JSON.stringify(Z(X));return $.createHash("sha256").update(Y).digest("hex")}function V6(X){let $={};for(let Z of X)$[Z.table]=Z;return $}function j8(X){let $={};for(let Z of X)$[Z.name]=Z;return $}function m1(X,$){if($==="sqlite"){if(X.name.endsWith("_id")&&JU(X.type))return"INTEGER";switch(X.type){case"string":case"text":case"date":case"datetime":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"}}return X.type}function u1(X){if(!X.hasDefault||X.defaultValue===void 0)return;let $=X.defaultValue;if($ instanceof Date)return $.toISOString();if(typeof $==="boolean")return $?"1":"0";if(typeof $==="bigint"||typeof $==="number")return String($);let Z=String($).trim();if(Z=Z.replace(/::[\w ]+$/i,"").trim(),Z.startsWith("'")&&Z.endsWith("'")||Z.startsWith('"')&&Z.endsWith('"'))Z=Z.slice(1,-1);let Y=Z.toUpperCase();if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(Y))return Y==="NOW()"?"CURRENT_TIMESTAMP":Y;if(X.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(Z))return"1";if(/^(?:0|f|false|no)$/i.test(Z))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(Z))return String(Number(Z));return Z}function Jj(X,$,Z){if(m1(X,Z)!==m1($,Z))return!0;if(X.isNullable!==$.isNullable)return!0;if(X.hasDefault!==$.hasDefault)return!0;if(u1(X)!==u1($))return!0;if(X.isUnique!==$.isUnique)return!0;if(X.type==="enum"&&$.type==="enum"){let Y=(X.enumValues||[]).slice().sort().join(","),U=($.enumValues||[]).slice().sort().join(",");if(Y!==U)return!0}return!1}function I6(X,$){return JSON.stringify([m1(X,$),X.isPrimaryKey,X.isUnique,X.isNullable,X.hasDefault,u1(X)??null,(X.enumValues??[]).slice().sort(),X.references?[X.references.table,X.references.column,X.references.onDelete??null,X.references.onUpdate??null]:null])}function Wj(X,$,Z){let Y=Object.keys(X).filter((E)=>!$[E]),U=Object.keys($).filter((E)=>!X[E]),_=new Map,Q=new Map;for(let E of Y){let V=I6(X[E],Z),G=_.get(V)??[];G.push(E),_.set(V,G)}for(let E of U){let V=I6($[E],Z),G=Q.get(V)??[];G.push(E),Q.set(V,G)}let L=[],z=new Set,j=new Set;for(let[E,V]of _){let G=Q.get(E);if(V.length===1&&G&&G.length===1)L.push({from:V[0],to:G[0]}),z.add(V[0]),j.add(G[0])}return{renames:L,removed:Y.filter((E)=>!z.has(E)),added:U.filter((E)=>!j.has(E))}}function Vj(X,$){let Z=X.columns.find((Y)=>Y.name===$);if(Z&&(Z.isPrimaryKey||Z.isUnique||Z.references))return!0;return X.indexes.some((Y)=>Y.columns.includes($))}function Ij(X,$){if(Boolean(X)!==Boolean($))return!0;if(!X||!$)return!1;let Z=(Y)=>(Y??"no action").toLowerCase();return X.table!==$.table||X.column!==$.column||Z(X.onDelete)!==Z($.onDelete)||Z(X.onUpdate)!==Z($.onUpdate)}function K6(X){let $={};for(let Z of X){let Y=`${Z.type}:${Z.name}:${Z.columns.join(",")}`;$[Y]=Z}return $}function w7(X,$,Z={}){if(!X||X.dialect!==$.dialect){let W=W5($,{dryRun:Z.dryRun}),F=$.tables.map((K)=>({kind:"create_table",table:K.table,destructive:!1,sql:""}));return{statements:W,operations:F}}let Y=Z.applyRenames!==!1,U=Z.dryRun?()=>!1:H7;q$=0,x9=0,f9=0,V5=!1;let _=[],Q=[],L=ZX($.dialect),z=$.dialect,j=V6(X.tables),E=V6($.tables);for(let W of Object.keys(j))if(!E[W]){let F=L.dropTable(W);_.push(F),Q.push({kind:"drop_table",table:W,destructive:!0,sql:F}),U(F,`drop-${W}-table`),n0(`-- Detected dropped table: ${W}`)}for(let W of Object.keys(E))if(!j[W]){let F=E[W],K=[],D=new Set;for(let N of F.columns)if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let q=`${F.table}_${N.name}_type`;if(N.enumTypeName=q,!D.has(q)){let H=L.createEnumType(q,N.enumValues);if(H)K.push(H);D.add(q)}}let w=L.createTable(F);K.push(w),_.push(...K),Q.push({kind:"create_table",table:F.table,destructive:!1,sql:w});let T=K.join(`
405
466
 
406
- `);S9(O,`create-${E.table}-table`)}for(let F of Object.keys(j))if(!L[F]){let E=j[F];for(let U of E.indexes){let V=_.createIndex(E.table,U);X.push(V),S9(V,`create-${U.name}-index-in-${E.table}`)}}for(let F of Object.keys(j))if(!L[F]){let E=j[F];for(let U of E.columns)if(U.references){let V=_.addForeignKey(E.table,U.name,U.references.table,U.references.column,U.references.onDelete,U.references.onUpdate);X.push(V),S9(V,`alter-${E.table}-${U.name}`)}}let Y=new Set;for(let F of Object.keys(j)){let E=L[F],U=j[F];if(!E)continue;let V=g1(E.columns),Q=g1(U.columns);for(let O of Object.keys(Q))if(!V[O]){let K=Q[O];if(K.type==="enum"&&K.enumValues&&K.enumValues.length>0){let I=`${K.name}_type`;if(!Y.has(I)){let C=_.createEnumType(I,K.enumValues);if(C)X.push(C),S9(C,`create-${I}-enum`);Y.add(I)}}}}for(let F of Object.keys(j)){let E=L[F],U=j[F];if(!E)continue;let V=g1(E.columns),Q=g1(U.columns),O=d7(E.indexes),K=d7(U.indexes),I=[],C=!1;for(let D of Object.keys(O))if(!K[D]){let M=O[D],J=_.dropIndex(U.table,M.name);I.push(J),X.push(J),console.log(`-- Detected dropped index: ${M.name} from ${U.table}`),C=!0}for(let D of Object.keys(V))if(!Q[D]){let M=_.dropColumn(U.table,D);I.push(M),X.push(M),console.log(`-- Detected dropped column: ${U.table}.${D}`),C=!0}for(let D of Object.keys(Q))if(V[D]&&Q[D]){let M=V[D],J=Q[D];if(Yz(M,J)){let N=_.modifyColumn(U.table,J);I.push(N),X.push(N),console.log(`-- Detected column type change: ${U.table}.${D} (${M.type} -> ${J.type})`),C=!0}}for(let D of Object.keys(Q))if(!V[D]){let M=Q[D],J=_.addColumn(U.table,M);if(I.push(J),X.push(J),console.log(`-- Detected new column: ${U.table}.${M.name}`),C=!0,M.references){let N=_.addForeignKey(U.table,M.name,M.references.table,M.references.column,M.references.onDelete,M.references.onUpdate);I.push(N),X.push(N)}}for(let D of Object.keys(K))if(!O[D]){let M=K[D],J=_.createIndex(U.table,M);I.push(J),X.push(J),console.log(`-- Detected new index: ${M.name} in ${U.table}`),C=!0}if(C){let D=I.join(`
467
+ `);U(T,`create-${F.table}-table`)}for(let W of Object.keys(E))if(!j[W]){let F=E[W];for(let K of F.indexes){let D=L.createIndex(F.table,K);_.push(D),Q.push({kind:"create_index",table:F.table,column:K.name,destructive:!1,sql:D}),U(D,`create-${K.name}-index-in-${F.table}`)}}for(let W of Object.keys(E))if(!j[W]){let F=E[W];for(let K of F.columns)if(K.references){let D=L.addForeignKey(F.table,K.name,K.references.table,K.references.column,K.references.onDelete,K.references.onUpdate);if(!D)continue;_.push(D),Q.push({kind:"add_foreign_key",table:F.table,column:K.name,destructive:!1,sql:D}),U(D,`alter-${F.table}-${K.name}`)}}let V=new Set;for(let W of Object.keys(E)){let F=j[W],K=E[W];if(!F)continue;let D=j8(F.columns),w=j8(K.columns);for(let T of Object.keys(w))if(!D[T]){let N=w[T];if(N.type==="enum"&&N.enumValues&&N.enumValues.length>0){let q=`${K.table}_${N.name}_type`;if(N.enumTypeName=q,!V.has(q)){let H=L.createEnumType(q,N.enumValues);if(H)_.push(H),Q.push({kind:"create_enum",table:K.table,column:N.name,destructive:!1,sql:H}),U(H,`create-${q}-enum`);V.add(q)}}}}for(let W of Object.keys(E)){let F=j[W],K=E[W];if(!F)continue;let D=j8(F.columns),w=j8(K.columns),T=K6(F.indexes),N=K6(K.indexes),q=[],H=Object.keys(D).filter((v)=>!w[v]),x=Object.keys(w).filter((v)=>!D[v]);if(Y){let v=Wj(D,w,z);q=v.renames,H=v.removed,x=v.added}let h=Object.keys(w).filter((v)=>D[v]&&Jj(D[v],w[v],z)),c=Object.keys(w).filter((v)=>D[v]&&Ij(D[v].references,w[v].references));if(z==="sqlite"){if(h.length>0||c.length>0||H.some((n)=>Vj(F,n))){let n={},p=new Map(q.map((a)=>[a.to,a.from]));for(let a of K.columns)if(D[a.name])n[a.name]=a.name;else if(p.has(a.name))n[a.name]=p.get(a.name);let o=`_qb_tmp_${K.table}`,D0=0;while((j[o]||E[o])&&D0<100)D0+=1,o=`_qb_tmp_${K.table}_${D0}`;let M0=L.rebuildTable({target:K,tempName:o,columnSource:n});_.push(M0);let o0=h.some((a)=>D[a].type!==w[a].type);Q.push({kind:"rebuild_table",table:K.table,destructive:H.length>0||o0,sql:M0});for(let a of q)Q.push({kind:"rename_column",table:K.table,from:a.from,to:a.to,destructive:!1,confidence:"high",sql:M0});for(let a of H)Q.push({kind:"drop_column",table:K.table,column:a,destructive:!0,sql:M0});n0(`-- Detected SQLite table rebuild required: ${K.table}`),U(M0,`alter-${K.table}-table`);continue}}let y=[],g=!1;for(let v of Object.keys(T))if(!N[v]){let n=T[v],p=L.dropIndex(K.table,n.name);y.push(p),_.push(p),Q.push({kind:"drop_index",table:K.table,column:n.name,destructive:!1,sql:p}),n0(`-- Detected dropped index: ${n.name} from ${K.table}`),g=!0}for(let v of q){let n=L.renameColumn(K.table,v.from,v.to);y.push(n),_.push(n),Q.push({kind:"rename_column",table:K.table,from:v.from,to:v.to,destructive:!1,confidence:"high",sql:n}),n0(`-- Detected renamed column: ${K.table}.${v.from} -> ${v.to}`),g=!0}for(let v of H){let n=L.dropColumn(K.table,v);y.push(n),_.push(n),Q.push({kind:"drop_column",table:K.table,column:v,destructive:!0,sql:n}),n0(`-- Detected dropped column: ${K.table}.${v}`),g=!0}for(let v of h){let n=D[v],p=w[v],o=L.modifyColumn(K.table,p);y.push(o),_.push(o),Q.push({kind:"modify_column",table:K.table,column:v,destructive:n.type!==p.type,sql:o}),n0(`-- Detected column change: ${K.table}.${v} (${n.type} -> ${p.type})`),g=!0}for(let v of c){let n=w[v];if(!n.references)continue;let p=L.addForeignKey(K.table,n.name,n.references.table,n.references.column,n.references.onDelete,n.references.onUpdate);if(!p)continue;y.push(p),_.push(p),Q.push({kind:"add_foreign_key",table:K.table,column:v,destructive:!1,sql:p}),n0(`-- Detected foreign-key change: ${K.table}.${v} -> ${n.references.table}(${n.references.column})`),g=!0}for(let v of x){let n=w[v],p=L.addColumn(K.table,n);if(y.push(p),_.push(p),Q.push({kind:"add_column",table:K.table,column:n.name,destructive:!1,sql:p}),n0(`-- Detected new column: ${K.table}.${n.name}`),g=!0,n.references){let o=L.addForeignKey(K.table,n.name,n.references.table,n.references.column,n.references.onDelete,n.references.onUpdate);if(o)y.push(o),_.push(o),Q.push({kind:"add_foreign_key",table:K.table,column:n.name,destructive:!1,sql:o})}}for(let v of Object.keys(N))if(!T[v]){let n=N[v],p=L.createIndex(K.table,n);y.push(p),_.push(p),Q.push({kind:"create_index",table:K.table,column:n.name,destructive:!1,sql:p}),n0(`-- Detected new index: ${n.name} in ${K.table}`),g=!0}if(g){let v=y.join(`
407
468
 
408
- `);S9(D,`alter-${U.table}-table`)}}if(R9+T9===0)console.log("-- Nothing to migrate");else{let F=[];if(R9>0)F.push(`${R9} created`);if(T9>0)F.push(`${T9} updated`);console.log(`-- Migration files: ${F.join(", ")}`)}if(X.length===0)return["-- No changes detected"];return X}var t8=0,R9=0,T9=0,yZ=!0,Fz=n(()=>{l$()});function hQ($){return $}class zz{get order(){return 100}get description(){return}}function yQ($){return $}var P0=n(async()=>{Y$(),Y$(),XY(),u7(),i$(),Y$(),await F9(),l$(),kZ(),hX(),mF(),Q_(),oF(),Fz(),PX()});await P0();export{VE as wipeDatabase,jO as waitReady,ej as validateSchema,$O as unsafe,RQ as unmarshallItem,SQ as toModelInstance,DQ as toDynamoDBItem,LE as tinker,IE as tableInfo,uL as startConsole,wQ as stacksModelToEntity,eE as sql,fE as showModel,dL as setQueryCacheMaxSize,lU as setConfig,GQ as seedModel,lj as runSeeders,rE as runSeeder,tU as runBenchmark,H8 as resolvePivot,v7 as resolveKeyPattern,Kj as resetDatabase,rU as resetConnection,iE as relationDiagram,fF as registerBrowserModels,cE as queryExplainAll,gE as ping,cF as parseStacksModels,OE as optimizeDatabase,fE as modelShow,Pj as migrateStatus,kE as migrateRollback,Jz as migrateModels,yE as migrateList,HE as migrateGenerate,MQ as marshallObject,tE as makeSeeder,RE as makeModel,W8 as loadModels,aU as iterateAllPivots,Rz as isDefinitionEqual,Dz as isBrowser,WE as introspect,Zj as inspectTable,FE as importData,F$ as hashTableDefinition,jz as hashMigrationPlan,yF as hasModel,f0 as getPlaceholders,m as getPlaceholder,hF as getModelRegistry,xF as getModel,p9 as getDialectDriver,V0 as getDatabase,iU as getConfig,Wz as getBrowserConfig,BF as getAllModels,xQ as generateSqlString,hZ as generateSql,v2 as generateMigration,BQ as generateDiffSqlString,fX as generateDiffSql,iE as generateDiagram,CQ as generateAccessPatterns,aE as freshDatabase,KE as file,j_ as extractTableDefinition,Y_ as extractModelSchema,YE as exportData,cE as explainAllQueries,GE as explain,Gj as executeMigration,O_ as dynamo,zE as dumpDatabase,yQ as defineSeeder,hQ as defineModels,bF as defineModel,e5 as defaultConfig,VE as dbWipe,UE as dbStats,OE as dbOptimize,oL as dbInfo,VQ as createTableFromModel,gF as createSingleTableManager,pF as createRepository,W0 as createQueryBuilder,TF as createModel,U_ as createMigrationDriver,JQ as createDynamoDBToolingAdapter,KQ as createDynamoDBQueryBuilder,IQ as createDynamoDBItemBuilder,V8 as createDynamoDBDriver,WQ as createDynamoDBClient,Cz as createDynamo,l7 as createClient,aX as createBrowserModel,Sz as createBrowserDb,F_ as convertSchemaToDefinition,QQ as configureOrm,Mz as configureModels,Iz as configureBrowser,y as config,pL as clearQueryCache,AF as clearModelRegistry,LO as checkSchema,$E as cacheStats,ZE as cacheConfig,eU as cacheClear,rF as buildSchemaMeta,BZ as buildMigrationPlan,z_ as buildDynamoDBMigrationPlan,AX as buildDatabaseSchema,m7 as browserQuery,eX as browserAuth,xX as SingleTableRepository,BX as SingleTableQueryBuilder,dF as SingleTablePatterns,kX as SingleTableManager,zz as Seeder,k2 as SQLiteDriver,W0 as QueryBuilder,T2 as PostgresDriver,P2 as MySQLDriver,__ as Model,E9 as MIGRATIONS_TABLE,a7 as EntityQueryBuilder,yX as DynamoDBToolingAdapter,I8 as DynamoDBQueryBuilder,o7 as DynamoDBMigrationTracker,t7 as DynamoDBMigrationDriver,P9 as DynamoDBItemBuilder,n7 as DynamoDBDriverImpl,i7 as DynamoDBClient,J9 as BrowserQueryError,c7 as BrowserQueryBuilder,NX as BelongsToManyRelationBuilder};
469
+ `);U(v,`alter-${K.table}-table`)}}if(x9+f9===0)n0("-- Nothing to migrate");else{let W=[];if(x9>0)W.push(`${x9} created`);if(f9>0)W.push(`${f9} updated`);n0(`-- Migration files: ${W.join(", ")}`)}return{statements:_.length===0?["-- No changes detected"]:_,operations:Q}}function Kj(X,$,Z={}){return w7(X,$,Z).statements}var q$=0,x9=0,f9=0,V5=!0,Rj=e(()=>{d0(),_Z(),R7()});function qO(X){return X}class Dj{get order(){return 100}get description(){return}}function PO(X){return X}var y0=e(async()=>{P8(),P8(),Kz(),M6(),UZ(),P8(),await d0(),_Z(),F5(),V7(),tL(),_2(),Uj(),R7(),Rj(),G7(),e1()});await y0();var P7=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000","PRAGMA wal_autocheckpoint = 1"];function Hj(X){for(let $ of P7)try{X.unsafe($).execute().catch(()=>{})}catch{}}var q7=new WeakSet;function T7(){try{let X=L7?.();if(!X||typeof X.run!=="function"||q7.has(X))return;for(let $ of P7)try{X.run($)}catch{}q7.add(X)}catch{}}function gO(X){z7(X),T7()}function dO(X){let $=K0(X);if(!X?.sql&&f.dialect==="sqlite")Hj($),T7();return $}var Cj=new Map;function pO(X,$){let Z=EZ;if(typeof Z==="function")return Z(X,$);Cj.set(X,$);let Y=typeof $?.getDefinition==="function"?$.getDefinition():$?.definition;if(Y&&typeof Y==="object")G5(Y);return $}var wj=/^[A-Z_][A-Z0-9_]*$/i;function qj(X,$={}){if(typeof X!=="string"||X.length===0)return{valid:!1,reason:"empty"};if(X.length>64)return{valid:!1,reason:"too-long"};if(!wj.test(X))return{valid:!1,reason:"invalid-shape"};if($.allowlist&&!$.allowlist.includes(X))return{valid:!1,reason:"not-in-allowlist"};return{valid:!0}}function cO(X,$={}){let Z=qj(X,$);if(Z.valid)return;let Y=$.context?` in ${$.context}`:"";throw Error(`[query-builder] Refusing to use ${JSON.stringify(X)} as a SQL identifier${Y} \u2014 ${Z.reason}`)}var N7=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function Pj(X){return typeof X==="string"&&N7.has(X.toLowerCase())}function mO(X,$){if(Pj(X))return;let Z=$?` in ${$}`:"";throw Error(`[query-builder] Refusing to use ${JSON.stringify(X)} as a SQL operator${Z} \u2014 not in the allowed set (${[...N7].join(", ")})`)}export{BG as wipeDatabase,PF as waitReady,Wz as validateSchema,qj as validateIdentifier,MF as unsafe,OO as unmarshallItem,GO as toModelInstance,EO as toDynamoDBItem,wG as tinker,vG as tableInfo,i_ as startConsole,VO as stacksModelToEntity,QQ as sqlTypeToAttr,DF as sql,_F as showModel,c_ as setQueryCacheMaxSize,H_ as setConfig,QO as seedModel,jz as runSeeders,IF as runSeeder,VG as runBenchmark,C_ as resolveSqlitePragmas,PX as resolvePivot,F6 as resolveKeyPattern,NQ as resetDatabase,WG as resetConnection,OF as relationDiagram,pO as registerModel,lL as registerBrowserModels,KG as raw,jF as queryExplainAll,QF as ping,aL as parseStacksModels,kG as optimizeDatabase,_F as modelShow,QU as modelNameForTable,uQ as migrateStatus,aG as migrateRollback,dj as migrateModels,$F as migrateList,lG as migrateGenerate,FO as marshallObject,KF as makeSeeder,cG as makeModel,dX as loadModels,IG as iterateAllPivots,Pj as isSafeOperator,J0 as isMysqlLike,gj as isDefinitionEqual,vj as isBrowser,fG as introspectDatabase,bG as introspect,YQ as inspectTable,TG as importData,T8 as hashTableDefinition,Oj as hashMigrationPlan,uL as hasModel,h0 as getPlaceholders,i as getPlaceholder,mL as getModelRegistry,pL as getModel,ZX as getDialectDriver,L7 as getDatabase,EG as getConfig,hj as getBrowserConfig,cL as getAllModels,CO as generateSqlString,W5 as generateSql,EQ as generateModelSource,MU as generateMigration,wO as generateDiffSqlString,Kj as generateDiffSql,w7 as generateDiffOperations,OF as generateDiagram,WO as generateAccessPatterns,RF as freshDatabase,hG as file,t7 as extractTableDefinition,e7 as extractModelSchema,E6 as extractInsertId,j6 as extractChanges,PG as exportData,jF as explainAllQueries,yG as explain,TQ as executeMigration,U2 as dynamo,NG as dumpDatabase,PO as defineSeeder,qO as defineModels,G5 as defineModel,M1 as defaultConfig,BG as dbWipe,SG as dbStats,kG as dbOptimize,a_ as dbInfo,_O as createTableFromModel,sL as createSingleTableManager,oL as createRepository,dO as createQueryBuilder,bL as createModel,Z2 as createMigrationDriver,JO as createDynamoDBToolingAdapter,zO as createDynamoDBQueryBuilder,LO as createDynamoDBItemBuilder,bX as createDynamoDBDriver,jO as createDynamoDBClient,pj as createDynamo,w6 as createClient,n7 as createBrowserModel,bj as createBrowserDb,X2 as convertSchemaToDefinition,gO as configureOrm,fj as configureModels,yj as configureBrowser,f as config,p_ as clearQueryCache,nL as clearModelRegistry,qF as checkSchema,u1 as canonicalizeDefault,m1 as canonicalStorageType,DG as cacheStats,MG as cacheConfig,RG as cacheClear,Qj as buildSchemaMeta,J5 as buildMigrationPlan,$2 as buildDynamoDBMigrationPlan,K7 as buildDatabaseSchema,D6 as browserQuery,i7 as browserAuth,T7 as bootstrapModelExecutorPragmas,mO as assertSafeOperator,cO as assertSafeIdentifier,Hj as applySqlitePragmas,t1 as applySqliteBootstrapPragmas,J7 as SingleTableRepository,W7 as SingleTableQueryBuilder,rL as SingleTablePatterns,O7 as SingleTableManager,OU as SingleStoreDriver,Dj as Seeder,WU as SQLiteDriver,P7 as SQLITE_BOOTSTRAP_PRAGMAS,dO as QueryBuilder,FU as PostgresDriver,Z5 as MySQLDriver,r7 as Model,K9 as MIGRATIONS_TABLE,S6 as EntityQueryBuilder,I7 as DynamoDBToolingAdapter,gX as DynamoDBQueryBuilder,P6 as DynamoDBMigrationTracker,N6 as DynamoDBMigrationDriver,b9 as DynamoDBItemBuilder,H6 as DynamoDBDriverImpl,C6 as DynamoDBClient,ZU as DEFAULT_SQLITE_PRAGMAS,B9 as BrowserQueryError,R6 as BrowserQueryBuilder,E7 as BelongsToManyRelationBuilder};