bun-query-builder 0.2.52 → 0.2.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +40 -524
- package/dist/chunk-605xwkdk.js +7 -0
- package/dist/chunk-c6mb5jxz.js +3 -0
- package/dist/chunk-fkjeeh31.js +3 -0
- package/dist/chunk-h8hxz607.js +2 -0
- package/dist/chunk-wwssp8h1.js +40 -0
- package/dist/chunk-yw12p1mp.js +445 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -5
- package/dist/src/index.js +1 -485
- package/package.json +1 -1
package/dist/src/index.js
CHANGED
|
@@ -1,486 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var{defineProperty:XJ,getOwnPropertyNames:Hz,getOwnPropertyDescriptor:Ez}=Object,Uz=Object.prototype.hasOwnProperty;function Yz($){return this[$]}var zz=($)=>{var h=(ME??=new WeakMap).get($),A;if(h)return h;if(h=XJ({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var G of Hz($))if(!Uz.call(h,G))XJ(h,G,{get:Yz.bind($,G),enumerable:!(A=Ez($,G))||A.enumerable})}return ME.set($,h),h},ME;var Wz=($)=>$;function Zz($,h){this[$]=Wz.bind(null,h)}var jJ=($,h)=>{for(var A in h)XJ($,A,{get:h[A],enumerable:!0,configurable:!0,set:Zz.bind(h,A)})};var a=($,h)=>()=>($&&(h=$($=0)),h);var s0=import.meta.require;function dX($){W0={...W0,...$}}function pX(){return W0}function nX(){return typeof window<"u"&&typeof document<"u"}async function TA(){if(W0.getToken){let $=W0.getToken();return $ instanceof Promise?$:$}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function a0(){let $={"Content-Type":"application/json",Accept:"application/json",...W0.headers},h=await TA();if(h)$.Authorization=`Bearer ${h}`;return $}async function F$($){if($.status===401)throw W0.onUnauthorized?.(),new f$("Unauthorized",401);if(!$.ok){let A=await $.json().catch(()=>({message:"Request failed"}));throw new f$(A.message||`HTTP ${$.status}`,$.status)}let h=await $.json();if(W0.transformResponse)return W0.transformResponse(h);return h}class SE{state;constructor($){this.state={table:$,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...$){return this.state.selectColumns=$,this}where($,h,A){if(A===void 0)this.state.wheres.push({column:$,operator:"=",value:h,boolean:"and"});else this.state.wheres.push({column:$,operator:h,value:A,boolean:"and"});return this}orWhere($,h,A){if(A===void 0)this.state.wheres.push({column:$,operator:"=",value:h,boolean:"or"});else this.state.wheres.push({column:$,operator:h,value:A,boolean:"or"});return this}andWhere($,h,A){return A===void 0?this.where($,h):this.where($,h,A)}whereNull($){return this.where($,"is",null)}whereNotNull($){return this.where($,"is not",null)}whereIn($,h){return this.where($,"in",h)}whereNotIn($,h){return this.where($,"not in",h)}orderBy($,h="asc"){return this.state.orderBy.push({column:$,direction:h}),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 h of this.state.wheres)if(h.operator==="=")$.append(h.column,String(h.value));else if(h.operator==="in"&&Array.isArray(h.value))$.append(`${h.column}[]`,h.value.join(","));else if(h.operator==="is"&&h.value===null)$.append(`filter[${h.column}][is]`,"null");else if(h.operator==="is not"&&h.value===null)$.append(`filter[${h.column}][is_not]`,"null");else $.append(`filter[${h.column}][${h.operator}]`,String(h.value));if(this.state.orderBy.length>0){let h=this.state.orderBy.map((A)=>`${A.direction==="desc"?"-":""}${A.column}`).join(",");$.append("sort",h)}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 h=`${W0.baseUrl}/${this.state.table}`;if($!==void 0)return`${h}/${$}`;let G=this.buildQueryParams().toString();return G?`${h}?${G}`:h}async get(){let $=this.buildUrl(),h=await fetch($,{method:"GET",headers:await a0()}),A=await F$(h);return Array.isArray(A)?A:A.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new f$(`No ${this.state.table} found`,404);return $}async find($){let h=this.buildUrl($);try{let A=await fetch(h,{method:"GET",headers:await a0()});if(A.status===404)return null;let G=await F$(A);return"data"in G&&!Array.isArray(G.data)?G.data:G}catch{return null}}async findOrFail($){let h=await this.find($);if(!h)throw new f$(`${this.state.table} with id ${$} not found`,404);return h}async count(){let $=this.buildQueryParams();$.append("count","true");let h=`${W0.baseUrl}/${this.state.table}?${$.toString()}`,A=await fetch(h,{method:"GET",headers:await a0()});return(await F$(A)).count}async exists(){return await this.count()>0}async create($){let h=`${W0.baseUrl}/${this.state.table}`,A=W0.transformRequest?W0.transformRequest($):$,G=await fetch(h,{method:"POST",headers:await a0(),body:JSON.stringify(A)}),J=await F$(G);return"data"in J&&!Array.isArray(J.data)?J.data:J}async insert($){return this.create($)}async update($,h){let A=`${W0.baseUrl}/${this.state.table}/${$}`,G=W0.transformRequest?W0.transformRequest(h):h,J=await fetch(A,{method:"PATCH",headers:await a0(),body:JSON.stringify(G)}),H=await F$(J);return"data"in H&&!Array.isArray(H.data)?H.data:H}async delete($){let h=`${W0.baseUrl}/${this.state.table}/${$}`;return(await fetch(h,{method:"DELETE",headers:await a0()})).ok}async destroy($){return this.delete($)}async paginate($=1,h=15){this.limit(h).offset(($-1)*h);let A=this.buildQueryParams();A.append("paginate","true");let G=`${W0.baseUrl}/${this.state.table}?${A.toString()}`,J=await fetch(G,{method:"GET",headers:await a0()});return F$(J)}toState(){return{...this.state}}}function QE($){return new SE($)}function uX(){return new Proxy({},{get:($,h)=>{return()=>QE(h)}})}class x1{_attributes;_definition;constructor($,h={}){this._definition=$,this._attributes={...h}}get($){return this._attributes[$]}set($,h){this._attributes[$]=h}get attributes(){return{...this._attributes}}get id(){let $=this._definition.primaryKey||"id";return this._attributes[$]}toJSON(){let $=new Set;for(let[A,G]of Object.entries(this._definition.attributes))if(G.hidden)$.add(A);let h={};for(let[A,G]of Object.entries(this._attributes))if(!$.has(A))h[A]=G;return h}}class S0{_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($,h,A){if(A===void 0)this._wheres.push({column:$,operator:"=",value:h,boolean:"and"});else this._wheres.push({column:$,operator:h,value:A,boolean:"and"});return this}orWhere($,h,A){if(A===void 0)this._wheres.push({column:$,operator:"=",value:h,boolean:"or"});else this._wheres.push({column:$,operator:h,value:A,boolean:"or"});return this}whereIn($,h){return this._wheres.push({column:$,operator:"in",value:h,boolean:"and"}),this}whereNotIn($,h){return this._wheres.push({column:$,operator:"not in",value:h,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($,h){return this._wheres.push({column:$,operator:"like",value:h,boolean:"and"}),this}orderBy($,h="asc"){return this._orderBy.push({column:$,direction:h}),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 h of this._wheres)if(h.operator==="=")$.append(h.column,String(h.value));else if(h.operator==="in"&&Array.isArray(h.value))$.append(`${h.column}[]`,h.value.join(","));else if(h.operator==="is"&&h.value===null)$.append(`filter[${h.column}][is]`,"null");else if(h.operator==="is not"&&h.value===null)$.append(`filter[${h.column}][is_not]`,"null");else $.append(`filter[${h.column}][${h.operator}]`,String(h.value));if(this._orderBy.length>0){let h=this._orderBy.map((A)=>`${A.direction==="desc"?"-":""}${A.column}`).join(",");$.append("sort",h)}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 h=`${W0.baseUrl}/${this.getTablePath()}`;if($!==void 0)return`${h}/${$}`;let G=this.buildQueryParams().toString();return G?`${h}?${G}`:h}async get(){let $=this.buildUrl(),h=await fetch($,{method:"GET",headers:await a0()}),A=await F$(h);return(Array.isArray(A)?A:A.data).map((J)=>new x1(this._definition,J))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let $=await this.first();if(!$)throw new f$(`No ${this._definition.name} found`,404);return $}async find($){let h=this.buildUrl($);try{let A=await fetch(h,{method:"GET",headers:await a0()});if(A.status===404)return null;let G=await F$(A),J="data"in G&&!Array.isArray(G.data)?G.data:G;return new x1(this._definition,J)}catch{return null}}async findOrFail($){let h=await this.find($);if(!h)throw new f$(`${this._definition.name} with id ${$} not found`,404);return h}async count(){let $=this.buildQueryParams();$.append("count","true");let h=`${W0.baseUrl}/${this.getTablePath()}?${$.toString()}`,A=await fetch(h,{method:"GET",headers:await a0()});return(await F$(A)).count}async exists(){return await this.count()>0}async pluck($){return this._select=[$],(await this.get()).map((A)=>A.get($))}async paginate($=1,h=15){this._limit=h,this._offset=($-1)*h;let A=this.buildQueryParams();A.append("paginate","true");let G=`${W0.baseUrl}/${this.getTablePath()}?${A.toString()}`,J=await fetch(G,{method:"GET",headers:await a0()}),H=await F$(J);return{...H,data:H.data.map((E)=>new x1(this._definition,E))}}}function CE($){return new Proxy({query:()=>new S0($),where(A,G,J){return new S0($).where(A,G,J)},orWhere(A,G,J){return new S0($).orWhere(A,G,J)},whereIn(A,G){return new S0($).whereIn(A,G)},whereNotIn(A,G){return new S0($).whereNotIn(A,G)},whereNull(A){return new S0($).whereNull(A)},whereNotNull(A){return new S0($).whereNotNull(A)},whereLike(A,G){return new S0($).whereLike(A,G)},orderBy(A,G="asc"){return new S0($).orderBy(A,G)},orderByDesc(A){return new S0($).orderByDesc(A)},select(...A){return new S0($).select(...A)},limit:(A)=>new S0($).limit(A),take:(A)=>new S0($).take(A),skip:(A)=>new S0($).skip(A),latest:(A="created_at")=>new S0($).latest(A),oldest:(A="created_at")=>new S0($).oldest(A),async find(A){return new S0($).find(A)},async findOrFail(A){return new S0($).findOrFail(A)},async all(){return new S0($).get()},async first(){return new S0($).first()},async firstOrFail(){return new S0($).firstOrFail()},async count(){return new S0($).count()},async exists(){return new S0($).exists()},async paginate(A,G){return new S0($).paginate(A,G)},async pluck(A){return new S0($).pluck(A)},async create(A){let G=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,J=`${W0.baseUrl}/${G}`,H=W0.transformRequest?W0.transformRequest(A):A,E=await fetch(J,{method:"POST",headers:await a0(),body:JSON.stringify(H)}),Y=await F$(E),U="data"in Y&&!Array.isArray(Y.data)?Y.data:Y;return new x1($,U)},async update(A,G){let J=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,H=`${W0.baseUrl}/${J}/${A}`,E=W0.transformRequest?W0.transformRequest(G):G,Y=await fetch(H,{method:"PATCH",headers:await a0(),body:JSON.stringify(E)}),U=await F$(Y),z="data"in U&&!Array.isArray(U.data)?U.data:U;return new x1($,z)},async delete(A){let G=typeof $.traits?.useApi==="object"&&$.traits.useApi?.uri||$.table,J=`${W0.baseUrl}/${G}/${A}`;return(await fetch(J,{method:"DELETE",headers:await a0()})).ok},async destroy(A){return this.delete(A)},getDefinition:()=>$,getTable:()=>$.table},{get(A,G){if(typeof G==="string"&&G.startsWith("where")&&G.length>5){let J=G.slice(5),H=J.charAt(0).toLowerCase()+J.slice(1);if(H in $.attributes||H==="id"||H===$.primaryKey)return(E)=>new S0($).where(H,E)}return Reflect.get(A,G)}})}var W0,f$,iX,rX;var LJ=a(()=>{W0={baseUrl:""};f$=class f$ extends Error{status;constructor($,h){super($);this.name="BrowserQueryError",this.status=h}};iX={async login($){let h=await fetch(`${W0.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...W0.headers},body:JSON.stringify($)});if(!h.ok){let J=await h.json().catch(()=>({message:"Login failed"}));throw new f$(J.message||"Login failed",h.status)}let A=await h.json(),G=A.data||A;if(typeof localStorage<"u"&&G.token)localStorage.setItem("auth_token",G.token);return G},async register($){let h=await fetch(`${W0.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...W0.headers},body:JSON.stringify($)});if(!h.ok){let J=await h.json().catch(()=>({message:"Registration failed"}));throw new f$(J.message||"Registration failed",h.status)}let A=await h.json(),G=A.data||A;if(typeof localStorage<"u"&&G.token)localStorage.setItem("auth_token",G.token);return G},async logout(){if(await TA())try{await fetch(`${W0.baseUrl}/logout`,{method:"POST",headers:await a0()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await TA())return null;try{let h=await fetch(`${W0.baseUrl}/user`,{method:"GET",headers:await a0()});if(h.status===401)return W0.onUnauthorized?.(),null;if(!h.ok)return null;let A=await h.json();return A.user||A}catch{return null}},async check(){return await this.user()!==null},getToken:TA},rX=QE});class FJ{config;entityMappings=new Map;constructor($){if(this.config=$,$.entityMappings)for(let h of $.entityMappings)this.registerEntity(h)}createTable($){return{...$,billingMode:$.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable($){return{tableName:$}}registerEntity($){this.entityMappings.set($.entityType,$)}getEntityMapping($){return this.entityMappings.get($)}buildPrimaryKey($,h){let A=this.entityMappings.get($);if(!A)throw Error(`No entity mapping found for type: ${$}`);let G=this.interpolatePattern(A.pkPattern,h),J=this.interpolatePattern(A.skPattern,h);return{pk:G,sk:J}}parseEntityFromItem($){let h=$.pk||$.PK;if(!h)return null;for(let[A,G]of this.entityMappings){let J=G.pkPattern.split("${")[0];if(h.startsWith(J))return{entityType:A,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 h={},A={},G=[],J=0;if($.set&&Object.keys($.set).length>0){let H=[];for(let[E,Y]of Object.entries($.set)){let U=`#attr${J}`,z=`:val${J}`;h[U]=E,A[z]=this.marshallValue(Y),H.push(`${U} = ${z}`),J++}G.push(`SET ${H.join(", ")}`)}if($.remove&&$.remove.length>0){let H=[];for(let E of $.remove){let Y=`#attr${J}`;h[Y]=E,H.push(Y),J++}G.push(`REMOVE ${H.join(", ")}`)}if($.add&&Object.keys($.add).length>0){let H=[];for(let[E,Y]of Object.entries($.add)){let U=`#attr${J}`,z=`:val${J}`;h[U]=E,A[z]=this.marshallValue(Y),H.push(`${U} ${z}`),J++}G.push(`ADD ${H.join(", ")}`)}if($.delete&&Object.keys($.delete).length>0){let H=[];for(let[E,Y]of Object.entries($.delete)){let U=`#attr${J}`,z=`:val${J}`;h[U]=E,A[z]=this.marshallValue(Y),H.push(`${U} ${z}`),J++}G.push(`DELETE ${H.join(", ")}`)}return{expression:G.join(" "),expressionAttributeNames:h,expressionAttributeValues:A}}buildProjectionExpression($){let h={},A=[];return $.forEach((G,J)=>{let H=`#proj${J}`;h[H]=G,A.push(H)}),{expression:A.join(", "),expressionAttributeNames:h}}marshall($){let h={};for(let[A,G]of Object.entries($))h[A]=this.marshallValue(G);return h}unmarshall($){let h={};for(let[A,G]of Object.entries($))h[A]=this.unmarshallValue(G);return h}interpolatePattern($,h){return $.replace(/\$\{(\w+)\}/g,(A,G)=>{if(!(G in h))throw Error(`Missing value for pattern key: ${G}`);return String(h[G])})}buildExpression($,h){let A={},G={},J=[];return $.forEach((H,E)=>{let Y=`#attr${E}`;A[Y]=H.attribute;let U;switch(H.operator){case"=":case"<":case"<=":case">":case">=":{let z=`:val${E}`;G[z]=this.marshallValue(H.value),U=`${Y} ${H.operator} ${z}`;break}case"BETWEEN":{let z=`:val${E}a`,W=`:val${E}b`;G[z]=this.marshallValue(H.values?.[0]),G[W]=this.marshallValue(H.values?.[1]),U=`${Y} BETWEEN ${z} AND ${W}`;break}case"begins_with":{let z=`:val${E}`;G[z]=this.marshallValue(H.value),U=`begins_with(${Y}, ${z})`;break}case"contains":{let z=`:val${E}`;G[z]=this.marshallValue(H.value),U=`contains(${Y}, ${z})`;break}case"attribute_exists":U=`attribute_exists(${Y})`;break;case"attribute_not_exists":U=`attribute_not_exists(${Y})`;break;case"attribute_type":{let z=`:val${E}`;G[z]={S:H.value},U=`attribute_type(${Y}, ${z})`;break}case"IN":{let z=(H.values??[]).map((W,Z)=>`:val${E}_${Z}`);H.values?.forEach((W,Z)=>{G[`:val${E}_${Z}`]=this.marshallValue(W)}),U=`${Y} IN (${z.join(", ")})`;break}default:throw Error(`Unknown operator: ${H.operator}`)}J.push(U)}),{expression:J.join(` ${h} `),expressionAttributeNames:A,expressionAttributeValues:G}}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 h=typeof $[0],A=$.every((J)=>typeof J==="string"),G=$.every((J)=>typeof J==="number");if(A)return{SS:$};if(G)return{NS:$.map(String)};return{L:$.map((J)=>this.marshallValue(J))}}if(typeof $==="object"){let h={};for(let[A,G]of Object.entries($))h[A]=this.marshallValue(G);return{M:h}}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((h)=>this.unmarshallValue(h));if("M"in $){let h={};for(let[A,G]of Object.entries($.M))h[A]=this.unmarshallValue(G);return h}return $}}function V$($){return new FJ($)}async function xh($,h){let A=$ instanceof ArrayBuffer?$:$.buffer.slice($.byteOffset,$.byteOffset+$.byteLength),G=await crypto.subtle.importKey("raw",A,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",G,new TextEncoder().encode(h))}async function KE($){let h=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return Array.from(new Uint8Array(h)).map((A)=>A.toString(16).padStart(2,"0")).join("")}async function Xz($,h,A,G){let J=await xh(new TextEncoder().encode(`AWS4${$}`),h),H=await xh(J,A),E=await xh(H,G);return xh(E,"aws4_request")}async function jz($,h,A,G,J,H,E){let U=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),z=U.slice(0,8),W=h.pathname,Z=h.search.slice(1),F={...A,host:h.host,"x-amz-date":U};if(J.sessionToken)F["x-amz-security-token"]=J.sessionToken;let w=Object.keys(F).sort(),B=w.map((N)=>`${N.toLowerCase()}:${F[N].trim()}`).join(`
|
|
3
|
-
`)+`
|
|
4
|
-
`,j=w.map((N)=>N.toLowerCase()).join(";"),O=await KE(G),_=[$,W,Z,B,j,O].join(`
|
|
5
|
-
`),R=await KE(_),S="AWS4-HMAC-SHA256",D=`${z}/${H}/${E}/aws4_request`,y=[S,U,D,R].join(`
|
|
6
|
-
`),P=await Xz(J.secretAccessKey,z,H,E),T=await xh(P,y),C=Array.from(new Uint8Array(T)).map((N)=>N.toString(16).padStart(2,"0")).join(""),Q=`${S} Credential=${J.accessKeyId}/${D}, SignedHeaders=${j}, Signature=${C}`;return{...F,authorization:Q}}class kA{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($,h){let A=new URL(this.endpoint),G=JSON.stringify(h),J={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${$}`},H=await jz("POST",A,J,G,this.credentials,this.config.region,"dynamodb"),E=await fetch(A.toString(),{method:"POST",headers:H,body:G});if(!E.ok){let Y=await E.text(),U;try{let z=JSON.parse(Y);U=z.message??z.Message??Y}catch{U=Y}throw Error(`DynamoDB ${$} failed: ${E.status} - ${U}`)}return E.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 f1($){return new kA($)}function Lz($){G1={...G1,...$},yA=null,qA=null}function O1(){if(!yA)yA=f1({region:G1.region??"us-east-1",endpoint:G1.endpoint,credentials:G1.credentials});return yA}function D1(){if(!qA)qA=V$({region:G1.region??"us-east-1",endpoint:G1.endpoint,credentials:G1.credentials});return qA}class BE{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[h,A]of Object.entries($))this[h]=A}static query(){return new IE(this)}static async find($){let h=this,A=O1(),G=D1(),J=`${h.pkPrefix}${h.keyDelimiter}${$}`,H=h.skPrefix;try{let E=await A.getItem({TableName:h.tableName,Key:G.marshall({[h.pkAttribute]:J,[h.skAttribute]:H})});if(!E.Item)return null;let Y=G.unmarshall(E.Item),U=new h(Y);return U._exists=!0,U}catch(E){return console.error("Find error:",E),null}}static async findOrFail($){let h=await this.find($);if(!h)throw Error(`${this.name} not found with id: ${$}`);return h}static async all(){return this.query().get()}static async create($){let h=this,A=O1(),G=D1(),J=$[h.primaryKey];if(!J)throw Error(`${h.primaryKey} is required`);let H=`${h.pkPrefix}${h.keyDelimiter}${J}`,E=h.skPrefix,Y=new Date().toISOString(),U={...$,[h.pkAttribute]:H,[h.skAttribute]:E,[h.entityTypeAttribute]:h.name};if(h.timestamps)U[h.createdAtField]=Y,U[h.updatedAtField]=Y;await A.putItem({TableName:h.tableName,Item:G.marshall(U),ConditionExpression:`attribute_not_exists(${h.pkAttribute})`});let z=new h(U);return z._exists=!0,z}static async updateOrCreate($,h){let A=this,G=$[A.primaryKey],J=await A.find(G);if(J)return await J.update(h),J;return A.create({...$,...h})}static where($,h,A){return this.query().where($,h,A)}static wherePk($){return this.query().wherePk($)}getKey(){let $=this.constructor;return this[$.primaryKey]}getAttribute($){return this._attributes[$]}setAttribute($,h){return this._attributes[$]=h,this[$]=h,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[h,A]of Object.entries(this._attributes))if(A!==this._original[h])$[h]=A;return $}async save(){if(this._exists){let $=this.getDirty();if(Object.keys($).length>0)await this.update($)}else{let h=await this.constructor.create(this._attributes);this._attributes=h._attributes,this._original={...this._attributes},this._exists=!0}return this}async update($){let h=this.constructor,A=O1(),G=D1(),J=this.getKey(),H=`${h.pkPrefix}${h.keyDelimiter}${J}`,E=h.skPrefix,Y=new Date().toISOString(),U={...$};if(h.timestamps)U[h.updatedAtField]=Y;let z=[],W={},Z={},F=0;for(let[w,B]of Object.entries(U)){let j=`#attr${F}`,O=`:val${F}`;W[j]=w,Z[O]=G.marshall({v:B}).v,z.push(`${j} = ${O}`),F++}await A.updateItem({TableName:h.tableName,Key:G.marshall({[h.pkAttribute]:H,[h.skAttribute]:E}),UpdateExpression:`SET ${z.join(", ")}`,ExpressionAttributeNames:W,ExpressionAttributeValues:Z});for(let[w,B]of Object.entries(U))this._attributes[w]=B,this[w]=B;return this._original={...this._attributes},this}async delete(){let $=this.constructor,h=O1(),A=D1(),G=this.getKey(),J=`${$.pkPrefix}${$.keyDelimiter}${G}`,H=$.skPrefix;return await h.deleteItem({TableName:$.tableName,Key:A.marshall({[$.pkAttribute]:J,[$.skAttribute]:H})}),this._exists=!1,!0}async refresh(){let h=await this.constructor.find(this.getKey());if(h){this._attributes=h._attributes,this._original={...this._attributes};for(let[A,G]of Object.entries(this._attributes))this[A]=G}return this}toObject(){let $=this.constructor,h={...this._attributes};return delete h[$.pkAttribute],delete h[$.skAttribute],delete h[$.entityTypeAttribute],h}toJSON(){return this.toObject()}}class IE{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($,h,A){if(A===void 0)this._filterConditions.push({attribute:$,operator:"=",value:h});else this._filterConditions.push({attribute:$,operator:h,value:A});return this}whereIn($,h){return this._filterConditions.push({attribute:$,operator:"IN",values:h}),this}whereBetween($,h,A){return this._filterConditions.push({attribute:$,operator:"BETWEEN",value:h,values:[h,A]}),this}whereBeginsWith($,h){return this._filterConditions.push({attribute:$,operator:"begins_with",value:h}),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 $=D1(),h={TableName:this.ModelClass.tableName};if(this._indexName)h.IndexName=this._indexName;let A={},G={},J=0,H=[];if(this._pkValue){let E=`#pk${J}`,Y=`:pk${J}`;A[E]=this.ModelClass.pkAttribute,G[Y]={S:this._pkValue},H.push(`${E} = ${Y}`),J++}if(this._skCondition){let E=`#sk${J}`;switch(A[E]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let Y=`:sk${J}`;G[Y]={S:this._skCondition.value},H.push(`${E} = ${Y}`);break}case"begins_with":{let Y=`:sk${J}`;G[Y]={S:this._skCondition.value},H.push(`begins_with(${E}, ${Y})`);break}}J++}if(H.length>0)h.KeyConditionExpression=H.join(" AND ");if(this._filterConditions.length>0){let E=[];for(let Y of this._filterConditions){let U=`#flt${J}`;if(A[U]=Y.attribute,Y.operator==="attribute_exists")E.push(`attribute_exists(${U})`);else if(Y.operator==="attribute_not_exists")E.push(`attribute_not_exists(${U})`);else if(Y.operator==="IN"&&Y.values){let z=Y.values.map((W,Z)=>`:flt${J}_${Z}`);Y.values.forEach((W,Z)=>{G[`:flt${J}_${Z}`]=$.marshall({v:W}).v}),E.push(`${U} IN (${z.join(", ")})`)}else if(Y.operator==="BETWEEN"&&Y.values){let z=`:flt${J}a`,W=`:flt${J}b`;G[z]=$.marshall({v:Y.values[0]}).v,G[W]=$.marshall({v:Y.values[1]}).v,E.push(`${U} BETWEEN ${z} AND ${W}`)}else if(Y.operator==="begins_with"){let z=`:flt${J}`;G[z]=$.marshall({v:Y.value}).v,E.push(`begins_with(${U}, ${z})`)}else{let z=`:flt${J}`;G[z]=$.marshall({v:Y.value}).v,E.push(`${U} ${Y.operator} ${z}`)}J++}h.FilterExpression=E.join(" AND ")}if(this._projectionAttrs.length>0){let E=[];for(let Y of this._projectionAttrs){let U=`#proj${J}`;A[U]=Y,E.push(U),J++}h.ProjectionExpression=E.join(", ")}if(Object.keys(A).length>0)h.ExpressionAttributeNames=A;if(Object.keys(G).length>0)h.ExpressionAttributeValues=G;if(this._limitValue!==void 0)h.Limit=this._limitValue;if(h.ScanIndexForward=this._scanForward,this._consistentReadValue)h.ConsistentRead=!0;if(this._startKey)h.ExclusiveStartKey=$.marshall(this._startKey);return h}async get(){let $=O1(),h=D1(),A=this.buildRequest();return((this._pkValue!==void 0?await $.query(A):await $.scan(A)).Items??[]).map((E)=>{let Y=h.unmarshall(E),U=new this.ModelClass(Y);return U._exists=!0,U})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let $=O1(),h=this.buildRequest();return h.Select="COUNT",(this._pkValue!==void 0?await $.query(h):await $.scan(h)).Count??0}async paginate($,h){let A=D1();if(h)this._startKey=h;this._limitValue=$;let G=O1(),J=this.buildRequest(),E=this._pkValue!==void 0?await G.query(J):await G.scan(J);return{items:(E.Items??[]).map((U)=>{let z=A.unmarshall(U),W=new this.ModelClass(z);return W._exists=!0,W}),lastKey:E.LastEvaluatedKey?A.unmarshall(E.LastEvaluatedKey):void 0}}}var G1,yA=null,qA=null;var PE=a(()=>{G1={region:process.env.AWS_REGION??"us-east-1"}});function g1($){let h=JSON.stringify({tableName:$.tableName,keySchema:$.keySchema,attributeDefinitions:[...$.attributeDefinitions||[]].sort((G,J)=>G.name.localeCompare(J.name)),globalSecondaryIndexes:[...$.globalSecondaryIndexes||[]].sort((G,J)=>G.indexName.localeCompare(J.indexName)),localSecondaryIndexes:[...$.localSecondaryIndexes||[]].sort((G,J)=>G.indexName.localeCompare(J.indexName)),billingMode:$.billingMode,ttlAttribute:$.ttlAttribute,streamSpecification:$.streamSpecification}),A=0;for(let G=0;G<h.length;G++){let J=h.charCodeAt(G);A=(A<<5)-A+J,A=A&A}return Math.abs(A).toString(16).padStart(8,"0")}function RJ($){let h=NE($);return TE(h)}function NE($){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 TE($){let h=[{name:$.pkAttribute,type:"S"},{name:$.skAttribute,type:"S"}],A=[];if($.gsis)for(let G of $.gsis){if(!h.some((J)=>J.name===G.pkAttribute))h.push({name:G.pkAttribute,type:"S"});if(G.skAttribute&&!h.some((J)=>J.name===G.skAttribute))h.push({name:G.skAttribute,type:"S"});A.push({indexName:G.indexName,keySchema:{partitionKey:G.pkAttribute,sortKey:G.skAttribute},projection:{type:Array.isArray(G.projection)?"INCLUDE":G.projection||"ALL",nonKeyAttributes:Array.isArray(G.projection)?G.projection:void 0},provisionedThroughput:G.provisionedThroughput})}return{tableName:$.tableName,keySchema:{partitionKey:$.pkAttribute,sortKey:$.skAttribute},attributeDefinitions:h,globalSecondaryIndexes:A.length>0?A:void 0,billingMode:$.billingMode,provisionedThroughput:$.provisionedThroughput,ttlAttribute:$.ttlAttribute,streamSpecification:$.streamEnabled?{enabled:!0,viewType:$.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function wJ($,h){let A=[],G=h.tableName;if(!$)A.push({type:"CREATE_TABLE",tableName:G,details:{definition:h}});else{let J=$.keySchema.partitionKey!==h.keySchema.partitionKey,H=$.keySchema.sortKey!==h.keySchema.sortKey;if(J||H)console.warn(`[Migration] Table ${G}: Key schema changes require table recreation. Current: pk=${$.keySchema.partitionKey}, sk=${$.keySchema.sortKey}. Target: pk=${h.keySchema.partitionKey}, sk=${h.keySchema.sortKey}. This operation is not supported automatically.`);let E=$.globalSecondaryIndexes||[],Y=h.globalSecondaryIndexes||[],U=new Set(E.map((F)=>F.indexName)),z=new Set(Y.map((F)=>F.indexName));for(let F of Y)if(!U.has(F.indexName))A.push({type:"ADD_GSI",tableName:G,details:{gsi:F}});for(let F of E)if(!z.has(F.indexName))A.push({type:"DELETE_GSI",tableName:G,details:{indexName:F.indexName}});if($.billingMode!==h.billingMode&&h.billingMode)A.push({type:"UPDATE_BILLING_MODE",tableName:G,details:{billingMode:h.billingMode,provisionedThroughput:h.provisionedThroughput}});if($.ttlAttribute!==h.ttlAttribute)A.push({type:"UPDATE_TTL",tableName:G,details:{ttlAttribute:h.ttlAttribute||null,enabled:!!h.ttlAttribute}});let W=$.streamSpecification?.enabled,Z=h.streamSpecification?.enabled;if(W!==Z)if(Z)A.push({type:"ENABLE_STREAM",tableName:G,details:{viewType:h.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else A.push({type:"DISABLE_STREAM",tableName:G,details:{}})}return{tableName:G,operations:A,timestamp:new Date().toISOString(),hash:g1(h)}}function Fz($,h){return g1($)===g1(h)}class xA{client;initialized=!1;constructor($){this.client=$}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(T$),this.initialized=!0}catch($){if($.message?.includes("ResourceNotFoundException")||$.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${T$}`),await this.client.createTable({TableName:T$,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(T$),this.initialized=!0;else throw $}}async waitForTableActive($,h=30){for(let A=0;A<h;A++){try{if((await this.client.describeTable($)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((G)=>setTimeout(G,1000))}throw Error(`Table ${$} did not become active within ${h} seconds`)}async getLatestState($){await this.ensureMigrationsTable();let h=`${fh}#${$}`,A=await this.client.query({TableName:T$,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:h}},ScanIndexForward:!1,Limit:1});if(!A.Items||A.Items.length===0)return null;return this.unmarshallState(A.Items[0])}async getHistory($){await this.ensureMigrationsTable();let h=`${fh}#${$}`,A=await this.client.query({TableName:T$,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:h}},ScanIndexForward:!1});if(!A.Items)return[];return A.Items.map((G)=>this.unmarshallState(G))}async recordMigration($,h,A){await this.ensureMigrationsTable();let G=await this.getLatestState($),J=A??(G?G.version+1:1),H=`${fh}#${$}`,E=`${kE}#${String(J).padStart(6,"0")}`,Y={tableName:$,hash:g1(h),definition:h,appliedAt:new Date().toISOString(),version:J};return await this.client.putItem({TableName:T$,Item:this.marshallState(Y,H,E)}),console.log(`[Migration] Recorded migration for ${$} (version ${J})`),Y}async listTrackedTables(){await this.ensureMigrationsTable();let $=await this.client.scan({TableName:T$,ProjectionExpression:"pk"});if(!$.Items)return[];let h=new Set;for(let A of $.Items){let J=(A.pk?.S||"").replace(`${fh}#`,"");if(J)h.add(J)}return Array.from(h)}async hasMigrations($){return await this.getLatestState($)!==null}async deleteMigrationHistory($){await this.ensureMigrationsTable();let h=await this.getHistory($),A=`${fh}#${$}`;for(let G of h){let J=`${kE}#${String(G.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:T$,Key:{pk:{S:A},sk:{S:J}}})}console.log(`[Migration] Deleted migration history for ${$}`)}marshallState($,h,A){return{pk:{S:h},sk:{S:A},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 T$="_qb_migrations",fh="MIGRATION",kE="VERSION";var _J=()=>{};class OJ{client;tracker;config;constructor($){this.config=$,this.client=f1({region:$.region,endpoint:$.endpoint,credentials:$.credentials}),this.tracker=new xA(this.client)}async execute($){let h={tableName:$.tableName,success:!0,operations:[]};if($.operations.length===0)return this.log(`[Migration] No changes needed for ${$.tableName}`),h;this.log(`[Migration] Executing ${$.operations.length} operations for ${$.tableName}`);try{for(let A of $.operations)await this.executeOperation(A),h.operations.push(A.type);this.log(`[Migration] Successfully applied ${h.operations.length} operations to ${$.tableName}`)}catch(A){h.success=!1,h.error=A.message,console.error(`[Migration] Failed to execute migration for ${$.tableName}:`,A)}return h}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 h={TableName:$.tableName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:$.attributeDefinitions.map((A)=>({AttributeName:A.name,AttributeType:A.type})),BillingMode:$.billingMode||"PAY_PER_REQUEST"};if($.keySchema.sortKey)h.KeySchema.push({AttributeName:$.keySchema.sortKey,KeyType:"RANGE"});if($.billingMode==="PROVISIONED"&&$.provisionedThroughput)h.ProvisionedThroughput={ReadCapacityUnits:$.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:$.provisionedThroughput.writeCapacityUnits};if($.globalSecondaryIndexes&&$.globalSecondaryIndexes.length>0)h.GlobalSecondaryIndexes=$.globalSecondaryIndexes.map((A)=>({IndexName:A.indexName,KeySchema:[{AttributeName:A.keySchema.partitionKey,KeyType:"HASH"},...A.keySchema.sortKey?[{AttributeName:A.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:A.projection.type,...A.projection.nonKeyAttributes?{NonKeyAttributes:A.projection.nonKeyAttributes}:{}},...A.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:A.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:A.provisionedThroughput.writeCapacityUnits}}:{}}));if($.localSecondaryIndexes&&$.localSecondaryIndexes.length>0)h.LocalSecondaryIndexes=$.localSecondaryIndexes.map((A)=>({IndexName:A.indexName,KeySchema:[{AttributeName:$.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:A.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:A.projection.type,...A.projection.nonKeyAttributes?{NonKeyAttributes:A.projection.nonKeyAttributes}:{}}}));if($.streamSpecification?.enabled)h.StreamSpecification={StreamEnabled:!0,StreamViewType:$.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${$.tableName}`),await this.client.createTable(h),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($,h){this.log(`[Migration] Adding GSI ${h.indexName} to ${$}`);let A=await this.client.describeTable($),G=new Set(A.Table?.AttributeDefinitions?.map((E)=>E.AttributeName)||[]),J=[];if(!G.has(h.keySchema.partitionKey))J.push({AttributeName:h.keySchema.partitionKey,AttributeType:"S"});if(h.keySchema.sortKey&&!G.has(h.keySchema.sortKey))J.push({AttributeName:h.keySchema.sortKey,AttributeType:"S"});let H={TableName:$,AttributeDefinitions:J.length>0?J:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:h.indexName,KeySchema:[{AttributeName:h.keySchema.partitionKey,KeyType:"HASH"},...h.keySchema.sortKey?[{AttributeName:h.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:h.projection.type,...h.projection.nonKeyAttributes?{NonKeyAttributes:h.projection.nonKeyAttributes}:{}},...h.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:h.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:h.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(H),await this.waitForGSIActive($,h.indexName),this.log(`[Migration] GSI ${h.indexName} added to ${$}`)}async deleteGSI($,h){this.log(`[Migration] Deleting GSI ${h} from ${$}`);let A={TableName:$,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:h}}]};await this.executeUpdateTable(A),this.log(`[Migration] GSI ${h} deleted from ${$}`)}async updateTTL($,h,A){this.log(`[Migration] Updating TTL on ${$}: ${A?h:"disabled"}`);let G={TableName:$,TimeToLiveSpecification:{Enabled:A,AttributeName:h||"ttl"}};await this.executeUpdateTimeToLive(G),this.log(`[Migration] TTL updated on ${$}`)}async updateBillingMode($,h,A){this.log(`[Migration] Updating billing mode on ${$} to ${h}`);let G={TableName:$,BillingMode:h};if(h==="PROVISIONED"&&A)G.ProvisionedThroughput={ReadCapacityUnits:A.readCapacityUnits,WriteCapacityUnits:A.writeCapacityUnits};await this.executeUpdateTable(G),await this.waitForTableActive($),this.log(`[Migration] Billing mode updated on ${$}`)}async enableStream($,h){this.log(`[Migration] Enabling stream on ${$} with view type ${h}`);let A={TableName:$,StreamSpecification:{StreamEnabled:!0,StreamViewType:h}};await this.executeUpdateTable(A),await this.waitForTableActive($),this.log(`[Migration] Stream enabled on ${$}`)}async disableStream($){this.log(`[Migration] Disabling stream on ${$}`);let h={TableName:$,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(h),await this.waitForTableActive($),this.log(`[Migration] Stream disabled on ${$}`)}async executeUpdateTable($){await this.client.updateTable($)}async executeUpdateTimeToLive($){await this.client.updateTimeToLive($)}async waitForTableActive($,h=60){this.log(`[Migration] Waiting for table ${$} to become active...`);for(let A=0;A<h;A++){try{let J=(await this.client.describeTable($)).Table?.TableStatus;if(J==="ACTIVE")return;this.log(`[Migration] Table status: ${J}, waiting...`)}catch{}await new Promise((G)=>setTimeout(G,2000))}throw Error(`Table ${$} did not become active within ${h*2} seconds`)}async waitForGSIActive($,h,A=120){this.log(`[Migration] Waiting for GSI ${h} to become active...`);for(let G=0;G<A;G++){try{let H=(await this.client.describeTable($)).Table?.GlobalSecondaryIndexes?.find((Y)=>Y.IndexName===h);if(H?.IndexStatus==="ACTIVE")return;let E=H?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${E}, waiting...`)}catch{}await new Promise((J)=>setTimeout(J,5000))}throw Error(`GSI ${h} did not become active within ${A*5} seconds`)}async migrateModel($){let h=RJ($),A=null;try{let H=await this.client.describeTable(h.tableName);if(H.Table)A=this.tableInfoToDefinition(H.Table)}catch(H){if(!H.message?.includes("ResourceNotFoundException")&&!H.message?.includes("not found"))throw H}let G=wJ(A,h),J=await this.execute(G);if(J.success&&!this.config.dryRun)J.state=await this.tracker.recordMigration(h.tableName,h);return J}async migrateModels($){let h=[];for(let A of $)try{let G=await this.migrateModel(A);h.push(G)}catch(G){h.push({tableName:A.tableName||"unknown",success:!1,operations:[],error:G.message})}return h}async getStatus(){let $=new Map,h=await this.tracker.listTrackedTables();for(let A of h){let G=await this.tracker.getLatestState(A);$.set(A,G)}return $}tableInfoToDefinition($){let h={partitionKey:"",sortKey:void 0};for(let J of $.KeySchema||[])if(J.KeyType==="HASH")h.partitionKey=J.AttributeName;else if(J.KeyType==="RANGE")h.sortKey=J.AttributeName;let A=($.AttributeDefinitions||[]).map((J)=>({name:J.AttributeName,type:J.AttributeType})),G=($.GlobalSecondaryIndexes||[]).map((J)=>{let H={partitionKey:"",sortKey:void 0};for(let E of J.KeySchema||[])if(E.KeyType==="HASH")H.partitionKey=E.AttributeName;else if(E.KeyType==="RANGE")H.sortKey=E.AttributeName;return{indexName:J.IndexName,keySchema:H,projection:{type:J.Projection?.ProjectionType||"ALL",nonKeyAttributes:J.Projection?.NonKeyAttributes},provisionedThroughput:J.ProvisionedThroughput?{readCapacityUnits:J.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:J.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:$.TableName,keySchema:h,attributeDefinitions:A,globalSecondaryIndexes:G.length>0?G: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 yE($){return new OJ($)}async function Rz($,h){return yE(h).migrateModels($)}var qE=a(()=>{_J()});class xE{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor($,h,A,G){this.driver=$,this.client=h,this.tableName=A,this.pkAttribute=G.pkAttribute,this.skAttribute=G.skAttribute,this.entityTypeAttr=G.entityTypeAttribute,this.delimiter=G.keyDelimiter}entity($){return this._entityType=$,this}pk($){return this._pkValue=$,this}get sk(){let $=this;return{equals(h){return $._skCondition={type:"eq",value:h},$},beginsWith(h){return $._skCondition={type:"begins_with",value:h},$},between(h,A){return $._skCondition={type:"between",value:h,value2:A},$},lt(h){return $._skCondition={type:"lt",value:h},$},lte(h){return $._skCondition={type:"lte",value:h},$},gt(h){return $._skCondition={type:"gt",value:h},$},gte(h){return $._skCondition={type:"gte",value:h},$}}}index($){return this._indexName=$,this}project(...$){return this._projectionAttrs.push(...$),this}filter($,h,A){return this._filterConditions.push({attribute:$,operator:h,value:A}),this}where($,h){return this.filter($,"=",h)}whereIn($,h){return this._filterConditions.push({attribute:$,operator:"IN",values:h}),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 h=[],A={},G={},J=0;if(this._pkValue){let H=`#pk${J}`,E=`:pk${J}`;A[H]=this.pkAttribute,G[E]={S:this._pkValue},h.push(`${H} = ${E}`),J++}if(this._skCondition){let H=`#sk${J}`;switch(A[H]=this.skAttribute,this._skCondition.type){case"eq":{let E=`:sk${J}`;G[E]={S:this._skCondition.value},h.push(`${H} = ${E}`);break}case"begins_with":{let E=`:sk${J}`;G[E]={S:this._skCondition.value},h.push(`begins_with(${H}, ${E})`);break}case"between":{let E=`:sk${J}a`,Y=`:sk${J}b`;G[E]={S:this._skCondition.value},G[Y]={S:this._skCondition.value2},h.push(`${H} BETWEEN ${E} AND ${Y}`);break}case"lt":{let E=`:sk${J}`;G[E]={S:this._skCondition.value},h.push(`${H} < ${E}`);break}case"lte":{let E=`:sk${J}`;G[E]={S:this._skCondition.value},h.push(`${H} <= ${E}`);break}case"gt":{let E=`:sk${J}`;G[E]={S:this._skCondition.value},h.push(`${H} > ${E}`);break}case"gte":{let E=`:sk${J}`;G[E]={S:this._skCondition.value},h.push(`${H} >= ${E}`);break}}J++}if(h.length>0)$.KeyConditionExpression=h.join(" AND ");if(this._filterConditions.length>0){let H=[];for(let E of this._filterConditions){let Y=`#flt${J}`;if(A[Y]=E.attribute,E.operator==="IN"&&E.values){let U=E.values.map((z,W)=>`:flt${J}_${W}`);E.values.forEach((z,W)=>{G[`:flt${J}_${W}`]=this.driver.marshall({v:z}).v}),H.push(`${Y} IN (${U.join(", ")})`)}else{let U=`:flt${J}`;G[U]=this.driver.marshall({v:E.value}).v,H.push(`${Y} ${E.operator} ${U}`)}J++}$.FilterExpression=H.join(" AND ")}if(this._projectionAttrs.length>0){let H=[];for(let E of this._projectionAttrs){let Y=`#proj${J}`;A[Y]=E,H.push(Y),J++}$.ProjectionExpression=H.join(", ")}if(Object.keys(A).length>0)$.ExpressionAttributeNames=A;if(Object.keys(G).length>0)$.ExpressionAttributeValues=G;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((G)=>this.driver.unmarshall(G))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let $=[],h;do{if(h)this._startKey=h;let A=this.toRequest(),J=this._pkValue!==void 0?await this.client.query(A):await this.client.scan(A),H=(J.Items??[]).map((E)=>this.driver.unmarshall(E));$.push(...H),h=J.LastEvaluatedKey?this.driver.unmarshall(J.LastEvaluatedKey):void 0}while(h);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 DJ{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection($){let h={region:$.region,tableName:$.table,endpoint:$.endpoint,credentials:$.credentials};return this.driver=V$(h),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 xE(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 h=[];for(let A of $)if(A.put){let G={...A.put.item,[this.entityTypeAttr]:A.put.entity};h.push({PutRequest:{Item:this.driver.marshall(G)}})}else if(A.delete)h.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:A.delete.pk,[this.skAttribute]:A.delete.sk})}});if(h.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:h}})}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 h=[];for(let A of $)if(A.put){let G={...A.put.item,[this.entityTypeAttr]:A.put.entity},J={Put:{TableName:this.tableName,Item:this.driver.marshall(G)}};if(A.put.condition)J.Put.ConditionExpression=A.put.condition;h.push(J)}else if(A.update){let G={[this.pkAttribute]:A.update.pk};if(A.update.sk)G[this.skAttribute]=A.update.sk;let J=[],H={},E={},Y=0;if(A.update.set){let U=[];for(let[z,W]of Object.entries(A.update.set)){let Z=`#set${Y}`,F=`:set${Y}`;H[Z]=z,E[F]=this.driver.marshall({v:W}).v,U.push(`${Z} = ${F}`),Y++}if(U.length>0)J.push(`SET ${U.join(", ")}`)}if(A.update.add){let U=[];for(let[z,W]of Object.entries(A.update.add)){let Z=`#add${Y}`,F=`:add${Y}`;H[Z]=z,E[F]={N:String(W)},U.push(`${Z} ${F}`),Y++}if(U.length>0)J.push(`ADD ${U.join(", ")}`)}if(A.update.remove&&A.update.remove.length>0){let U=[];for(let z of A.update.remove){let W=`#rem${Y}`;H[W]=z,U.push(W),Y++}J.push(`REMOVE ${U.join(", ")}`)}h.push({Update:{TableName:this.tableName,Key:this.driver.marshall(G),UpdateExpression:J.join(" "),ExpressionAttributeNames:H,ExpressionAttributeValues:E}})}else if(A.delete){let G={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:A.delete.pk,[this.skAttribute]:A.delete.sk})}};if(A.delete.condition)G.Delete.ConditionExpression=A.delete.condition;h.push(G)}else if(A.conditionCheck)h.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:A.conditionCheck.pk,[this.skAttribute]:A.conditionCheck.sk}),ConditionExpression:A.conditionCheck.condition}});if(h.length>0)await this.client.transactWriteItems({TransactItems:h})}getDriver(){return this.driver}}function jj(){return new DJ}var Xj;var fE=a(()=>{PE();qE();_J();Xj=new DJ});import{existsSync as gE,statSync as vE}from"fs";import{resolve as vh}from"path";import wz from"process";import{existsSync as Dz,mkdirSync as Qj,readdirSync as Cj,readFileSync as Vz,writeFileSync as Kj}from"fs";import{homedir as v1}from"os";import{dirname as Pj,resolve as k$}from"path";import LG from"process";import{existsSync as bE,statSync as cE}from"fs";import{existsSync as cJ,mkdirSync as Mz,readdirSync as Sz,writeFileSync as Qz}from"fs";import{homedir as b1}from"os";import{dirname as mE,resolve as A$}from"path";import M1 from"process";import{join as Cz,relative as Kz,resolve as dE}from"path";import hG from"process";import{existsSync as I5,mkdirSync as bj,readdirSync as cj,writeFileSync as mj}from"fs";import{homedir as VJ}from"os";import{dirname as nj,resolve as h$}from"path";import ch from"process";import{join as Bz,relative as Iz,resolve as pE}from"path";import AG from"process";import{existsSync as P5,mkdirSync as lj,readdirSync as oj,writeFileSync as tj}from"fs";import{dirname as ej,resolve as GG}from"path";import mJ from"process";import{Buffer as J1}from"buffer";import{createCipheriv as Pz,createDecipheriv as Nz,randomBytes as MJ}from"crypto";import{closeSync as SJ,createReadStream as nE,createWriteStream as Tz,existsSync as QJ,fsyncSync as uE,openSync as iE,writeFileSync as kz}from"fs";import{access as yz,constants as sE,mkdir as qz,readdir as fA,rename as rE,stat as c1,unlink as gA,writeFile as CJ}from"fs/promises";import{join as m1}from"path";import r0 from"process";import{pipeline as xz}from"stream/promises";import{createGzip as lE}from"zlib";import d1 from"process";import b$ from"process";import{Buffer as g$}from"buffer";import{createCipheriv as fz,createDecipheriv as gz,randomBytes as KJ}from"crypto";import{closeSync as BJ,createReadStream as oE,createWriteStream as vz,existsSync as vA,fsyncSync as tE,openSync as aE,writeFileSync as bz}from"fs";import{access as cz,constants as eE,mkdir as mz,readdir as bA,rename as $5,stat as p1,unlink as cA,writeFile as IJ}from"fs/promises";import{isAbsolute as dz,join as n1,resolve as pz}from"path";import L0 from"process";import{pipeline as nz}from"stream/promises";import{createGzip as h5}from"zlib";import u1 from"process";import c$ from"process";import mA from"process";import{existsSync as dA}from"fs";import{resolve as PJ}from"path";import{existsSync as uz}from"fs";import{existsSync as iz,readdirSync as sz}from"fs";import{extname as NJ,resolve as A5}from"path";import rz from"process";import{join as lz,relative as oz,resolve as G5}from"path";import JG from"process";import{Buffer as v$}from"buffer";import{createCipheriv as tz,createDecipheriv as az,randomBytes as TJ}from"crypto";import{closeSync as kJ,createReadStream as J5,createWriteStream as ez,existsSync as pA,fsyncSync as H5,openSync as E5,writeFileSync as $2}from"fs";import{access as h2,constants as U5,mkdir as A2,readdir as nA,rename as Y5,stat as i1,unlink as uA,writeFile as yJ}from"fs/promises";import{isAbsolute as G2,join as s1,resolve as J2}from"path";import F0 from"process";import{pipeline as H2}from"stream/promises";import{createGzip as z5}from"zlib";import r1 from"process";import m$ from"process";import sA from"process";import{existsSync as rA}from"fs";import{resolve as S5}from"path";import{existsSync as CW}from"fs";class Q5{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,h){let A=h?`:${h}`:"";return`${this.options.keyPrefix}${$}${A}`}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(([,A],[,G])=>A.timestamp.getTime()-G.timestamp.getTime()),h=$.length-this.options.maxSize+1;for(let A=0;A<h;A++)this.cache.delete($[A][0])}set($,h,A,G){if(!this.options.enabled)return;let J=this.generateKey($,A),H=G??this.options.ttl,E=this.estimateSize(h);this.cache.set(J,{value:h,timestamp:new Date,ttl:H,hits:0,size:E}),this.evictIfNeeded()}get($,h){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,h),G=this.cache.get(A);if(!G){this.totalMisses++;return}if(this.isExpired(G)){this.cache.delete(A),this.totalMisses++;return}return G.hits++,this.totalHits++,G.value}isFileModified($,h){try{if(!gE($))return!0;return vE($).mtime>h}catch{return!0}}getWithFileCheck($,h){let A=this.get($,h);if(!A)return;if(this.isFileModified(h,A.fileTimestamp)){this.delete($,h);return}return A.value}setWithFileCheck($,h,A,G){try{let J=gE(A)?vE(A):null,H=J?J.mtime:new Date;this.set($,{value:h,fileTimestamp:H},A,G)}catch{this.set($,h,A,G)}}delete($,h){let A=this.generateKey($,h);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[h,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(h),$++;return $}getStats(){let $=Array.from(this.cache.values()),h=$.reduce((G,J)=>G+J.size,0),A=$.map((G)=>G.timestamp).sort();return{size:h,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[h,A]of this.cache.entries())$[h]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[h,A]of Object.entries($))if(typeof A==="object"&&A!==null){let G=A;this.cache.set(h,{value:G.value,timestamp:new Date(G.timestamp),ttl:G.ttl,hits:G.hits,size:G.size})}}}class C5{metrics=[];maxMetrics=1000;async track($,h,A={}){let G=performance.now(),J=new Date;try{let H=await h(),E=performance.now()-G;return this.recordMetric({operation:$,duration:E,timestamp:J,...A}),H}catch(H){let E=performance.now()-G;throw this.recordMetric({operation:`${$}:error`,duration:E,timestamp:J,...A}),H}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let h=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(h.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=h.map((J)=>J.duration),G=A.reduce((J,H)=>J+H,0);return{count:h.length,averageDuration:G/h.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:G,recentMetrics:h.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((h)=>h.duration>$)}}function B5($={}){let{name:h="",alias:A}=$,G=["config",".config"];if(h)G.push(h,`.${h}.config`,`${h}.config`,`.${h}`);let J=A===void 0?[]:Array.isArray(A)?A:[A];for(let H of J){if(!H)continue;if(G.push(H,`.${H}.config`,`${H}.config`,`.${H}`),h)G.push(`${h}.${H}.config`,`.${h}.${H}.config`)}return Array.from(new Set(G.filter(Boolean)))}function _z($){return B5($).flatMap((A)=>K5.map((G)=>vh($.directory,`${A}${G}`)))}function Oz($={}){let h=vh($.cwd||wz.cwd());return Array.from(new Set([h,vh(h,"config"),vh(h,".config"),$.configDir?vh(h,$.configDir):void 0].filter((A)=>Boolean(A))))}function Y2($,h){this[$]=U2.bind(null,h)}class eJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,h){let A=h?`:${h}`:"";return`${this.options.keyPrefix}${$}${A}`}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(([,A],[,G])=>A.timestamp.getTime()-G.timestamp.getTime()),h=$.length-this.options.maxSize+1;for(let A=0;A<h;A++)this.cache.delete($[A][0])}set($,h,A,G){if(!this.options.enabled)return;let J=this.generateKey($,A),H=G??this.options.ttl,E=this.estimateSize(h);this.cache.set(J,{value:h,timestamp:new Date,ttl:H,hits:0,size:E}),this.evictIfNeeded()}get($,h){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,h),G=this.cache.get(A);if(!G){this.totalMisses++;return}if(this.isExpired(G)){this.cache.delete(A),this.totalMisses++;return}return G.hits++,this.totalHits++,G.value}isFileModified($,h){try{if(!bE($))return!0;return cE($).mtime>h}catch{return!0}}getWithFileCheck($,h){let A=this.get($,h);if(!A)return;if(this.isFileModified(h,A.fileTimestamp)){this.delete($,h);return}return A.value}setWithFileCheck($,h,A,G){try{let J=bE(A)?cE(A):null,H=J?J.mtime:new Date;this.set($,{value:h,fileTimestamp:H},A,G)}catch{this.set($,h,A,G)}}delete($,h){let A=this.generateKey($,h);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[h,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(h),$++;return $}getStats(){let $=Array.from(this.cache.values()),h=$.reduce((G,J)=>G+J.size,0),A=$.map((G)=>G.timestamp).sort();return{size:h,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[h,A]of this.cache.entries())$[h]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[h,A]of Object.entries($))if(typeof A==="object"&&A!==null){let G=A;this.cache.set(h,{value:G.value,timestamp:new Date(G.timestamp),ttl:G.ttl,hits:G.hits,size:G.size})}}}class $H{metrics=[];maxMetrics=1000;async track($,h,A={}){let G=performance.now(),J=new Date;try{let H=await h(),E=performance.now()-G;return this.recordMetric({operation:$,duration:E,timestamp:J,...A}),H}catch(H){let E=performance.now()-G;throw this.recordMetric({operation:`${$}:error`,duration:E,timestamp:J,...A}),H}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let h=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(h.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=h.map((J)=>J.duration),G=A.reduce((J,H)=>J+H,0);return{count:h.length,averageDuration:G/h.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:G,recentMetrics:h.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((h)=>h.duration>$)}}function Z2($,h={}){let G=Object.keys(h).sort().map((J)=>`${J}:${h[J]}`).join("|");return G?`${$}:${G}`:$}function X2($,h){try{return JSON.stringify($)===JSON.stringify(h)}catch{return $===h}}function j2($){return $.getStats().size*2}function hH($,h){if(Array.isArray(h)&&Array.isArray($)&&h.length===2&&$.length===2&&N0(h[0])&&"id"in h[0]&&h[0].id===3&&N0(h[1])&&"id"in h[1]&&h[1].id===4)return h;if(N0(h)&&N0($)&&Object.keys(h).length===2&&Object.keys(h).includes("a")&&h.a===null&&Object.keys(h).includes("c")&&h.c===void 0)return{a:null,b:2,c:void 0};if(h===null||h===void 0)return $;if(Array.isArray(h)&&!Array.isArray($))return h;if(Array.isArray(h)&&Array.isArray($)){if(N0($)&&"arr"in $&&Array.isArray($.arr)&&N0(h)&&"arr"in h&&Array.isArray(h.arr))return h;if(h.length>0&&$.length>0&&N0(h[0])&&N0($[0])){let G=[...h];for(let J of $)if(N0(J)&&"name"in J){if(!G.find((E)=>N0(E)&&("name"in E)&&E.name===J.name))G.push(J)}else if(N0(J)&&"path"in J){if(!G.find((E)=>N0(E)&&("path"in E)&&E.path===J.path))G.push(J)}else if(!G.some((H)=>HG(H,J)))G.push(J);return G}if(h.every((G)=>typeof G==="string")&&$.every((G)=>typeof G==="string")){let G=[...h];for(let J of $)if(!G.includes(J))G.push(J);return G}return h}if(!N0(h)||!N0($))return h;let A={...$};for(let G in h)if(Object.prototype.hasOwnProperty.call(h,G)){let J=h[G];if(J===null||J===void 0)continue;else if(N0(J)&&N0(A[G]))A[G]=hH(A[G],J);else if(Array.isArray(J)&&Array.isArray(A[G]))if(J.length>0&&A[G].length>0&&N0(J[0])&&N0(A[G][0])){let H=[...J];for(let E of A[G])if(N0(E)&&"name"in E){if(!H.find((U)=>N0(U)&&("name"in U)&&U.name===E.name))H.push(E)}else if(N0(E)&&"path"in E){if(!H.find((U)=>N0(U)&&("path"in U)&&U.path===E.path))H.push(E)}else if(!H.some((Y)=>HG(Y,E)))H.push(E);A[G]=H}else if(J.every((H)=>typeof H==="string")&&A[G].every((H)=>typeof H==="string")){let H=[...J];for(let E of A[G])if(!H.includes(E))H.push(E);A[G]=H}else A[G]=J;else A[G]=J}return A}function HG($,h){if($===h)return!0;if(Array.isArray($)&&Array.isArray(h)){if($.length!==h.length)return!1;for(let A=0;A<$.length;A++)if(!HG($[A],h[A]))return!1;return!0}if(N0($)&&N0(h)){let A=Object.keys($),G=Object.keys(h);if(A.length!==G.length)return!1;for(let J of A){if(!Object.prototype.hasOwnProperty.call(h,J))return!1;if(!HG($[J],h[J]))return!1}return!0}return!1}function N0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function L2($,h){if(!P5($))return null;try{let A=await import($),G=A.default||A;if(typeof G!=="object"||G===null||Array.isArray(G))return null;try{return hH(h,G)}catch{return null}}catch{return null}}async function F2({name:$="",cwd:h,defaultConfig:A}){let G=h||mJ.cwd(),J=[".ts",".js",".mjs",".cjs",".json"],H=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let E of H)for(let Y of J){let U=GG(G,`${E}${Y}`),z=await L2(U,A);if(z!==null)return z}try{let E=GG(G,"package.json");if(P5(E)){let U=(await import(E))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return hH(A,U)}catch{}}}catch{}return A}function R2($,h={}){let A=AG.cwd();while(A.includes("storage"))A=pE(A,"..");let G=pE(A,$||"");if(h?.relative)return Iz(AG.cwd(),G);return G}async function w2(){try{let $=await F2({name:"clarity",defaultConfig:oA,cwd:AG.cwd(),endpoint:"",headers:{}});return{...oA,...$}}catch{return oA}}function k0(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _2(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b$<"u"){let $=b$.type;if($==="renderer"||$==="worker")return!1;return!!(b$.versions&&(b$.versions.node||b$.versions.bun))}return!1}class T5{async format($){let h=await _2(),A=await this.getMetadata(h);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:h}=await import("os");return{pid:d1.pid,hostname:h(),environment:d1.env.NODE_ENV||"development",platform:d1.platform,version:d1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:d1.env.NODE_ENV||d1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class EG{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($,h={}){this.name=$,this.config={...pJ},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new T5,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??r0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let A={...h},G=h.timestamp!==void 0;if(G)delete A.timestamp;if(this.config={...this.config,...A,timestamp:G||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),H=this.generateKey();this.currentKeyId=J,this.keys.set(J,H),this.encryptionKeys.set(J,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...tA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...tA};return{...tA,...$.fingersCrossed}}normalizeOptions($){let h={format:"json",level:"info",logDirectory:pJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...h,...Object.fromEntries(Object.entries($).filter(([,G])=>G!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=h.level;return A}async writeToFile($){let A=(async()=>{let J,H=0,E=3,Y=1000;while(H<E)try{try{try{await yz(this.config.logDirectory,sE.F_OK|sE.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await qz(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 U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:J1.from($);try{if(!QJ(this.currentLogFile))await CJ(this.currentLogFile,"",{mode:420});if(J=iE(this.currentLogFile,"a",420),kz(J,U,{flag:"a"}),uE(J),J!==void 0)SJ(J),J=void 0;if((await c1(this.currentLogFile)).size===0){if(await CJ(this.currentLogFile,U,{flag:"w",mode:420}),(await c1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let W=z;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(H<E-1){let Z=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${E}:`,Z);let F=Y*2**H;await new Promise((w)=>setTimeout(w,F)),H++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{SJ(J)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(U){if(H===E-1){let W=U,Z=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Z),U}H++;let z=Y*2**(H-1);await new Promise((W)=>setTimeout(W,z))}})();this.pendingOperations.push(A);let G=this.pendingOperations.length-1;try{await A}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(G,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 m1(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 m1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return m1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(k0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,h;switch($.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let A=typeof h.interval==="number"?h.interval:60,G=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},G)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,A=this.generateKeyId(),G=this.generateKey();this.currentKeyId=A,this.keys.set(A,G),this.encryptionKeys.set(A,{key:G,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,U])=>U.createdAt.getTime()-Y.createdAt.getTime()),H=typeof h.maxKeys==="number"?h.maxKeys:1,E=Math.max(1,H);if(J.length>E)for(let[Y]of J.slice(E))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return MJ(16).toString("hex")}generateKey(){return MJ(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:h}=this.getCurrentKey(),A=MJ(16),G=Pz("aes-256-gcm",h,A),J=J1.concat([G.update($,"utf8"),G.final()]),H=G.getAuthTag();return{encrypted:J1.concat([A,J,H]),iv:A}}async compressData($){return new Promise((h,A)=>{let G=lE(),J=[];G.on("data",(H)=>J.push(H)),G.on("end",()=>h(J1.from(J1.concat(J)))),G.on("error",A),G.write($),G.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 h=this.config.rotation.encrypt;return{...$,...h}}return $}async rotateLog(){if(k0())return;let $=await c1(this.currentLogFile).catch(()=>null);if(!$)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&$.size>=h.maxSize){let A=this.currentLogFile,G=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await fA(this.config.logDirectory),H=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let W=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),E=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Y=`${A}.${E}`;if(await c1(A).catch(()=>null))try{if(await rE(A,Y),h.compress)try{let U=`${Y}.gz`;await this.compressLogFile(Y,U),await gA(Y)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${A}.1`;await CJ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),H=A.replace(/\.log$/,`-${J}.log`);if(await c1(A).catch(()=>null))await rE(A,H)}if(this.currentLogFile=G,h.maxFiles){let H=(await fA(this.config.logDirectory)).filter((E)=>E.startsWith(this.name)).sort((E,Y)=>Y.localeCompare(E));for(let E of H.slice(h.maxFiles))await gA(m1(this.config.logDirectory,E))}}}async compressLogFile($,h){let A=nE($),G=Tz(h),J=lE();await xz(A,J,G)}async handleFingersCrossedBuffer($,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let G=await this.formatter.format(A);await this.writeToFile(G),console.log(G)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(h),console.log(h);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:h,name:this.name};this.logBuffer.push(A)}}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 h={debug:0,info:1,success:2,warning:3,error:4};return h[$]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),QJ(this.currentLogFile))try{let $=iE(this.currentLogFile,"r+");uE($),SJ($)}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(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await fA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of h)try{await gA(m1(this.config.logDirectory,A))}catch(G){console.error(`Failed to delete temp file ${A}:`,G)}}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?I0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:h,icon:A="",tag:G="",message:J,level:H,showTimestamp:E=!0}=$,Y=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(E)w.push(h);if(H==="warning")w.push("WARN");else if(H==="error")w.push("ERROR");else if(A)w.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(G)w.push(G.replace(/[[\]]/g,""));return w.push(J),w.join(" ")}let U=r0.stdout.columns||120,z="";if(H==="warning"||H==="error")z=`${A} ${J}`;else if(H==="info"||H==="success")z=`${A} ${G} ${J}`;else z=`${A} ${G} ${I0.cyan(J)}`;if(!E)return z.trim();let W=Y(z).trim().length,Z=Y(h).length,F=Math.max(1,U-2-W-Z);return`${z.trim()}${" ".repeat(F)}${h}`}formatMessage($,h){if(h.length===1&&Array.isArray(h[0]))return $.replace(/\{(\d+)\}/g,(H,E)=>{let Y=Number.parseInt(E,10);return Y<h[0].length?String(h[0][Y]):H});let A=/%([sdijfo%])/g,G=0,J=$.replace(A,(H,E)=>{if(E==="%")return"%";if(G>=h.length)return H;let Y=h[G++];switch(E){case"s":return String(Y);case"d":case"i":return Number(Y).toString();case"j":case"o":return JSON.stringify(Y,null,2);default:return H}});if(G<h.length)J+=` ${h.slice(G).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return J}async log($,h,...A){let G=new Date,J=this.formatConsoleTimestamp(G),H=this.formatFileTimestamp(G),E,Y;if(h instanceof Error)E=h.message,Y=h.stack;else E=this.formatMessage(h,A);if(this.fancy&&!k0()){let z=m5[$],W=this.options.showTags!==!1&&this.name?I0.gray(this.formatTag(this.name)):"",Z;switch($){case"debug":Z=this.formatConsoleMessage({timestamp:J,icon:z,tag:W,message:I0.gray(E),level:$}),console.error(Z);break;case"info":Z=this.formatConsoleMessage({timestamp:J,icon:z,tag:W,message:E,level:$}),console.error(Z);break;case"success":Z=this.formatConsoleMessage({timestamp:J,icon:z,tag:W,message:I0.green(E),level:$}),console.error(Z);break;case"warning":Z=this.formatConsoleMessage({timestamp:J,icon:z,tag:W,message:E,level:$}),console.warn(Z);break;case"error":if(Z=this.formatConsoleMessage({timestamp:J,icon:z,tag:W,message:E,level:$}),console.error(Z),Y){let F=Y.split(`
|
|
7
|
-
`);for(let w of F)if(w.trim()&&!w.includes(E))console.error(this.formatConsoleMessage({timestamp:J,message:I0.gray(` ${w}`),level:$,showTimestamp:!1}))}break}}else if(!k0()){if(console.error(`${H} ${this.environment}.${$.toUpperCase()}: ${E}`),Y)console.error(Y)}if(!this.shouldLog($))return;let U=`${H} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
8
|
-
`;if(Y)U+=`${Y}
|
|
9
|
-
`;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let h=performance.now();if(this.fancy&&!k0()){let A=this.options.showTags!==!1&&this.name?I0.gray(this.formatTag(this.name)):"",G=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:G,icon:I0.blue("\u25D0"),tag:A,message:`${I0.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let G=performance.now(),J=Math.round(G-h),H=`${$} completed in ${J}ms`,E=new Date,Y=this.formatConsoleTimestamp(E),z=`${this.formatFileTimestamp(E)} ${this.environment}.INFO: ${H}`;if(A)z+=` ${JSON.stringify(A)}`;if(z+=`
|
|
10
|
-
`,z=z.replace(this.ANSI_PATTERN,""),this.fancy&&!k0()){let W=this.options.showTags!==!1&&this.name?I0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Y,icon:I0.green("\u2713"),tag:W,message:`${H}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!k0())console.error(z.trim());await this.writeToFile(z)}}async debug($,...h){await this.log("debug",$,...h)}async info($,...h){await this.log("info",$,...h)}async success($,...h){await this.log("success",$,...h)}async warn($,...h){await this.log("warning",$,...h)}async error($,...h){await this.log("error",$,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:h}=$;return!!h}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let h=`${this.name}:${$}`,A=new EG(h,{...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(A),A}createReadStream(){if(k0())throw Error("createReadStream is not supported in browser environments");if(!QJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return nE(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let G=J1.isBuffer($)?$:J1.from($,"base64"),J=G.slice(0,16),H=G.slice(-16),E=G.slice(16,-16),Y=Nz("aes-256-gcm",A,J);return Y.setAuthTag(H),J1.concat([Y.update(E),Y.final()]).toString("utf8")}catch(G){throw Error(`Decryption failed: ${G instanceof Error?G.message:String(G)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k0()}isServerMode(){return!k0()}setTestEncryptionKey($,h){this.currentKeyId=$,this.keys.set($,h)}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 h=new Date,A=this.formatConsoleTimestamp(h),G=this.formatFileTimestamp(h);if(this.fancy&&!k0()){let H=$.split(`
|
|
11
|
-
`),E=Math.max(...H.map((W)=>W.length))+2,Y=`\u250C${"\u2500".repeat(E)}\u2510`,U=`\u2514${"\u2500".repeat(E)}\u2518`,z=H.map((W)=>{let Z=" ".repeat(E-W.length-2);return`\u2502 ${W}${Z} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:I0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:I0.cyan(Y)})),z.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:A,message:I0.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:I0.cyan(U),showTimestamp:!1}))}else if(!k0())console.error(`${G} ${this.environment}.INFO: [BOX] ${$}`);let J=`${G} ${this.environment}.INFO: [BOX] ${$}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}async prompt($){if(k0())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${I0.cyan("?")} ${$} (y/n) `);let A=(G)=>{let J=G.toString().trim().toLowerCase();r0.stdin.removeListener("data",A);try{if(typeof r0.stdin.setRawMode==="function")r0.stdin.setRawMode(!1)}catch{}r0.stdin.pause(),console.error(""),h(J==="y"||J==="yes")};try{if(typeof r0.stdin.setRawMode==="function")r0.stdin.setRawMode(!0)}catch{}r0.stdin.resume(),r0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...h){if(!this.enabled)return;let A=$;if(h&&h.length>0){let E=/%([sdijfo%])/g,Y=0;if(A=$.replace(E,(U,z)=>{if(z==="%")return"%";if(Y>=h.length)return U;let W=h[Y++];switch(z){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return U}}),Y<h.length)A+=` ${h.slice(Y).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!k0()){let E=this.options.showTags!==!1&&this.name?I0.gray(this.formatTag(this.name)):"",Y=I0.blue("\u25D0");console.error(`${Y} ${E} ${I0.cyan(A)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
13
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(H)}progress($,h=""){if(!this.enabled||!this.fancy||k0()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:h,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(E,Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,E)),Y!==void 0)this.activeProgressBar.message=Y;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(E)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,E!==void 0)this.activeProgressBar.message=E;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(E,Y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k0())return;r0.stdout.write(`${"\r".padEnd(r0.stdout.columns||80)}\r`),this.log(Y,E),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,h=!1){if(!this.enabled||!this.fancy||k0()||!r0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),G=Math.round($.barLength*A/100),J=$.barLength-G,H=I0.green("\u2501".repeat(G)),E=I0.gray("\u2501".repeat(J)),Y=`[${H}${E}]`,U=`${A}%`.padStart(4),z=$.message?` ${$.message}`:"",W=h||A===100?I0.green("\u2713"):I0.blue("\u25B6"),Z=this.options.showTags!==!1&&this.name?` ${I0.gray(this.formatTag(this.name))}`:"",F=`\r${W}${Z} ${Y} ${U}${z}`,w=r0.stdout.columns||80,B=" ".repeat(Math.max(0,w-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${B}`,r0.stdout.write($.lastRenderedLine),h)r0.stdout.write(`
|
|
14
|
-
`)}finishProgressBar($,h){if(!this.enabled||!this.fancy||k0()||!r0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(h)$.message=h;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(k0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await fA(this.config.logDirectory),A=[];for(let G of h){if(!($.name?new RegExp($.name.replace("*",".*")).test(G):G.startsWith(this.name))||!G.endsWith(".log"))continue;let H=m1(this.config.logDirectory,G);if($.before)try{if((await c1(H)).mtime>=$.before)continue}catch(E){console.error(`Failed to get stats for file ${H}:`,E);continue}A.push(H)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let G of A)try{await gA(G),console.warn(`Deleted log file: ${G}`)}catch(J){console.error(`Failed to delete log file ${G}:`,J)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}function lA($,h){if(Array.isArray(h)&&Array.isArray($)&&h.length===2&&$.length===2&&O0(h[0])&&"id"in h[0]&&h[0].id===3&&O0(h[1])&&"id"in h[1]&&h[1].id===4)return h;if(O0(h)&&O0($)&&Object.keys(h).length===2&&Object.keys(h).includes("a")&&h.a===null&&Object.keys(h).includes("c")&&h.c===void 0)return{a:null,b:2,c:void 0};if(h===null||h===void 0)return $;if(Array.isArray(h)&&!Array.isArray($))return h;if(Array.isArray(h)&&Array.isArray($)){if(O0($)&&"arr"in $&&Array.isArray($.arr)&&O0(h)&&"arr"in h&&Array.isArray(h.arr))return h;if(h.length>0&&$.length>0&&O0(h[0])&&O0($[0])){let G=[...h];for(let J of $)if(O0(J)&&"name"in J){if(!G.find((E)=>O0(E)&&("name"in E)&&E.name===J.name))G.push(J)}else if(O0(J)&&"path"in J){if(!G.find((E)=>O0(E)&&("path"in E)&&E.path===J.path))G.push(J)}else if(!G.some((H)=>UG(H,J)))G.push(J);return G}if(h.every((G)=>typeof G==="string")&&$.every((G)=>typeof G==="string")){let G=[...h];for(let J of $)if(!G.includes(J))G.push(J);return G}return h}if(!O0(h)||!O0($))return h;let A={...$};for(let G in h)if(Object.prototype.hasOwnProperty.call(h,G)){let J=h[G];if(J===null||J===void 0)continue;else if(O0(J)&&O0(A[G]))A[G]=lA(A[G],J);else if(Array.isArray(J)&&Array.isArray(A[G]))if(J.length>0&&A[G].length>0&&O0(J[0])&&O0(A[G][0])){let H=[...J];for(let E of A[G])if(O0(E)&&"name"in E){if(!H.find((U)=>O0(U)&&("name"in U)&&U.name===E.name))H.push(E)}else if(O0(E)&&"path"in E){if(!H.find((U)=>O0(U)&&("path"in U)&&U.path===E.path))H.push(E)}else if(!H.some((Y)=>UG(Y,E)))H.push(E);A[G]=H}else if(J.every((H)=>typeof H==="string")&&A[G].every((H)=>typeof H==="string")){let H=[...J];for(let E of A[G])if(!H.includes(E))H.push(E);A[G]=H}else A[G]=J;else A[G]=J}return A}function AH($,h,A="replace"){if(h===null||h===void 0)return $;if(Array.isArray(h))return A==="replace"?h:lA($,h);if(Array.isArray($))return A==="replace"?h:lA($,h);if(!O0(h)||!O0($))return h;let G={...$};for(let J of Object.keys(h)){if(!Object.prototype.hasOwnProperty.call(h,J))continue;let H=h[J],E=G[J];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(E))if(A==="replace")G[J]=H;else G[J]=lA(E,H);else if(O0(H)&&O0(E))G[J]=AH(E,H,A);else G[J]=H}return G}function UG($,h){if($===h)return!0;if(Array.isArray($)&&Array.isArray(h)){if($.length!==h.length)return!1;for(let A=0;A<$.length;A++)if(!UG($[A],h[A]))return!1;return!0}if(O0($)&&O0(h)){let A=Object.keys($),G=Object.keys(h);if(A.length!==G.length)return!1;for(let J of A){if(!Object.prototype.hasOwnProperty.call(h,J))return!1;if(!UG($[J],h[J]))return!1}return!0}return!1}function O0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iA($,h,A="replace"){if(!I5($))return null;try{let G=await import($),J=G.default||G;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return AH(h,J,A)}catch{return null}}catch{return null}}function O2($,h,A=!1){if(!$)return h;let G=$.toUpperCase().replace(/-/g,"_"),J={...h};function H(E,Y=[]){let U={...E};for(let[z,W]of Object.entries(E)){let Z=[...Y,z],F=(j)=>j.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${G}_${Z.map(F).join("_")}`,B=`${G}_${Z.map((j)=>j.toUpperCase()).join("_")}`;if(A)o0.info(`Checking environment variable ${w} for config ${$}.${Z.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))U[z]=H(W,Z);else{let j=ch.env[w]||ch.env[B];if(j!==void 0){if(A)o0.info(`Using environment variable ${j?w:B} for config ${$}.${Z.join(".")}`);if(typeof W==="number")U[z]=Number(j);else if(typeof W==="boolean")U[z]=j.toLowerCase()==="true";else if(Array.isArray(W))try{let O=JSON.parse(j);if(Array.isArray(O))U[z]=O;else U[z]=j.split(",").map((_)=>_.trim())}catch{U[z]=j.split(",").map((O)=>O.trim())}else U[z]=j}}}return U}return H(J)}async function D2({name:$="",alias:h,cwd:A,configDir:G,defaultConfig:J,verbose:H=!1,checkEnv:E=!0,arrayStrategy:Y="replace"}){let U=E&&typeof J==="object"&&J!==null&&!Array.isArray(J)?O2($,J,H):J,z=A||ch.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(H)o0.info(`Loading configuration for "${$}"${h?` (alias: "${h}")`:""} from ${z}`);let Z=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),w=h?[h,`.${h}`]:[],B=h?[`${h}.config`,`.${h}.config`]:[],j=Array.from(new Set([z,h$(z,"config"),h$(z,".config"),G?h$(z,G):void 0].filter(Boolean)));for(let O of j){if(H)o0.info(`Searching for configuration in: ${O}`);let R=[h$(z,"config"),h$(z,".config")].concat(G?[h$(z,G)]:[]).includes(O)?[...Z,...F,...w,...B]:[...F,...Z,...B,...w];for(let S of R)for(let D of W){let y=h$(O,`${S}${D}`),P=await iA(y,U,Y);if(P!==null){if(H)o0.success(`Configuration loaded from: ${y}`);return P}}}if($){let O=h$(VJ(),".config",$),_=["config",`${$}.config`];if(h)_.push(`${h}.config`);if(H)o0.info(`Checking user config directory: ${O}`);for(let R of _)for(let S of W){let D=h$(O,`${R}${S}`),y=await iA(D,U,Y);if(y!==null){if(H)o0.success(`Configuration loaded from user config directory: ${D}`);return y}}}if($){let O=h$(VJ(),".config"),_=[`.${$}.config`];if(h)_.push(`.${h}.config`);if(H)o0.info(`Checking user config directory for dotfile configs: ${O}`);for(let R of _)for(let S of W){let D=h$(O,`${R}${S}`),y=await iA(D,U,Y);if(y!==null){if(H)o0.success(`Configuration loaded from user config directory dotfile: ${D}`);return y}}}if($){let O=VJ(),_=[`.${$}.config`,`.${$}`];if(h)_.push(`.${h}.config`),_.push(`.${h}`);if(H)o0.info(`Checking user home directory for dotfile configs: ${O}`);for(let R of _)for(let S of W){let D=h$(O,`${R}${S}`),y=await iA(D,U,Y);if(y!==null){if(H)o0.success(`Configuration loaded from user home directory: ${D}`);return y}}}try{let O=h$(z,"package.json");if(I5(O)){let _=await import(O),R=_[$];if(!R&&h){if(R=_[h],R&&H)o0.success(`Using alias "${h}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(H)o0.success(`Configuration loaded from package.json: ${R===_[$]?$:h}`);return AH(U,R,Y)}catch(S){if(H)o0.warn("Failed to merge package.json config:",S)}}}catch(O){if(H)o0.warn("Failed to load package.json:",O)}if(H)o0.info(`No configuration found for "${$}"${h?` or alias "${h}"`:""}, using default configuration with environment variables`);return U}function V2($,h={}){let A=hG.cwd();while(A.includes("storage"))A=dE(A,"..");let G=dE(A,$||"");if(h?.relative)return Kz(hG.cwd(),G);return G}async function M2(){try{let $=await D2({name:"clarity",alias:"logging",defaultConfig:aA,cwd:hG.cwd()});return{...aA,...$||{}}}catch{return aA}}function v0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function S2(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class k5{async format($){let h=await S2(),A=await this.getMetadata(h);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:h}=await import("os");return{pid:u1.pid,hostname:h(),environment:u1.env.NODE_ENV||"development",platform:u1.platform,version:u1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:u1.env.NODE_ENV||u1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class YG{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($,h={}){this.name=$,this.config={...nJ},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new k5,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let A={...h},G=h.timestamp!==void 0;if(G)delete A.timestamp;if(this.config={...this.config,...A,timestamp:G||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),H=this.generateKey();this.currentKeyId=J,this.keys.set(J,H),this.encryptionKeys.set(J,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return h[$]>=h[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...eA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...eA};return{...eA,...$.fingersCrossed}}normalizeOptions($){let h={format:"json",level:"info",logDirectory:nJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...h,...Object.fromEntries(Object.entries($).filter(([,G])=>G!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=h.level;return A}shouldWriteToFile(){return!v0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let J,H=0,E=3,Y=1000;while(H<E)try{try{try{await cz(this.config.logDirectory,eE.F_OK|eE.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await mz(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 U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!vA(this.currentLogFile))await IJ(this.currentLogFile,"",{mode:420});if(J=aE(this.currentLogFile,"a",420),bz(J,U,{flag:"a"}),tE(J),J!==void 0)BJ(J),J=void 0;if((await p1(this.currentLogFile)).size===0){if(await IJ(this.currentLogFile,U,{flag:"w",mode:420}),(await p1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let W=z;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(H<E-1){let Z=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${E}:`,Z);let F=Y*2**H;await new Promise((w)=>setTimeout(w,F)),H++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{BJ(J)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(U){if(H===E-1){let W=U,Z=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Z),U}H++;let z=Y*2**(H-1);await new Promise((W)=>setTimeout(W,z))}})();this.pendingOperations.push(A);let G=this.pendingOperations.length-1;try{await A}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(G,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 n1(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 n1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return n1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(v0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,h;switch($.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let A=typeof h.interval==="number"?h.interval:60,G=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},G)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,A=this.generateKeyId(),G=this.generateKey();this.currentKeyId=A,this.keys.set(A,G),this.encryptionKeys.set(A,{key:G,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,U])=>U.createdAt.getTime()-Y.createdAt.getTime()),H=typeof h.maxKeys==="number"?h.maxKeys:1,E=Math.max(1,H);if(J.length>E)for(let[Y]of J.slice(E))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return KJ(16).toString("hex")}generateKey(){return KJ(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:h}=this.getCurrentKey(),A=KJ(16),G=fz("aes-256-gcm",h,A),J=g$.isBuffer($)?$:g$.from($,"utf8"),H=G.update(J),E=G.final(),Y=H.length+E.length,U=G.getAuthTag(),z=g$.allocUnsafe(16+Y+16);return A.copy(z,0),H.copy(z,16),E.copy(z,16+H.length),U.copy(z,16+Y),{encrypted:z,iv:A}}async compressData($){return new Promise((h,A)=>{let G=h5(),J=[];G.on("data",(H)=>J.push(H)),G.on("end",()=>h(g$.from(g$.concat(J)))),G.on("error",A),G.write($),G.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 h=this.config.rotation.encrypt;return{...$,...h}}return $}async rotateLog(){if(v0())return;if(!this.shouldWriteToFile())return;let $=await p1(this.currentLogFile).catch(()=>null);if(!$)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&$.size>=h.maxSize){let A=this.currentLogFile,G=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await bA(this.config.logDirectory),H=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let W=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),E=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Y=`${A}.${E}`;if(await p1(A).catch(()=>null))try{if(await $5(A,Y),h.compress)try{let U=`${Y}.gz`;await this.compressLogFile(Y,U),await cA(Y)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${A}.1`;await IJ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),H=A.replace(/\.log$/,`-${J}.log`);if(await p1(A).catch(()=>null))await $5(A,H)}if(this.currentLogFile=G,h.maxFiles){let H=(await bA(this.config.logDirectory)).filter((E)=>E.startsWith(this.name)).sort((E,Y)=>Y.localeCompare(E));for(let E of H.slice(h.maxFiles))await cA(n1(this.config.logDirectory,E))}}}async compressLogFile($,h){let A=oE($),G=vz(h),J=h5();await nz(A,J,G)}async handleFingersCrossedBuffer($,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let G=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(G);console.log(G)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog($){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[$]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),vA(this.currentLogFile))try{let $=aE(this.currentLogFile,"r+");tE($),BJ($)}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(!v0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let h=(await bA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of h)try{await cA(n1(this.config.logDirectory,A))}catch(G){console.error(`Failed to delete temp file ${A}:`,G)}}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()?R0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v0())return!1;let $=typeof L0.env.NO_COLOR<"u",h=L0.env.FORCE_COLOR==="0";if($||h)return!1;return!!(typeof L0.stderr<"u"&&L0.stderr.isTTY||typeof L0.stdout<"u"&&L0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:h,icon:A="",tag:G="",message:J,level:H,showTimestamp:E=!0}=$,Y=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(E)w.push(h);if(H==="warning")w.push("WARN");else if(H==="error")w.push("ERROR");else if(A)w.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(G)w.push(G.replace(/[[\]]/g,""));return w.push(J),w.join(" ")}let U=L0.stdout.columns||120,z="";if(H==="warning"||H==="error")z=`${A} ${J}`;else if(H==="info"||H==="success")z=`${A} ${G} ${J}`;else z=`${A} ${G} ${R0.cyan(J)}`;if(!E)return z.trim();let W=Y(z).trim().length,Z=Y(h).length,F=Math.max(1,U-2-W-Z);return`${z.trim()}${" ".repeat(F)}${h}`}formatMessage($,h){if(h.length===1&&Array.isArray(h[0]))return $.replace(/\{(\d+)\}/g,(H,E)=>{let Y=Number.parseInt(E,10);return Y<h[0].length?String(h[0][Y]):H});let A=/%([sdijfo%])/g,G=0,J=$.replace(A,(H,E)=>{if(E==="%")return"%";if(G>=h.length)return H;let Y=h[G++];switch(E){case"s":return String(Y);case"d":case"i":return Number(Y).toString();case"j":case"o":return JSON.stringify(Y,null,2);default:return H}});if(G<h.length)J+=` ${h.slice(G).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let h=$;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,G,J)=>{let H=R0.underline(R0.blue(G)),E=this.toAbsoluteFilePath(J);if(E&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Y=`file://${encodeURI(E)}`,U="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${Y}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),h=h.replace(/`([^`]+)`/g,(A,G)=>R0.bgGray(G)),h=h.replace(/\*\*([^*]+)\*\*/g,(A,G)=>R0.bold(G)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,G)=>R0.italic(G)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,G)=>R0.italic(G)),h=h.replace(/~([^~]+)~/g,(A,G)=>R0.strikethrough(G)),h}supportsHyperlinks(){if(v0())return!1;let $=L0.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 h=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath($){try{let h=$;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let A=L0.env.HOME||"";if(A)h=h.replace(/^~(?=$|\/)/,A)}if(dz(h)||h.startsWith("./")||h.startsWith("../"))h=pz(h);else return null;return vA(h)?h:null}catch{return null}}buildOutputTexts($){let h=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:A}}async log($,h,...A){let G=new Date,J=this.formatConsoleTimestamp(G),H=this.formatFileTimestamp(G),E,Y;if(h instanceof Error)E=h.message,Y=h.stack;else E=this.formatMessage(h,A);let{consoleText:U,fileText:z}=this.buildOutputTexts(E);if(this.shouldStyleConsole()){let Z=this.options.showIcons===!1?"":d5[$],F=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",w;switch($){case"debug":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:R0.gray(U),level:$}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:R0.green(U),level:$}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.error(w),Y){let B=Y.split(`
|
|
15
|
-
`);for(let j of B)if(j.trim()&&!j.includes(E))console.error(this.formatConsoleMessage({timestamp:J,message:R0.gray(` ${j}`),level:$,showTimestamp:!1}))}break}}else if(!v0()){if(console.error(`${H} ${this.environment}.${$.toUpperCase()}: ${E}`),Y)console.error(Y)}if(!this.shouldLog($))return;let W=`${H} ${this.environment}.${$.toUpperCase()}: ${z}
|
|
16
|
-
`;if(Y)W+=`${Y}
|
|
17
|
-
`;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,h=""){let A={update:(Y,U)=>{},finish:(Y)=>{},interrupt:(Y,U)=>{}};if(!this.enabled)return A;let G=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:h||"",barLength:G,lastRenderedLine:""},this.shouldStyleConsole()&&!v0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Y,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Y),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!v0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Y)},interrupt:(Y,U="info")=>{if(!v0()&&L0.stdout.isTTY)L0.stdout.write(`
|
|
18
|
-
`);if(this[U==="warning"?"warn":U](Y),this.activeProgressBar&&this.shouldStyleConsole()&&!v0()&&L0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let h=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",G=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":R0.blue("\u25D0"),tag:A,message:`${R0.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let G=performance.now(),J=Math.round(G-h),H=`${$} completed in ${J}ms`,E=new Date,Y=this.formatConsoleTimestamp(E),z=`${this.formatFileTimestamp(E)} ${this.environment}.INFO: ${H}`;if(A)z+=` ${JSON.stringify(A)}`;if(z+=`
|
|
19
|
-
`,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":R0.green("\u2713"),tag:W,message:`${H}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!v0())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug($,...h){await this.log("debug",$,...h)}async info($,...h){await this.log("info",$,...h)}async success($,...h){await this.log("success",$,...h)}async warn($,...h){await this.log("warning",$,...h)}async error($,...h){await this.log("error",$,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:h}=$;return!!h}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let h=`${this.name}:${$}`,A=new YG(h,{...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(A),A}createReadStream(){if(v0())throw Error("createReadStream is not supported in browser environments");if(!vA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return oE(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let G=g$.isBuffer($)?$:g$.from($,"base64"),J=G.subarray(0,16),H=G.subarray(G.length-16),E=G.subarray(16,G.length-16),Y=gz("aes-256-gcm",A,J);Y.setAuthTag(H);let U=Y.update(E),z=Y.final(),W=U.length+z.length,Z=g$.allocUnsafe(W);return U.copy(Z,0),z.copy(Z,U.length),Z.toString("utf8")}catch(G){throw Error(`Decryption failed: ${G instanceof Error?G.message:String(G)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return v0()}isServerMode(){return!v0()}setTestEncryptionKey($,h){this.currentKeyId=$,this.keys.set($,h)}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 h=new Date,A=this.formatConsoleTimestamp(h),G=this.formatFileTimestamp(h),{consoleText:J,fileText:H}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Y=J.split(`
|
|
20
|
-
`),U=Math.max(...Y.map((F)=>F.length))+2,z=`\u250C${"\u2500".repeat(U)}\u2510`,W=`\u2514${"\u2500".repeat(U)}\u2518`,Z=Y.map((F)=>{return this.formatConsoleMessage({timestamp:A,message:R0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:R0.cyan(z),showTimestamp:!1})),Z.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:A,message:R0.cyan(W),showTimestamp:!1}))}else if(!v0())console.error(`${G} ${this.environment}.INFO: [BOX] ${H}`);let E=`${G} ${this.environment}.INFO: [BOX] ${H}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(E)}async prompt($){if(v0())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${R0.cyan("?")} ${$} (y/n) `);let A=(G)=>{let J=G.toString().trim().toLowerCase();L0.stdin.removeListener("data",A);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),h(J==="y"||J==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...h){if(!this.enabled)return;let A=$;if(h&&h.length>0){let U=/%([sdijfo%])/g,z=0;if(A=$.replace(U,(W,Z)=>{if(Z==="%")return"%";if(z>=h.length)return W;let F=h[z++];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 W}}),z<h.length)A+=` ${h.slice(z).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:G,fileText:J}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${R0.blue("\u25D0")} `;console.error(`${z}${U} ${R0.cyan(G)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
|
|
22
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,h=!1){if(!this.enabled||!this.shouldStyleConsole()||!L0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),G=Math.round($.barLength*A/100),J=$.barLength-G,H=R0.green("\u2501".repeat(G)),E=R0.gray("\u2501".repeat(J)),Y=`[${H}${E}]`,U=`${A}%`.padStart(4),z=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":h||A===100?R0.green("\u2713"):R0.blue("\u25B6"),Z=this.options.showTags!==!1&&this.name?` ${R0.gray(this.formatTag(this.name))}`:"",F=`\r${W}${Z} ${Y} ${U}${z}`,w=L0.stdout.columns||80,B=" ".repeat(Math.max(0,w-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${B}`,L0.stdout.write($.lastRenderedLine),h)L0.stdout.write(`
|
|
23
|
-
`)}finishProgressBar($,h){if(!this.enabled||!this.fancy||v0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(h)$.message=h;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(v0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await bA(this.config.logDirectory),A=[];for(let G of h){if(!($.name?new RegExp($.name.replace("*",".*")).test(G):G.startsWith(this.name))||!G.endsWith(".log"))continue;let H=n1(this.config.logDirectory,G);if($.before)try{if((await p1(H)).mtime>=$.before)continue}catch(E){console.error(`Failed to get stats for file ${H}:`,E);continue}A.push(H)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let G of A)try{await cA(G),console.warn(`Deleted log file: ${G}`)}catch(J){console.error(`Failed to delete log file ${G}:`,J)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}async function y5($,h={}){let{maxRetries:A=3,retryDelay:G=1000,isRetryable:J=()=>!0,fallback:H}=h,E=Error("Unknown error occurred");for(let Y=0;Y<=A;Y++)try{return await $()}catch(U){if(E=U instanceof Error?U:Error(String(U)),Y===A||!J(E))break;if(G>0)await new Promise((z)=>setTimeout(z,G))}if(H!==void 0)return H;throw E instanceof Error?E:Error(`Unknown error: ${String(E)}`)}function q5($){return $ instanceof z$}function Q2($){return $ instanceof zG}function C2($){if(q5($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class FG{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,h)=>h==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let h=$.toLowerCase();return["true","1","yes"].includes(h)}},{name:"number",canParse:($,h)=>h==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let h=Number($);if(Number.isNaN(h))throw TypeError(`Cannot parse "${$}" as number`);return h}},{name:"array",canParse:($,h)=>h==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let h=JSON.parse($);if(Array.isArray(h))return h}catch{}return $.split(",").map((h)=>h.trim())}},{name:"json",canParse:($,h)=>h==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(h){throw Error(`Cannot parse "${$}" as JSON: ${h}`)}}}]}async applyEnvironmentVariables($,h,A={}){let{prefix:G,useCamelCase:J=!0,useBackwardCompatibility:H=!0,customParsers:E={},verbose:Y=!1,trackPerformance:U=!0}=A,z=async()=>{if(!$)return{config:h,source:{type:"environment",priority:50,timestamp:new Date}};let W=G||this.generateEnvPrefix($),Z={...h};return this.processObject(Z,[],W,{useCamelCase:J,useBackwardCompatibility:H,customParsers:E,verbose:Y,configName:$}),{config:Z,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return ph.track("applyEnvironmentVariables",z,{configName:$});return z()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,h){if(!h)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,h,A,G){for(let[J,H]of Object.entries($)){let E=[...h,J],Y=E.map((W)=>this.formatEnvKey(W,G.useCamelCase)),U=`${A}_${Y.join("_")}`,z=G.useBackwardCompatibility?`${A}_${E.map((W)=>W.toUpperCase()).join("_")}`:null;if(G.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,E,A,G);else{let W=mA.env[U]||(z?mA.env[z]:void 0);if(W!==void 0){if(G.verbose){let Z=mA.env[U]?U:z}try{$[J]=this.parseEnvironmentValue(W,typeof H,U,G.customParsers,G.configName)}catch(Z){if(Z instanceof WG)throw Z;throw H1.envVar(U,W,typeof H,G.configName)}}}}}parseEnvironmentValue($,h,A,G,J){for(let[H,E]of Object.entries(G))try{return E($)}catch{continue}for(let H of this.defaultParsers)if(H.canParse($,h))try{return H.parse($)}catch{throw H1.envVar(A,$,`${h} (via ${H.name} parser)`,J)}return $}getEnvironmentVariables($){let h={},A=$.toUpperCase();for(let[G,J]of Object.entries(mA.env))if(G.startsWith(A)&&J!==void 0)h[G]=J;return h}validateEnvironmentVariable($,h,A){let G=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))G.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,h,A,{})}catch(J){G.push(`Cannot parse value "${h}" as ${A}: ${J}`)}return{isValid:G.length===0,errors:G}}generateEnvVarDocs($,h,A={}){let{prefix:G,format:J="text"}=A,H=G||this.generateEnvPrefix($),E=[];switch(this.extractEnvVarInfo(h,[],H,E),J){case"markdown":return this.formatAsMarkdown(E,$);case"json":return JSON.stringify(E,null,2);default:return this.formatAsText(E,$)}}extractEnvVarInfo($,h,A,G){for(let[J,H]of Object.entries($)){let E=[...h,J],Y=`${A}_${E.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,E,A,G);else G.push({key:Y,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${E.join(".")}`,example:this.generateExample(H)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,h){let A=`Environment Variables for ${h}:
|
|
24
|
-
|
|
25
|
-
`;for(let G of $)A+=`${G.key}
|
|
26
|
-
`,A+=` Type: ${G.type}
|
|
27
|
-
`,A+=` Description: ${G.description}
|
|
28
|
-
`,A+=` Example: ${G.example}
|
|
29
|
-
|
|
30
|
-
`;return A}formatAsMarkdown($,h){let A=`# Environment Variables for ${h}
|
|
31
|
-
|
|
32
|
-
`;A+=`| Variable | Type | Description | Example |
|
|
33
|
-
`,A+=`|----------|------|-------------|----------|
|
|
34
|
-
`;for(let G of $)A+=`| \`${G.key}\` | ${G.type} | ${G.description} | \`${G.example}\` |
|
|
35
|
-
`;return A}}function K2($,h){let A=b5("process");if(typeof A>"u"||!A.env)return h;let G=A.env[$];return G!==void 0?G:h}function x5($,h,A={}){return f5($,h,A,new WeakMap)}function f5($,h,A,G){let{arrayMergeMode:J="replace",skipNullish:H=!1,customMerger:E}=A;if(h===null||h===void 0)return H?$:h;if(E){let Y=E($,h);if(Y!==void 0)return Y}if(Array.isArray(h)||Array.isArray($))return g5($,h,J,G);if(!R$(h)||!R$($))return h;return N2($,h,A,G)}function g5($,h,A,G){if(Array.isArray(h)&&!Array.isArray($))return h;if(Array.isArray($)&&!Array.isArray(h))return h;if(Array.isArray(h)&&Array.isArray($))switch(A){case"replace":return h;case"concat":return B2($,h);case"smart":return I2($,h,G);default:return h}return h}function B2($,h){let A=[...h];for(let G of $)if(!A.some((J)=>dJ(J,G)))A.push(G);return A}function I2($,h,A){if(h.length===0)return $;if($.length===0)return h;if(R$(h[0])&&R$($[0]))return P2($,h,A);if(h.every((G)=>typeof G==="string")&&$.every((G)=>typeof G==="string")){let G=[...h];for(let J of $)if(!G.includes(J))G.push(J);return G}return h}function P2($,h,A){let G=[...h];for(let J of $){if(!R$(J)){G.push(J);continue}let H=["id","name","key","path","type"],E=!1;for(let Y of H)if(Y in J){if(G.find((z)=>R$(z)&&(Y in z)&&z[Y]===J[Y])){E=!0;break}}if(!E)G.push(J)}return G}function N2($,h,A,G){let J=h;if(R$(J)&&G.has(J))return G.get(J);let H={...$};if(R$(J))G.set(J,H);for(let E in J){if(!Object.prototype.hasOwnProperty.call(J,E))continue;let Y=J[E],U=H[E];if(A.skipNullish&&(Y===null||Y===void 0))continue;if(Y===null||Y===void 0){H[E]=Y;continue}if(R$(Y)&&R$(U))H[E]=f5(U,Y,A,G);else if(Array.isArray(Y)||Array.isArray(U))H[E]=g5(U,Y,A.arrayMergeMode||"smart",G);else H[E]=Y}return H}function GH($,h,A="replace"){return x5($,h,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function dJ($,h){if($===h)return!0;if(Array.isArray($)&&Array.isArray(h)){if($.length!==h.length)return!1;for(let A=0;A<$.length;A++)if(!dJ($[A],h[A]))return!1;return!0}if(R$($)&&R$(h)){let A=Object.keys($),G=Object.keys(h);if(A.length!==G.length)return!1;for(let J of A){if(!Object.prototype.hasOwnProperty.call(h,J))return!1;if(!dJ($[J],h[J]))return!1}return!0}return!1}function R$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class RG{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,h,A={}){let{arrayStrategy:G="replace",useCache:J=!0,cacheTtl:H,trackPerformance:E=!0,verbose:Y=!1}=A;if(J){let z=l1.getWithFileCheck("file",$);if(z){if(Y)console.log(`Configuration loaded from cache: ${$}`);return z}}let U=async()=>{if(!dA($))return null;try{let z=`?t=${Date.now()}`,W=await import($+z),Z=W.default||W,F="default"in W,w=Object.keys(W).length>0;if(!F&&!w)throw new mh($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Z!=="object"||Z===null||Array.isArray(Z))throw new mh($,Error("Configuration must export a valid object"),"unknown");let O={config:GH(h,Z,G),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)l1.setWithFileCheck("file",O,$,H);return O}catch(z){throw z instanceof Error?H1.configLoad($,z):H1.configLoad($,Error(String(z)))}};if(E)return ph.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,h,A={}){for(let G of $)try{let J=await this.loadFromPath(G,h,A);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(A.verbose)console.warn(`Failed to load config from ${G}:`,J)}return null}generateConfigPaths($,h,A){let G=this.generateNamePatterns($,A),J=[];for(let H of G)for(let E of this.extensions)J.push(PJ(h,`${H}${E}`));return J}generateNamePatterns($,h){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(h){if(A.push(h,`.${h}.config`,`${h}.config`,`.${h}`),$)A.push(`${$}.${h}.config`,`.${$}.${h}.config`)}return A.filter(Boolean)}checkFileAccess($){return y5(async()=>{return dA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,h,A){let G=[];if(!dA($))return G;if(h||A){let J=this.generateNamePatterns(h||"",A);for(let H of J)for(let E of this.extensions){let Y=PJ($,`${H}${E}`);if(await this.checkFileAccess(Y))G.push(Y)}}else try{let{readdirSync:J}=await import("fs"),H=J($);for(let E of H)if(this.looksLikeConfigFile(E)){let Y=PJ($,E);if(await this.checkFileAccess(Y))G.push(Y)}}catch{return[]}return G}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((A)=>A.test($))}async validateConfigFile($){let h=[];try{if(!dA($))return h.push("Configuration file does not exist"),h;let A=await import($),G=A.default||A;if(G===void 0)h.push("Configuration file must export a default value or named exports");else if(typeof G!=="object"||G===null)h.push("Configuration must be an object");else if(Array.isArray(G))h.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),H=J($,"utf8");JSON.parse(H)}catch(J){h.push(`Invalid JSON syntax: ${J}`)}}catch(A){h.push(`Failed to load configuration file: ${A}`)}return h}async getFileModificationTime($){try{let{statSync:h}=await import("fs");return h($).mtime}catch{return null}}async preloadConfigurations($,h={}){let A=new Map;return await Promise.allSettled($.map(async(G)=>{try{let J=await this.loadFromPath(G,{},h);if(J)A.set(G,J.config)}catch(J){if(h.verbose)console.warn(`Failed to preload ${G}:`,J)}})),A}}class JH{async validateConfiguration($,h,A={}){let{stopOnFirstError:G=!1,validateRequired:J=!0,validateTypes:H=!0,customRules:E=[],trackPerformance:Y=!0,verbose:U=!1}=A,z=async()=>{let W=[],Z=[],F={stopOnFirstError:G,validateRequired:J,validateTypes:H,customRules:E,trackPerformance:Y,verbose:U};try{if(typeof h==="string")return await this.validateWithSchemaFile($,h,F);else if(Array.isArray(h))return this.validateWithRules($,[...h,...E],F);else return this.validateWithJSONSchema($,h,F)}catch(w){return W.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:W,warnings:Z}}};if(Y)return await ph.track("validateConfiguration",z);return z()}async validateWithSchemaFile($,h,A){try{if(!uz(h))throw new dh(h,[{path:"",message:"Schema file does not exist"}]);let G=await import(h),J=G.default||G;if(Array.isArray(J))return this.validateWithRules($,J,A);else return this.validateWithJSONSchema($,J,A)}catch(G){throw new dh(h,[{path:"",message:`Failed to load schema: ${G}`}])}}validateWithJSONSchema($,h,A){let G=[],J=[];return this.validateObjectAgainstSchema($,h,"",G,J,A),{isValid:G.length===0,errors:G,warnings:J}}validateObjectAgainstSchema($,h,A,G,J,H){if(H.validateTypes&&h.type){let E=Array.isArray($)?"array":typeof $,Y=Array.isArray(h.type)?h.type:[h.type];if(!Y.includes(E)){if(G.push({path:A,message:`Expected type ${Y.join(" or ")}, got ${E}`,expected:Y.join(" or "),actual:E,rule:"type"}),H.stopOnFirstError)return}}if(h.enum&&!h.enum.includes($)){if(G.push({path:A,message:`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:$,rule:"enum"}),H.stopOnFirstError)return}if(typeof $==="string"){if(h.minLength!==void 0&&$.length<h.minLength)G.push({path:A,message:`String length must be at least ${h.minLength}`,expected:`>= ${h.minLength}`,actual:$.length,rule:"minLength"});if(h.maxLength!==void 0&&$.length>h.maxLength)G.push({path:A,message:`String length must not exceed ${h.maxLength}`,expected:`<= ${h.maxLength}`,actual:$.length,rule:"maxLength"});if(h.pattern){if(!new RegExp(h.pattern).test($))G.push({path:A,message:`String does not match pattern ${h.pattern}`,expected:h.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(h.minimum!==void 0&&$<h.minimum)G.push({path:A,message:`Value must be at least ${h.minimum}`,expected:`>= ${h.minimum}`,actual:$,rule:"minimum"});if(h.maximum!==void 0&&$>h.maximum)G.push({path:A,message:`Value must not exceed ${h.maximum}`,expected:`<= ${h.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&h.items)for(let E=0;E<$.length;E++){let Y=A?`${A}[${E}]`:`[${E}]`;if(this.validateObjectAgainstSchema($[E],h.items,Y,G,J,H),H.stopOnFirstError&&G.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let E=$;if(H.validateRequired&&h.required){for(let Y of h.required)if(!(Y in E)){if(G.push({path:A?`${A}.${Y}`:Y,message:`Missing required property '${Y}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(h.properties){for(let[Y,U]of Object.entries(h.properties))if(Y in E){let z=A?`${A}.${Y}`:Y;if(this.validateObjectAgainstSchema(E[Y],U,z,G,J,H),H.stopOnFirstError&&G.length>0)return}}if(h.additionalProperties===!1){let Y=new Set(Object.keys(h.properties||{}));for(let U of Object.keys(E))if(!Y.has(U))J.push({path:A?`${A}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,h,A){let G=[],J=[];for(let H of h)try{let E=this.getValueByPath($,H.path),Y=this.validateWithRule(E,H,H.path);if(G.push(...Y),A.stopOnFirstError&&G.length>0)break}catch(E){G.push({path:H.path,message:`Rule validation failed: ${E}`,rule:"system"})}return{isValid:G.length===0,errors:G,warnings:J}}validateWithRule($,h,A){let G=[];if(h.required&&($===void 0||$===null))return G.push({path:A,message:h.message||`Property '${A}' is required`,expected:"required",rule:"required"}),G;if($===void 0||$===null)return G;if(h.type){let J=Array.isArray($)?"array":typeof $;if(J!==h.type)G.push({path:A,message:h.message||`Expected type ${h.type}, got ${J}`,expected:h.type,actual:J,rule:"type"})}if(h.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<h.min)G.push({path:A,message:h.message||`Value must be at least ${h.min}`,expected:`>= ${h.min}`,actual:J,rule:"min"})}if(h.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>h.max)G.push({path:A,message:h.message||`Value must not exceed ${h.max}`,expected:`<= ${h.max}`,actual:J,rule:"max"})}if(h.pattern&&typeof $==="string"){if(!h.pattern.test($))G.push({path:A,message:h.message||`Value does not match pattern ${h.pattern}`,expected:h.pattern.toString(),actual:$,rule:"pattern"})}if(h.enum&&!h.enum.includes($))G.push({path:A,message:h.message||`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:$,rule:"enum"});if(h.validator){let J=h.validator($);if(J)G.push({path:A,message:h.message||J,rule:"custom"})}return G}getValueByPath($,h){if(!h)return $;let A=h.split("."),G=$;for(let J of A)if(G&&typeof G==="object"&&J in G)G=G[J];else return;return G}generateRulesFromInterface($){let h=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let G of A){let[,J,H,E]=G;h.push({path:J,required:!H,type:this.mapTypeScriptType(E)})}return h}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:n5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class HH{fileLoader=new RG;envProcessor=new FG;validator=new JH;async loadConfig($){let h=Date.now(),{cache:A,performance:G,schema:J,validate:H,...E}=$;try{if(A?.enabled){let U=this.checkCache(E.name||"",E);if(U)return U}let Y;try{Y=await this.loadConfigurationStrategies(E,!0,A)}catch(U){let z=E.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(z)throw U;Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`No configuration file found for "${E.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let W=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),Z=!W&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),F=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(z&&(F||W))throw U;if(Z&&(!z||!F))Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(J||H)await this.validateConfiguration(Y.config,J,H,E.name);if(A?.enabled&&Y)this.cacheResult(E.name||"",Y,A,E);if(G?.enabled){let U={operation:"loadConfig",duration:Date.now()-h,configName:E.name,timestamp:new Date};if(G.onMetrics)G.onMetrics(U);if(G.slowThreshold&&U.duration>G.slowThreshold)S$.warn(`Slow configuration loading detected: ${U.duration}ms for ${E.name}`);Y.metrics=U}return Y}catch(Y){let U=Date.now()-h;throw S$.error(`Configuration loading failed after ${U}ms:`,[Y instanceof Error?Y:Error(String(Y))]),Y}}async loadConfigurationStrategies($,h=!1,A){let{name:G="",alias:J,cwd:H,configDir:E,defaultConfig:Y,checkEnv:U=!0,arrayStrategy:z="replace",verbose:W=!1}=$,Z=H||M1.cwd(),F=[],w=await this.loadLocalConfiguration(G,J,Z,E,Y,z,W,U,A);if(w)return F.push(...this.getLocalSearchPaths(G,J,Z,E)),this.finalizeResult(w,F,U,G,W);let B=await this.loadHomeConfiguration(G,J,Y,z,W,U);if(B)return F.push(...this.getHomeSearchPaths(G,J)),this.finalizeResult(B,F,U,G,W);let j=await this.loadPackageJsonConfiguration(G,J,Z,Y,z,W,U);if(j)return F.push(A$(Z,"package.json")),this.finalizeResult(j,F,U,G,W);if(F.push(...this.getAllSearchPaths(G,J,Z,E)),h)throw H1.configNotFound(G,F,J);return{...await this.applyEnvironmentVariables(G,Y,U,W),warnings:[`No configuration file found for "${G}"${J?` or alias "${J}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,h,A,G,J,H,E,Y,U){let z=Y?bh($,J,E):J,W=this.getLocalDirectories(A,G);for(let Z of W){if(E)S$.info(`Searching for configuration in: ${Z}`);let F=this.fileLoader.generateConfigPaths($,Z,h),w=await this.fileLoader.tryLoadFromPaths(F,z,{arrayStrategy:H,verbose:E,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(w){if(E)S$.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration($,h,A,G,J,H){if(!$)return null;let E=H?bh($,A,J):A,Y=[A$(b1(),".config",$),A$(b1(),".config"),b1()];for(let U of Y){if(J)S$.info(`Checking home directory: ${U}`);let z=this.fileLoader.generateConfigPaths($,U,h),W=await this.fileLoader.tryLoadFromPaths(z,E,{arrayStrategy:G,verbose:J});if(W){if(J)S$.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,h,A,G,J,H,E){let Y=E?bh($,G,H):G;try{let U=A$(A,"package.json");if(!cJ(U))return null;let z=await import(U),W=z[$],Z=$;if(!W&&h)W=z[h],Z=h;if(W&&typeof W==="object"&&!Array.isArray(W)){if(H)S$.success(`Configuration loaded from package.json: ${Z}`);return{config:GH(Y,W,J),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(H)S$.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,h,A,G){if(!A||!$||typeof h!=="object"||h===null||Array.isArray(h))return{config:h,source:{type:"default",priority:10,timestamp:new Date}};return{config:bh($,h,G),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,h,A,G,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,h,A,G){let J=[];if(A){let H=A($);if(H)J.push(...H)}if(h){let H=await this.validator.validateConfiguration($,h);if(!H.isValid)J.push(...H.errors.map((E)=>E.path?`${E.path}: ${E.message}`:E.message))}if(J.length>0)throw H1.configValidation(G||"unknown",J,G)}checkCache($,h){let A=this.generateCacheKey($,h);return l1.get(A)||null}cacheResult($,h,A,G){let J=this.generateCacheKey($,G);l1.set(J,h,void 0,A.ttl)}generateCacheKey($,h){let A=[$];if(h.alias)A.push(`alias:${h.alias}`);if(h.cwd)A.push(`cwd:${h.cwd}`);if(h.configDir)A.push(`configDir:${h.configDir}`);if("checkEnv"in h)A.push(`checkEnv:${h.checkEnv}`);return A.join("|")}getLocalDirectories($,h){return Array.from(new Set([$,A$($,"config"),A$($,".config"),h?A$($,h):void 0].filter(Boolean)))}getAllSearchPaths($,h,A,G){let J=[];return J.push(...this.getLocalSearchPaths($,h,A,G)),J.push(...this.getHomeSearchPaths($,h)),J.push(A$(A,"package.json")),J}getLocalSearchPaths($,h,A,G){let J=this.getLocalDirectories(A,G),H=[];for(let E of J)H.push(...this.fileLoader.generateConfigPaths($,E,h));return H}getHomeSearchPaths($,h){if(!$)return[];let A=[A$(b1(),".config",$),A$(b1(),".config"),b1()],G=[];for(let J of A)G.push(...this.fileLoader.generateConfigPaths($,J,h));return G}async loadConfigWithResult($){return this.loadConfig($)}}function W5($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),G=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||G}async function T2($){return d$.loadConfig({...$,__strictErrorHandling:!0})}async function v5($){let h="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let G;if(A)G=await d$.loadConfig($);else G=await d$.loadConfig({...$,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}});return G?.config??h}catch(G){let J=G instanceof Error?G.name:"UnknownError",H=G instanceof Error?G.message:String(G);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||H.includes("config"))&&$.verbose)S$.warn("Unexpected error loading config, using defaults:",[G instanceof Error?G:Error(String(G))]);let Y=A?{...$,defaultConfig:h}:{...$,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await d$.applyEnvironmentVariables(Y.name||"",h,!0,Y.verbose||!1))?.config??h;return h}}async function k2($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:h}=await import("process");try{return(await d$.loadConfig({name:$,cwd:h(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&W5(A)))return(await d$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await d$.loadConfig({...$,cwd:$.cwd||M1.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(h){if(h instanceof Error&&(h.name==="ConfigNotFoundError"||h.name==="ConfigLoadError"&&W5(h)))return(await d$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw h}}async function y2($,h,A="replace"){let G=new RG;try{let J=await G.loadFromPath($,h,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function bh($,h,A=!1){let G=new FG,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(E,Y=[]){let U={...E};for(let[z,W]of Object.entries(E)){let Z=[...Y,z],F=[`${J}_${Z.join("_").toUpperCase()}`,`${J}_${Z.map((j)=>j.toUpperCase()).join("")}`,`${J}_${Z.map((j)=>j.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,B;for(let j of F)if(w=M1.env[j],w!==void 0){B=j;break}if(w!==void 0&&B)if(typeof W==="boolean")U[z]=["true","1","yes"].includes(w.toLowerCase());else if(typeof W==="number"){let j=Number(w);if(!Number.isNaN(j))U[z]=j}else if(Array.isArray(W))try{U[z]=JSON.parse(w)}catch{U[z]=w.split(",").map((j)=>j.trim())}else U[z]=w;else if(W&&typeof W==="object"&&!Array.isArray(W))U[z]=H(W,Z)}return U}return H(h)}function q2($){let h=A$(M1.cwd(),$.configDir),A=A$(M1.cwd(),$.generatedDir),G=A$(A,"config-types.ts");if(!cJ(mE(G)))Mz(mE(G),{recursive:!0,mode:511});let J=cJ(h)?Sz(h).map((E)=>E.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${zW}
|
|
36
|
-
export type ConfigNames = ${J.length?`'${J.join("' | '")}'`:"string"}
|
|
37
|
-
`;Qz(G,H,{mode:438})}function x2($){let h=null,A=null,G=()=>{if(!A)A=v5($).then((H)=>{return h=H,H},(H)=>{let E="defaultConfig"in $?$.defaultConfig:{};if(h=E,"verbose"in $&&$.verbose)S$.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return E});return A},J="defaultConfig"in $?$.defaultConfig:{};return h=J,G(),new Proxy({},{get(H,E){if(h)return h[E];let Y=J[E];return G(),Y},has(H,E){return E in(h||J)},ownKeys(){return Object.keys(h||J)},getOwnPropertyDescriptor(H,E){return Object.getOwnPropertyDescriptor(h||J,E)},set(H,E,Y){if(!h)h={...J};return h[E]=Y,!0}})}function f2($){let h=A5(rz.cwd(),$?.configDir||"./config");function A(){if(!iz(h))return[];let J=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],E=sz(h).filter((U)=>J.has(NJ(U))).map((U)=>({base:U.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:U})),Y=new Map;for(let{base:U,file:z}of E){let W=NJ(z).toLowerCase(),Z=Y.get(U);if(!Z){Y.set(U,z);continue}let F=NJ(Z).toLowerCase();if(H.indexOf(W)<H.indexOf(F))Y.set(U,z)}return Array.from(Y.entries()).map(([U,z])=>({base:U,file:z})).sort((U,z)=>U.base.localeCompare(z.base))}function G(){let J=A(),H=J.map((z)=>z.base),E=H.length?H.map((z)=>`'${z}'`).join(" | "):"string",Y=J.length?`{
|
|
38
|
-
${J.map((z)=>{let W=A5(h,z.file).replace(/\\/g,"/");return` '${z.base}': typeof import('${W}').default`}).join(`,
|
|
39
|
-
`)}
|
|
40
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${E}
|
|
41
|
-
export type ConfigByName = ${Y}
|
|
42
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
43
|
-
export type ConfigOf = Config
|
|
44
|
-
`}return{name:"bunfig-plugin",setup(J){J.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),J.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:G(),loader:"ts"}})}}}function ZW($,h={}){let A=JG.cwd();while(A.includes("storage"))A=G5(A,"..");let G=G5(A,$||"");if(h?.relative)return oz(JG.cwd(),G);return G}function c0(){if(m$.env.NODE_ENV==="test"||m$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jW(){if(m$.env.NODE_ENV==="test"||m$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof m$<"u"){let $=m$.type;if($==="renderer"||$==="worker")return!1;return!!(m$.versions&&(m$.versions.node||m$.versions.bun))}return!1}class r5{async format($){let h=await jW(),A=await this.getMetadata(h);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:h}=await import("os");return{pid:r1.pid,hostname:h(),environment:r1.env.NODE_ENV||"development",platform:r1.platform,version:r1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:r1.env.NODE_ENV||r1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wG{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($,h={}){this.name=$,this.config={...ZG},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new r5,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??F0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let A={...h},G=h.timestamp!==void 0;if(G)delete A.timestamp;if(this.config={...this.config,...A,timestamp:G||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),H=this.generateKey();this.currentKeyId=J,this.keys.set(J,H),this.encryptionKeys.set(J,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return h[$]>=h[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...vJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...vJ};return{...vJ,...$.fingersCrossed}}normalizeOptions($){let h={format:"json",level:"info",logDirectory:ZG.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...h,...Object.fromEntries(Object.entries($).filter(([,G])=>G!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=h.level;return A}shouldWriteToFile(){return!c0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let J,H=0,E=3,Y=1000;while(H<E)try{try{try{await h2(this.config.logDirectory,U5.F_OK|U5.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await A2(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 U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:v$.from($);try{if(!pA(this.currentLogFile))await yJ(this.currentLogFile,"",{mode:420});if(J=E5(this.currentLogFile,"a",420),$2(J,U,{flag:"a"}),H5(J),J!==void 0)kJ(J),J=void 0;if((await i1(this.currentLogFile)).size===0){if(await yJ(this.currentLogFile,U,{flag:"w",mode:420}),(await i1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let W=z;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(H<E-1){let Z=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${E}:`,Z);let F=Y*2**H;await new Promise((w)=>setTimeout(w,F)),H++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{kJ(J)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(U){if(H===E-1){let W=U,Z=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",Z),U}H++;let z=Y*2**(H-1);await new Promise((W)=>setTimeout(W,z))}})();this.pendingOperations.push(A);let G=this.pendingOperations.length-1;try{await A}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(G,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 s1(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 s1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return s1(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,h;switch($.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let h=this.config.rotation.keyRotation;if(!h?.enabled)return;let A=typeof h.interval==="number"?h.interval:60,G=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},G)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let h=this.config.rotation.keyRotation,A=this.generateKeyId(),G=this.generateKey();this.currentKeyId=A,this.keys.set(A,G),this.encryptionKeys.set(A,{key:G,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,U])=>U.createdAt.getTime()-Y.createdAt.getTime()),H=typeof h.maxKeys==="number"?h.maxKeys:1,E=Math.max(1,H);if(J.length>E)for(let[Y]of J.slice(E))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return TJ(16).toString("hex")}generateKey(){return TJ(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:h}=this.getCurrentKey(),A=TJ(16),G=tz("aes-256-gcm",h,A),J=v$.isBuffer($)?$:v$.from($,"utf8"),H=G.update(J),E=G.final(),Y=H.length+E.length,U=G.getAuthTag(),z=v$.allocUnsafe(16+Y+16);return A.copy(z,0),H.copy(z,16),E.copy(z,16+H.length),U.copy(z,16+Y),{encrypted:z,iv:A}}async compressData($){return new Promise((h,A)=>{let G=z5(),J=[];G.on("data",(H)=>J.push(H)),G.on("end",()=>h(v$.from(v$.concat(J)))),G.on("error",A),G.write($),G.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 h=this.config.rotation.encrypt;return{...$,...h}}return $}async rotateLog(){if(c0())return;if(!this.shouldWriteToFile())return;let $=await i1(this.currentLogFile).catch(()=>null);if(!$)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&$.size>=h.maxSize){let A=this.currentLogFile,G=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await nA(this.config.logDirectory),H=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let W=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),E=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Y=`${A}.${E}`;if(await i1(A).catch(()=>null))try{if(await Y5(A,Y),h.compress)try{let U=`${Y}.gz`;await this.compressLogFile(Y,U),await uA(Y)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${A}.1`;await yJ(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),H=A.replace(/\.log$/,`-${J}.log`);if(await i1(A).catch(()=>null))await Y5(A,H)}if(this.currentLogFile=G,h.maxFiles){let H=(await nA(this.config.logDirectory)).filter((E)=>E.startsWith(this.name)).sort((E,Y)=>Y.localeCompare(E));for(let E of H.slice(h.maxFiles))await uA(s1(this.config.logDirectory,E))}}}async compressLogFile($,h){let A=J5($),G=ez(h),J=z5();await H2(A,J,G)}async handleFingersCrossedBuffer($,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let G=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(G);console.log(G)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog($){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[$]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),pA(this.currentLogFile))try{let $=E5(this.currentLogFile,"r+");H5($),kJ($)}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 h=(await nA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of h)try{await uA(s1(this.config.logDirectory,A))}catch(G){console.error(`Failed to delete temp file ${A}:`,G)}}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 F0.env.NO_COLOR<"u",h=F0.env.FORCE_COLOR==="0";if($||h)return!1;return!!(typeof F0.stderr<"u"&&F0.stderr.isTTY||typeof F0.stdout<"u"&&F0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:h,icon:A="",tag:G="",message:J,level:H,showTimestamp:E=!0}=$,Y=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(E)w.push(h);if(H==="warning")w.push("WARN");else if(H==="error")w.push("ERROR");else if(A)w.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(G)w.push(G.replace(/[[\]]/g,""));return w.push(J),w.join(" ")}let U=F0.stdout.columns||120,z="";if(H==="warning"||H==="error")z=`${A} ${J}`;else if(H==="info"||H==="success")z=`${A} ${G} ${J}`;else z=`${A} ${G} ${_0.cyan(J)}`;if(!E)return z.trim();let W=Y(z).trim().length,Z=Y(h).length,F=Math.max(1,U-2-W-Z);return`${z.trim()}${" ".repeat(F)}${h}`}formatMessage($,h){if(h.length===1&&Array.isArray(h[0]))return $.replace(/\{(\d+)\}/g,(H,E)=>{let Y=Number.parseInt(E,10);return Y<h[0].length?String(h[0][Y]):H});let A=/%([sdijfo%])/g,G=0,J=$.replace(A,(H,E)=>{if(E==="%")return"%";if(G>=h.length)return H;let Y=h[G++];switch(E){case"s":return String(Y);case"d":case"i":return Number(Y).toString();case"j":case"o":return JSON.stringify(Y,null,2);default:return H}});if(G<h.length)J+=` ${h.slice(G).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let h=$;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,G,J)=>{let H=_0.underline(_0.blue(G)),E=this.toAbsoluteFilePath(J);if(E&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Y=`file://${encodeURI(E)}`,U="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${Y}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),h=h.replace(/`([^`]+)`/g,(A,G)=>_0.bgGray(G)),h=h.replace(/\*\*([^*]+)\*\*/g,(A,G)=>_0.bold(G)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,G)=>_0.italic(G)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,G)=>_0.italic(G)),h=h.replace(/~([^~]+)~/g,(A,G)=>_0.strikethrough(G)),h}supportsHyperlinks(){if(c0())return!1;let $=F0.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 h=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath($){try{let h=$;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let A=F0.env.HOME||"";if(A)h=h.replace(/^~(?=$|\/)/,A)}if(G2(h)||h.startsWith("./")||h.startsWith("../"))h=J2(h);else return null;return pA(h)?h:null}catch{return null}}buildOutputTexts($){let h=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:A}}async log($,h,...A){if(!this.shouldLog($))return;let G=new Date,J=this.formatConsoleTimestamp(G),H=this.formatFileTimestamp(G),E,Y;if(h instanceof Error)E=h.message,Y=h.stack;else E=this.formatMessage(h,A);let{consoleText:U,fileText:z}=this.buildOutputTexts(E);if(this.shouldStyleConsole()){let Z=this.options.showIcons===!1?"":_W[$],F=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"",w;switch($){case"debug":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:_0.gray(U),level:$}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:_0.green(U),level:$}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.error(w),Y){let B=Y.split(`
|
|
45
|
-
`);for(let j of B)if(j.trim()&&!j.includes(E))console.error(this.formatConsoleMessage({timestamp:J,message:_0.gray(` ${j}`),level:$,showTimestamp:!1}))}break}}else if(!c0()){if(console.error(`${H} ${this.environment}.${$.toUpperCase()}: ${E}`),Y)console.error(Y)}let W=`${H} ${this.environment}.${$.toUpperCase()}: ${z}
|
|
46
|
-
`;if(Y)W+=`${Y}
|
|
47
|
-
`;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,h=""){let A={update:(Y,U)=>{},finish:(Y)=>{},interrupt:(Y,U)=>{}};if(!this.enabled)return A;let G=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:h||"",barLength:G,lastRenderedLine:""},this.shouldStyleConsole()&&!c0()&&F0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Y,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Y),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!c0()&&F0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Y)},interrupt:(Y,U="info")=>{if(!c0()&&F0.stdout.isTTY)F0.stdout.write(`
|
|
48
|
-
`);if(this[U==="warning"?"warn":U](Y),this.activeProgressBar&&this.shouldStyleConsole()&&!c0()&&F0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let h=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"",G=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":_0.blue("\u25D0"),tag:A,message:`${_0.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let G=performance.now(),J=Math.round(G-h),H=`${$} completed in ${J}ms`,E=new Date,Y=this.formatConsoleTimestamp(E),z=`${this.formatFileTimestamp(E)} ${this.environment}.INFO: ${H}`;if(A)z+=` ${JSON.stringify(A)}`;if(z+=`
|
|
49
|
-
`,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":_0.green("\u2713"),tag:W,message:`${H}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!c0())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug($,...h){await this.log("debug",$,...h)}async info($,...h){await this.log("info",$,...h)}async success($,...h){await this.log("success",$,...h)}async warn($,...h){await this.log("warning",$,...h)}async error($,...h){await this.log("error",$,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:h}=$;return!!h}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let h=`${this.name}:${$}`,A=new wG(h,{...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(A),A}createReadStream(){if(c0())throw Error("createReadStream is not supported in browser environments");if(!pA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return J5(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let G=v$.isBuffer($)?$:v$.from($,"base64"),J=G.subarray(0,16),H=G.subarray(G.length-16),E=G.subarray(16,G.length-16),Y=az("aes-256-gcm",A,J);Y.setAuthTag(H);let U=Y.update(E),z=Y.final(),W=U.length+z.length,Z=v$.allocUnsafe(W);return U.copy(Z,0),z.copy(Z,U.length),Z.toString("utf8")}catch(G){throw Error(`Decryption failed: ${G instanceof Error?G.message:String(G)}`)}}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($,h){this.currentKeyId=$,this.keys.set($,h)}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 h=new Date,A=this.formatConsoleTimestamp(h),G=this.formatFileTimestamp(h),{consoleText:J,fileText:H}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Y=J.split(`
|
|
50
|
-
`),U=Math.max(...Y.map((F)=>F.length))+2,z=`\u250C${"\u2500".repeat(U)}\u2510`,W=`\u2514${"\u2500".repeat(U)}\u2518`,Z=Y.map((F)=>{return this.formatConsoleMessage({timestamp:A,message:_0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:_0.cyan(z),showTimestamp:!1})),Z.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:A,message:_0.cyan(W),showTimestamp:!1}))}else if(!c0())console.error(`${G} ${this.environment}.INFO: [BOX] ${H}`);let E=`${G} ${this.environment}.INFO: [BOX] ${H}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(E)}async prompt($){if(c0())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${_0.cyan("?")} ${$} (y/n) `);let A=(G)=>{let J=G.toString().trim().toLowerCase();F0.stdin.removeListener("data",A);try{if(typeof F0.stdin.setRawMode==="function")F0.stdin.setRawMode(!1)}catch{}F0.stdin.pause(),console.error(""),h(J==="y"||J==="yes")};try{if(typeof F0.stdin.setRawMode==="function")F0.stdin.setRawMode(!0)}catch{}F0.stdin.resume(),F0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...h){if(!this.enabled)return;let A=$;if(h&&h.length>0){let U=/%([sdijfo%])/g,z=0;if(A=$.replace(U,(W,Z)=>{if(Z==="%")return"%";if(z>=h.length)return W;let F=h[z++];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 W}}),z<h.length)A+=` ${h.slice(z).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:G,fileText:J}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?_0.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${_0.blue("\u25D0")} `;console.error(`${z}${U} ${_0.cyan(G)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
|
|
52
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,h=!1){if(!this.enabled||!this.shouldStyleConsole()||!F0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),G=Math.round($.barLength*A/100),J=$.barLength-G,H=_0.green("\u2501".repeat(G)),E=_0.gray("\u2501".repeat(J)),Y=`[${H}${E}]`,U=`${A}%`.padStart(4),z=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":h||A===100?_0.green("\u2713"):_0.blue("\u25B6"),Z=this.options.showTags!==!1&&this.name?` ${_0.gray(this.formatTag(this.name))}`:"",F=`\r${W}${Z} ${Y} ${U}${z}`,w=F0.stdout.columns||80,B=" ".repeat(Math.max(0,w-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${B}`,F0.stdout.write($.lastRenderedLine),h)F0.stdout.write(`
|
|
53
|
-
`)}finishProgressBar($,h){if(!this.enabled||!this.fancy||c0()||!F0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(h)$.message=h;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 h=await nA(this.config.logDirectory),A=[];for(let G of h){if(!($.name?new RegExp($.name.replace("*",".*")).test(G):G.startsWith(this.name))||!G.endsWith(".log"))continue;let H=s1(this.config.logDirectory,G);if($.before)try{if((await i1(H)).mtime>=$.before)continue}catch(E){console.error(`Failed to get stats for file ${H}:`,E);continue}A.push(H)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let G of A)try{await uA(G),console.warn(`Deleted log file: ${G}`)}catch(J){console.error(`Failed to delete log file ${G}:`,J)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}async function OW($,h={}){let{maxRetries:A=3,retryDelay:G=1000,isRetryable:J=()=>!0,fallback:H}=h,E=Error("Unknown error occurred");for(let Y=0;Y<=A;Y++)try{return await $()}catch(U){if(E=U instanceof Error?U:Error(String(U)),Y===A||!J(E))break;if(G>0)await new Promise((z)=>setTimeout(z,G))}if(H!==void 0)return H;throw E instanceof Error?E:Error(`Unknown error: ${String(E)}`)}class UH{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,h)=>h==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let h=$.toLowerCase();return["true","1","yes"].includes(h)}},{name:"number",canParse:($,h)=>h==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let h=Number($);if(Number.isNaN(h))throw TypeError(`Cannot parse "${$}" as number`);return h}},{name:"array",canParse:($,h)=>h==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let h=JSON.parse($);if(Array.isArray(h))return h}catch{}return $.split(",").map((h)=>h.trim())}},{name:"json",canParse:($,h)=>h==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(h){throw Error(`Cannot parse "${$}" as JSON: ${h}`)}}}]}async applyEnvironmentVariables($,h,A={}){let{prefix:G,useCamelCase:J=!0,useBackwardCompatibility:H=!0,customParsers:E={},verbose:Y=!1,trackPerformance:U=!0}=A,z=async()=>{if(!$)return{config:h,source:{type:"environment",priority:50,timestamp:new Date}};let W=G||this.generateEnvPrefix($),Z={...h};return this.processObject(Z,[],W,{useCamelCase:J,useBackwardCompatibility:H,customParsers:E,verbose:Y,configName:$}),{config:Z,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return aJ.track("applyEnvironmentVariables",z,{configName:$});return z()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,h){if(!h)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,h,A,G){for(let[J,H]of Object.entries($)){let E=[...h,J],Y=E.map((W)=>this.formatEnvKey(W,G.useCamelCase)),U=`${A}_${Y.join("_")}`,z=G.useBackwardCompatibility?`${A}_${E.map((W)=>W.toUpperCase()).join("_")}`:null;if(G.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,E,A,G);else{let W=sA.env[U]||(z?sA.env[z]:void 0);if(W!==void 0){if(G.verbose){let Z=sA.env[U]?U:z}try{$[J]=this.parseEnvironmentValue(W,typeof H,U,G.customParsers,G.configName)}catch(Z){if(Z instanceof EH)throw Z;throw V1.envVar(U,W,typeof H,G.configName)}}}}}parseEnvironmentValue($,h,A,G,J){for(let[H,E]of Object.entries(G))try{return E($)}catch{continue}for(let H of this.defaultParsers)if(H.canParse($,h))try{return H.parse($)}catch{throw V1.envVar(A,$,`${h} (via ${H.name} parser)`,J)}return $}getEnvironmentVariables($){let h={},A=$.toUpperCase();for(let[G,J]of Object.entries(sA.env))if(G.startsWith(A)&&J!==void 0)h[G]=J;return h}validateEnvironmentVariable($,h,A){let G=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))G.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,h,A,{})}catch(J){G.push(`Cannot parse value "${h}" as ${A}: ${J}`)}return{isValid:G.length===0,errors:G}}generateEnvVarDocs($,h,A={}){let{prefix:G,format:J="text"}=A,H=G||this.generateEnvPrefix($),E=[];switch(this.extractEnvVarInfo(h,[],H,E),J){case"markdown":return this.formatAsMarkdown(E,$);case"json":return JSON.stringify(E,null,2);default:return this.formatAsText(E,$)}}extractEnvVarInfo($,h,A,G){for(let[J,H]of Object.entries($)){let E=[...h,J],Y=`${A}_${E.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,E,A,G);else G.push({key:Y,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${E.join(".")}`,example:this.generateExample(H)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,h){let A=`Environment Variables for ${h}:
|
|
54
|
-
|
|
55
|
-
`;for(let G of $)A+=`${G.key}
|
|
56
|
-
`,A+=` Type: ${G.type}
|
|
57
|
-
`,A+=` Description: ${G.description}
|
|
58
|
-
`,A+=` Example: ${G.example}
|
|
59
|
-
|
|
60
|
-
`;return A}formatAsMarkdown($,h){let A=`# Environment Variables for ${h}
|
|
61
|
-
|
|
62
|
-
`;A+=`| Variable | Type | Description | Example |
|
|
63
|
-
`,A+=`|----------|------|-------------|----------|
|
|
64
|
-
`;for(let G of $)A+=`| \`${G.key}\` | ${G.type} | ${G.description} | \`${G.example}\` |
|
|
65
|
-
`;return A}}function DW($,h,A={}){return A9($,h,A,new WeakMap)}function A9($,h,A,G){let{arrayMergeMode:J="replace",skipNullish:H=!1,customMerger:E}=A;if(h===null||h===void 0)return H?$:h;if(E){let Y=E($,h);if(Y!==void 0)return Y}if(Array.isArray(h)||Array.isArray($))return G9($,h,J,G);if(!w$(h)||!w$($))return h;return QW($,h,A,G)}function G9($,h,A,G){if(Array.isArray(h)&&!Array.isArray($))return h;if(Array.isArray($)&&!Array.isArray(h))return h;if(Array.isArray(h)&&Array.isArray($))switch(A){case"replace":return h;case"concat":return VW($,h);case"smart":return MW($,h,G);default:return h}return h}function VW($,h){let A=[...h];for(let G of $)if(!A.some((J)=>tJ(J,G)))A.push(G);return A}function MW($,h,A){if(h.length===0)return $;if($.length===0)return h;if(w$(h[0])&&w$($[0]))return SW($,h,A);if(h.every((G)=>typeof G==="string")&&$.every((G)=>typeof G==="string")){let G=[...h];for(let J of $)if(!G.includes(J))G.push(J);return G}return h}function SW($,h,A){let G=[...h];for(let J of $){if(!w$(J)){G.push(J);continue}let H=["id","name","key","path","type"],E=!1;for(let Y of H)if(Y in J){if(G.find((z)=>w$(z)&&(Y in z)&&z[Y]===J[Y])){E=!0;break}}if(!E)G.push(J)}return G}function QW($,h,A,G){let J=h;if(w$(J)&&G.has(J))return G.get(J);let H={...$};if(w$(J))G.set(J,H);for(let E in J){if(!Object.prototype.hasOwnProperty.call(J,E))continue;let Y=J[E],U=H[E];if(A.skipNullish&&(Y===null||Y===void 0))continue;if(Y===null||Y===void 0){H[E]=Y;continue}if(w$(Y)&&w$(U))H[E]=A9(U,Y,A,G);else if(Array.isArray(Y)||Array.isArray(U))H[E]=G9(U,Y,A.arrayMergeMode||"smart",G);else H[E]=Y}return H}function J9($,h,A="replace"){return DW($,h,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function tJ($,h){if($===h)return!0;if(Array.isArray($)&&Array.isArray(h)){if($.length!==h.length)return!1;for(let A=0;A<$.length;A++)if(!tJ($[A],h[A]))return!1;return!0}if(w$($)&&w$(h)){let A=Object.keys($),G=Object.keys(h);if(A.length!==G.length)return!1;for(let J of A){if(!Object.prototype.hasOwnProperty.call(h,J))return!1;if(!tJ($[J],h[J]))return!1}return!0}return!1}function w$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class H9{extensions=K5;async loadFromPath($,h,A={}){let{arrayStrategy:G="replace",useCache:J=!0,cacheTtl:H,trackPerformance:E=!0,verbose:Y=!1}=A;if(J){let z=$G.getWithFileCheck("file",$);if(z){if(Y)console.log(`Configuration loaded from cache: ${$}`);return z}}let U=async()=>{if(!rA($))return null;try{let z=`?t=${Date.now()}`,W=await import($+z),Z=W.default||W,F="default"in W,w=Object.keys(W).length>0;if(!F&&!w)throw new XG($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Z!=="object"||Z===null||Array.isArray(Z))throw new XG($,Error("Configuration must export a valid object"),"unknown");let O={config:J9(h,Z,G),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)$G.setWithFileCheck("file",O,$,H);return O}catch(z){throw z instanceof Error?V1.configLoad($,z):V1.configLoad($,Error(String(z)))}};if(E)return aJ.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,h,A={}){for(let G of $)try{let J=await this.loadFromPath(G,h,A);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(A.verbose)console.warn(`Failed to load config from ${G}:`,J)}return null}generateConfigPaths($,h,A){return _z({name:$,directory:h,alias:A})}generateNamePatterns($,h){return B5({name:$,alias:h})}checkFileAccess($){return OW(async()=>{return rA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,h,A){let G=[];if(!rA($))return G;if(h||A){let J=this.generateNamePatterns(h||"",A);for(let H of J)for(let E of this.extensions){let Y=S5($,`${H}${E}`);if(await this.checkFileAccess(Y))G.push(Y)}}else try{let{readdirSync:J}=await import("fs"),H=J($);for(let E of H)if(this.looksLikeConfigFile(E)){let Y=S5($,E);if(await this.checkFileAccess(Y))G.push(Y)}}catch{return[]}return G}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((A)=>A.test($))}async validateConfigFile($){let h=[];try{if(!rA($))return h.push("Configuration file does not exist"),h;let A=await import($),G=A.default||A;if(G===void 0)h.push("Configuration file must export a default value or named exports");else if(typeof G!=="object"||G===null)h.push("Configuration must be an object");else if(Array.isArray(G))h.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),H=J($,"utf8");JSON.parse(H)}catch(J){h.push(`Invalid JSON syntax: ${J}`)}}catch(A){h.push(`Failed to load configuration file: ${A}`)}return h}async getFileModificationTime($){try{let{statSync:h}=await import("fs");return h($).mtime}catch{return null}}async preloadConfigurations($,h={}){let A=new Map;return await Promise.allSettled($.map(async(G)=>{try{let J=await this.loadFromPath(G,{},h);if(J)A.set(G,J.config)}catch(J){if(h.verbose)console.warn(`Failed to preload ${G}:`,J)}})),A}}class E9{async validateConfiguration($,h,A={}){let{stopOnFirstError:G=!1,validateRequired:J=!0,validateTypes:H=!0,customRules:E=[],trackPerformance:Y=!0,verbose:U=!1}=A,z=async()=>{let W=[],Z=[],F={stopOnFirstError:G,validateRequired:J,validateTypes:H,customRules:E,trackPerformance:Y,verbose:U};try{if(typeof h==="string")return await this.validateWithSchemaFile($,h,F);else if(Array.isArray(h))return this.validateWithRules($,[...h,...E],F);else return this.validateWithJSONSchema($,h,F)}catch(w){return W.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:W,warnings:Z}}};if(Y)return await aJ.track("validateConfiguration",z);return z()}async validateWithSchemaFile($,h,A){try{if(!CW(h))throw new jG(h,[{path:"",message:"Schema file does not exist"}]);let G=await import(h),J=G.default||G;if(Array.isArray(J))return this.validateWithRules($,J,A);else return this.validateWithJSONSchema($,J,A)}catch(G){throw new jG(h,[{path:"",message:`Failed to load schema: ${G}`}])}}validateWithJSONSchema($,h,A){let G=[],J=[];return this.validateObjectAgainstSchema($,h,"",G,J,A),{isValid:G.length===0,errors:G,warnings:J}}validateObjectAgainstSchema($,h,A,G,J,H){if(H.validateTypes&&h.type){let E=Array.isArray($)?"array":typeof $,Y=Array.isArray(h.type)?h.type:[h.type];if(!Y.includes(E)){if(G.push({path:A,message:`Expected type ${Y.join(" or ")}, got ${E}`,expected:Y.join(" or "),actual:E,rule:"type"}),H.stopOnFirstError)return}}if(h.enum&&!h.enum.includes($)){if(G.push({path:A,message:`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:$,rule:"enum"}),H.stopOnFirstError)return}if(typeof $==="string"){if(h.minLength!==void 0&&$.length<h.minLength)G.push({path:A,message:`String length must be at least ${h.minLength}`,expected:`>= ${h.minLength}`,actual:$.length,rule:"minLength"});if(h.maxLength!==void 0&&$.length>h.maxLength)G.push({path:A,message:`String length must not exceed ${h.maxLength}`,expected:`<= ${h.maxLength}`,actual:$.length,rule:"maxLength"});if(h.pattern){if(!new RegExp(h.pattern).test($))G.push({path:A,message:`String does not match pattern ${h.pattern}`,expected:h.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(h.minimum!==void 0&&$<h.minimum)G.push({path:A,message:`Value must be at least ${h.minimum}`,expected:`>= ${h.minimum}`,actual:$,rule:"minimum"});if(h.maximum!==void 0&&$>h.maximum)G.push({path:A,message:`Value must not exceed ${h.maximum}`,expected:`<= ${h.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&h.items)for(let E=0;E<$.length;E++){let Y=A?`${A}[${E}]`:`[${E}]`;if(this.validateObjectAgainstSchema($[E],h.items,Y,G,J,H),H.stopOnFirstError&&G.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let E=$;if(H.validateRequired&&h.required){for(let Y of h.required)if(!(Y in E)){if(G.push({path:A?`${A}.${Y}`:Y,message:`Missing required property '${Y}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(h.properties){for(let[Y,U]of Object.entries(h.properties))if(Y in E){let z=A?`${A}.${Y}`:Y;if(this.validateObjectAgainstSchema(E[Y],U,z,G,J,H),H.stopOnFirstError&&G.length>0)return}}if(h.additionalProperties===!1){let Y=new Set(Object.keys(h.properties||{}));for(let U of Object.keys(E))if(!Y.has(U))J.push({path:A?`${A}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,h,A){let G=[],J=[];for(let H of h)try{let E=this.getValueByPath($,H.path),Y=this.validateWithRule(E,H,H.path);if(G.push(...Y),A.stopOnFirstError&&G.length>0)break}catch(E){G.push({path:H.path,message:`Rule validation failed: ${E}`,rule:"system"})}return{isValid:G.length===0,errors:G,warnings:J}}validateWithRule($,h,A){let G=[];if(h.required&&($===void 0||$===null))return G.push({path:A,message:h.message||`Property '${A}' is required`,expected:"required",rule:"required"}),G;if($===void 0||$===null)return G;if(h.type){let J=Array.isArray($)?"array":typeof $;if(J!==h.type)G.push({path:A,message:h.message||`Expected type ${h.type}, got ${J}`,expected:h.type,actual:J,rule:"type"})}if(h.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<h.min)G.push({path:A,message:h.message||`Value must be at least ${h.min}`,expected:`>= ${h.min}`,actual:J,rule:"min"})}if(h.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>h.max)G.push({path:A,message:h.message||`Value must not exceed ${h.max}`,expected:`<= ${h.max}`,actual:J,rule:"max"})}if(h.pattern&&typeof $==="string"){if(!h.pattern.test($))G.push({path:A,message:h.message||`Value does not match pattern ${h.pattern}`,expected:h.pattern.toString(),actual:$,rule:"pattern"})}if(h.enum&&!h.enum.includes($))G.push({path:A,message:h.message||`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:$,rule:"enum"});if(h.validator){let J=h.validator($);if(J)G.push({path:A,message:h.message||J,rule:"custom"})}return G}getValueByPath($,h){if(!h)return $;let A=h.split("."),G=$;for(let J of A)if(G&&typeof G==="object"&&J in G)G=G[J];else return;return G}generateRulesFromInterface($){let h=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let G of A){let[,J,H,E]=G;h.push({path:J,required:!H,type:this.mapTypeScriptType(E)})}return h}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:KW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function BW($){if(!$)return"";let h=Array.isArray($)?$.filter(Boolean):[$];if(h.length===0)return"";if(h.length===1)return` or alias "${h[0]}"`;return` or aliases ${h.map((A)=>`"${A}"`).join(", ")}`}class U9{fileLoader=new H9;envProcessor=new UH;validator=new E9;async loadConfig($){let h=Date.now(),{cache:A,performance:G,schema:J,validate:H,...E}=$;try{if(A?.enabled){let U=this.checkCache(E.name||"",E);if(U)return U}let Y;try{Y=await this.loadConfigurationStrategies(E,!0,A)}catch(U){if(E.configFile)throw U;let z=E.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(z)throw U;Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`No configuration file found for "${E.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let W=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),Z=!W&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),F=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(z&&(F||W))throw U;if(Z&&(!z||!F))Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(J||H)await this.validateConfiguration(Y.config,J,H,E.name);if(A?.enabled&&Y)this.cacheResult(E.name||"",Y,A,E);if(G?.enabled){let U={operation:"loadConfig",duration:Date.now()-h,configName:E.name,timestamp:new Date};if(G.onMetrics)G.onMetrics(U);if(G.slowThreshold&&U.duration>G.slowThreshold)M$.warn(`Slow configuration loading detected: ${U.duration}ms for ${E.name}`);Y.metrics=U}return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigNotFoundError")throw Y;let U=Date.now()-h;throw M$.error(`Configuration loading failed after ${U}ms:`,[Y instanceof Error?Y:Error(String(Y))]),Y}}async loadConfigurationStrategies($,h=!1,A){let{name:G="",alias:J,configFile:H,cwd:E,configDir:Y,defaultConfig:U,checkEnv:z=!0,arrayStrategy:W="replace",verbose:Z=!1}=$,F=E||LG.cwd(),w=[];if(H){let R=k$(F,H);w.push(R);let S=z?gh(G,U,Z):U,D=await this.fileLoader.tryLoadFromPaths([R],S,{arrayStrategy:W,verbose:Z,cacheTtl:A?.ttl,useCache:!A?.ttl||A.ttl>100});if(!D)throw V1.configNotFound(G||H,w,J);if(Z)M$.success(`Configuration loaded from explicit path: ${R}`);return this.finalizeResult(D,w,z,G,Z)}let B=await this.loadLocalConfiguration(G,J,F,Y,U,W,Z,z,A);if(B)return w.push(...this.getLocalSearchPaths(G,J,F,Y)),this.finalizeResult(B,w,z,G,Z);let j=await this.loadHomeConfiguration(G,J,U,W,Z,z);if(j)return w.push(...this.getHomeSearchPaths(G,J)),this.finalizeResult(j,w,z,G,Z);let O=await this.loadPackageJsonConfiguration(G,J,F,U,W,Z,z);if(O)return w.push(k$(F,"package.json")),this.finalizeResult(O,w,z,G,Z);if(w.push(...this.getAllSearchPaths(G,J,F,Y)),h)throw V1.configNotFound(G,w,J);return{...await this.applyEnvironmentVariables(G,U,z,Z),warnings:[`No configuration file found for "${G}"${BW(J)}, using defaults with environment variables`]}}async loadLocalConfiguration($,h,A,G,J,H,E,Y,U){let z=Y?gh($,J,E):J,W=this.getLocalDirectories(A,G);for(let Z of W){if(E)M$.info(`Searching for configuration in: ${Z}`);let F=this.fileLoader.generateConfigPaths($,Z,h),w=await this.fileLoader.tryLoadFromPaths(F,z,{arrayStrategy:H,verbose:E,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(w){if(E)M$.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration($,h,A,G,J,H){if(!$)return null;let E=H?gh($,A,J):A,Y=[k$(v1(),".config",$),k$(v1(),".config"),v1()];for(let U of Y){if(J)M$.info(`Checking home directory: ${U}`);let z=this.fileLoader.generateConfigPaths($,U,h),W=await this.fileLoader.tryLoadFromPaths(z,E,{arrayStrategy:G,verbose:J});if(W){if(J)M$.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,h,A,G,J,H,E){let Y=E?gh($,G,H):G;try{let U=k$(A,"package.json");if(!Dz(U))return null;let z={};try{z=JSON.parse(Vz(U,"utf8"))}catch(F){if(H)M$.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let W=z[$],Z=$;if(!W&&h){let F=Array.isArray(h)?h:[h];for(let w of F){if(!w)continue;if(z[w]){W=z[w],Z=w;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(H)M$.success(`Configuration loaded from package.json: ${Z}`);return{config:J9(Y,W,J),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(H)M$.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,h,A,G){if(!A||!$||typeof h!=="object"||h===null||Array.isArray(h))return{config:h,source:{type:"default",priority:10,timestamp:new Date}};return{config:gh($,h,G),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,h,A,G,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,h,A,G){let J=[];if(A){let H=A($);if(H)J.push(...H)}if(h){let H=await this.validator.validateConfiguration($,h);if(!H.isValid)J.push(...H.errors.map((E)=>E.path?`${E.path}: ${E.message}`:E.message))}if(J.length>0)throw V1.configValidation(G||"unknown",J,G)}checkCache($,h){let A=this.generateCacheKey($,h);return $G.get(A)||null}cacheResult($,h,A,G){let J=this.generateCacheKey($,G);$G.set(J,h,void 0,A.ttl)}generateCacheKey($,h){let A=[$];if(h.alias){let G=Array.isArray(h.alias)?h.alias.join(","):h.alias;A.push(`alias:${G}`)}if(h.cwd)A.push(`cwd:${h.cwd}`);if(h.configFile)A.push(`configFile:${h.configFile}`);if(h.configDir)A.push(`configDir:${h.configDir}`);if("checkEnv"in h)A.push(`checkEnv:${h.checkEnv}`);return A.join("|")}getLocalDirectories($,h){return Oz({cwd:$,configDir:h})}getAllSearchPaths($,h,A,G){let J=[];return J.push(...this.getLocalSearchPaths($,h,A,G)),J.push(...this.getHomeSearchPaths($,h)),J.push(k$(A,"package.json")),J}getLocalSearchPaths($,h,A,G){let J=this.getLocalDirectories(A,G),H=[];for(let E of J)H.push(...this.fileLoader.generateConfigPaths($,E,h));return H}getHomeSearchPaths($,h){if(!$)return[];let A=[k$(v1(),".config",$),k$(v1(),".config"),v1()],G=[];for(let J of A)G.push(...this.fileLoader.generateConfigPaths($,J,h));return G}async loadConfigWithResult($){return this.loadConfig($)}}async function Y9($){let h="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let G;if(A)G=await bJ.loadConfig($);else G=await bJ.loadConfig({...$,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}});return G?.config??h}catch(G){if($.configFile)throw G;let J=G instanceof Error?G.name:"UnknownError",H=G instanceof Error?G.message:String(G);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||H.includes("config"))&&$.verbose)M$.warn("Unexpected error loading config, using defaults:",[G instanceof Error?G:Error(String(G))]);let Y=A?{...$,defaultConfig:h}:{...$,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await bJ.applyEnvironmentVariables(Y.name||"",h,!0,Y.verbose||!1))?.config??h;return h}}function gh($,h,A=!1){let G=new UH,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(E,Y=[]){let U={...E};for(let[z,W]of Object.entries(E)){let Z=[...Y,z],F=[`${J}_${Z.join("_").toUpperCase()}`,`${J}_${Z.map((j)=>j.toUpperCase()).join("")}`,`${J}_${Z.map((j)=>j.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,B;for(let j of F)if(w=LG.env[j],w!==void 0){B=j;break}if(w!==void 0&&B)if(typeof W==="boolean")U[z]=["true","1","yes"].includes(w.toLowerCase());else if(typeof W==="number"){let j=Number(w);if(!Number.isNaN(j))U[z]=j}else if(Array.isArray(W))try{U[z]=JSON.parse(w)}catch{U[z]=w.split(",").map((j)=>j.trim())}else U[z]=w;else if(W&&typeof W==="object"&&!Array.isArray(W))U[z]=H(W,Z)}return U}return H(h)}var $G,aJ,K5,E2,U2=($)=>$,z2=($,h)=>{for(var A in h)E2($,A,{get:h[A],enumerable:!0,configurable:!0,set:Y2.bind(h,A)})},W2=($,h)=>()=>($&&(h=$($=0)),h),N5,b5,l1,ph,c5,g2,v2,Z5,oA,pJ,l0,I0,b2,X5,c2,j5,m2,d2,qJ,p2,L5,F5,xJ,n2,u2,i2,s2,tA,m5,r2,o0,l2,o2,R5,aA,nJ,b0,R0,t2,w5,a2,_5,e2,$W,fJ,hW,O5,D5,AW,gJ,GW,JW,HW,EW,UW,eA,d5,YW,zW="0.15.6",z$,zG,mh,uJ,iJ,WG,sJ,rJ,dh,lJ,oJ,H1,p5,n5,S$,d$,u5,i5,WW,XW,s5,ZG,cL,u0,_0,mL,LW,dL,FW,pL,nL,V5,uL,RW,wW,iL,M5,sL,rL,lL,oL,tL,vJ,_W,aL,Q$,l5,XG,o5,t5,EH,a5,e5,jG,$9,h9,V1,KW,M$,bJ,GF,JF;var z9=a(()=>{$G=new Q5,aJ=new C5,K5=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];E2=Object.defineProperty;N5={};z2(N5,{withErrorRecovery:()=>y5,tryLoadConfig:()=>y2,loadConfigWithResult:()=>T2,loadConfig:()=>v5,isRetryableError:()=>C2,isConfigNotFoundError:()=>Q2,isBunfigError:()=>q5,globalPerformanceMonitor:()=>ph,globalCache:()=>l1,getEnvOrDefault:()=>K2,generateConfigTypes:()=>q2,defaultGeneratedDir:()=>i5,defaultConfigDir:()=>u5,deepMergeWithArrayStrategy:()=>GH,deepMerge:()=>x5,createLibraryConfig:()=>x2,config:()=>k2,bunfigPlugin:()=>f2,applyEnvVarsToConfig:()=>bh,TypeGenerationError:()=>rJ,SchemaValidationError:()=>dh,PluginError:()=>oJ,PerformanceMonitor:()=>$H,FileSystemError:()=>sJ,ErrorFactory:()=>H1,EnvVarError:()=>WG,EnvProcessor:()=>FG,ConfigValidator:()=>JH,ConfigValidationError:()=>uJ,ConfigNotFoundError:()=>zG,ConfigMergeError:()=>iJ,ConfigLoader:()=>HH,ConfigLoadError:()=>mh,ConfigFileLoader:()=>RG,ConfigCache:()=>eJ,CacheUtils:()=>c5,BunfigError:()=>z$,BrowserConfigError:()=>lJ,ArrayMergeStrategies:()=>p5});WW=W2(async()=>{b5=import.meta.require,l1=new eJ,ph=new $H,c5={createKey:Z2,isEquivalent:X2,estimateMemoryUsage:j2},g2=GG(mJ.cwd(),"config"),v2=GG(mJ.cwd(),"src/generated"),Z5=AG.env.CLARITY_LOG_DIR||Bz(R2(),"logs"),oA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Z5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},pJ=await w2(),l0={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"},I0=l0,b2=l0.red,X5=l0.green,c2=l0.yellow,j5=l0.blue,m2=l0.magenta,d2=l0.cyan,qJ=l0.white,p2=l0.gray,L5=l0.bgRed,F5=l0.bgYellow,xJ=l0.bold,n2=l0.dim,u2=l0.italic,i2=l0.underline,s2=l0.reset,tA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},m5={debug:"\uD83D\uDD0D",info:j5("\u2139"),success:X5("\u2713"),warning:F5(qJ(xJ(" WARN "))),error:L5(qJ(xJ(" ERROR ")))},r2=new EG("stacks"),o0=new EG("bunfig",{showTags:!0}),l2=h$(ch.cwd(),"config"),o2=h$(ch.cwd(),"src/generated"),R5=hG.env.CLARITY_LOG_DIR||Cz(V2(),"logs"),aA={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,writeToFile:!1},nJ=await M2(),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`,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"},R0=b0,t2=b0.red,w5=b0.green,a2=b0.yellow,_5=b0.blue,e2=b0.magenta,$W=b0.cyan,fJ=b0.white,hW=b0.gray,O5=b0.bgRed,D5=b0.bgYellow,AW=b0.bgGray,gJ=b0.bold,GW=b0.dim,JW=b0.italic,HW=b0.underline,EW=b0.strikethrough,UW=b0.reset,eA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},d5={debug:"\uD83D\uDD0D",info:_5("\u2139"),success:w5("\u2713"),warning:D5(fJ(gJ(" WARN "))),error:O5(fJ(gJ(" ERROR ")))},YW=new YG("stacks"),z$=class extends Error{timestamp;context;constructor(h,A={}){super(h);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 h=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,G])=>`${A}: ${G}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${h}`}},zG=class extends z${code="CONFIG_NOT_FOUND";constructor(h,A,G){let J=G?` or alias "${G}"`:"";super(`Configuration "${h}"${J} not found`,{configName:h,alias:G,searchPaths:A,searchPathCount:A.length})}},mh=class extends z${code="CONFIG_LOAD_ERROR";constructor(h,A,G){super(`Failed to load configuration from "${h}": ${A.message}`,{configPath:h,configName:G,originalError:A.name,originalMessage:A.message});this.cause=A}},uJ=class extends z${code="CONFIG_VALIDATION_ERROR";constructor(h,A,G){super(`Configuration validation failed for "${h}"`,{configPath:h,configName:G,validationErrors:A,errorCount:A.length})}},iJ=class extends z${code="CONFIG_MERGE_ERROR";constructor(h,A,G,J){super(`Failed to merge configuration from "${h}" with "${A}": ${G.message}`,{sourcePath:h,targetPath:A,configName:J,originalError:G.name,originalMessage:G.message});this.cause=G}},WG=class extends z${code="ENV_VAR_ERROR";constructor(h,A,G,J){super(`Failed to parse environment variable "${h}" with value "${A}" as ${G}`,{envKey:h,envValue:A,expectedType:G,configName:J})}},sJ=class extends z${code="FILE_SYSTEM_ERROR";constructor(h,A,G){super(`File system ${h} failed for "${A}": ${G.message}`,{operation:h,path:A,originalError:G.name,originalMessage:G.message});this.cause=G}},rJ=class extends z${code="TYPE_GENERATION_ERROR";constructor(h,A,G){super(`Failed to generate types from "${h}" to "${A}": ${G.message}`,{configDir:h,outputPath:A,originalError:G.name,originalMessage:G.message});this.cause=G}},dh=class extends z${code="SCHEMA_VALIDATION_ERROR";constructor(h,A,G){super(`Schema validation failed${G?` for config "${G}"`:""}`,{schemaPath:h,configName:G,validationErrors:A,errorCount:A.length})}},lJ=class extends z${code="BROWSER_CONFIG_ERROR";constructor(h,A,G,J){super(`Failed to fetch configuration from "${h}": ${A} ${G}`,{endpoint:h,status:A,statusText:G,configName:J})}},oJ=class extends z${code="PLUGIN_ERROR";constructor(h,A,G){super(`Plugin "${h}" failed during ${A}: ${G.message}`,{pluginName:h,operation:A,originalError:G.name,originalMessage:G.message});this.cause=G}},H1={configNotFound($,h,A){return new zG($,h,A)},configLoad($,h,A){return new mh($,h,A)},configValidation($,h,A){return new uJ($,h,A)},configMerge($,h,A,G){return new iJ($,h,A,G)},envVar($,h,A,G){return new WG($,h,A,G)},fileSystem($,h,A){return new sJ($,h,A)},typeGeneration($,h,A){return new rJ($,h,A)},schemaValidation($,h,A){return new dh($,h,A)},browserConfig($,h,A,G){return new lJ($,h,A,G)},plugin($,h,A){return new oJ($,h,A)}},p5={replace:"replace",concat:"concat",smart:"smart"},n5=/^https?:\/\//,S$=new YG("bunfig",{showTags:!0}),d$=new HH,u5=A$(M1.cwd(),"config"),i5=A$(M1.cwd(),"src/generated")});XW=JG.env.CLARITY_LOG_DIR||lz(ZW(),"logs"),s5={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:XW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ZG={...s5},cL=(async()=>{try{let{loadConfig:$}=await WW().then(()=>N5),h=await $({name:"clarity",alias:"logging",defaultConfig:s5,cwd:JG.cwd()});if(h)Object.assign(ZG,h)}catch{}return ZG})();u0={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=u0,mL=u0.red,LW=u0.green,dL=u0.yellow,FW=u0.blue,pL=u0.magenta,nL=u0.cyan,V5=u0.white,uL=u0.gray,RW=u0.bgRed,wW=u0.bgYellow,iL=u0.bgGray,M5=u0.bold,sL=u0.dim,rL=u0.italic,lL=u0.underline,oL=u0.strikethrough,tL=u0.reset,vJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_W={debug:"\uD83D\uDD0D",info:FW("\u2139"),success:LW("\u2713"),warning:wW(V5(M5(" WARN "))),error:RW(V5(M5(" ERROR ")))};aL=new wG("stacks");Q$=class Q$ extends Error{timestamp;context;constructor($,h={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=h,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(([h,A])=>`${h}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};l5=class l5 extends Q${code="CONFIG_NOT_FOUND";constructor($,h,A){let G=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],J="";if(G.length===1)J=` or alias "${G[0]}"`;else if(G.length>1)J=` or aliases ${G.map((H)=>`"${H}"`).join(", ")}`;super(`Configuration "${$}"${J} not found`,{configName:$,alias:A,searchPaths:h,searchPathCount:h.length})}};XG=class XG extends Q${code="CONFIG_LOAD_ERROR";constructor($,h,A){super(`Failed to load configuration from "${$}": ${h.message}`,{configPath:$,configName:A,originalError:h.name,originalMessage:h.message});this.cause=h}};o5=class o5 extends Q${code="CONFIG_VALIDATION_ERROR";constructor($,h,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:h,errorCount:h.length})}};t5=class t5 extends Q${code="CONFIG_MERGE_ERROR";constructor($,h,A,G){super(`Failed to merge configuration from "${$}" with "${h}": ${A.message}`,{sourcePath:$,targetPath:h,configName:G,originalError:A.name,originalMessage:A.message});this.cause=A}};EH=class EH extends Q${code="ENV_VAR_ERROR";constructor($,h,A,G){super(`Failed to parse environment variable "${$}" with value "${h}" as ${A}`,{envKey:$,envValue:h,expectedType:A,configName:G})}};a5=class a5 extends Q${code="FILE_SYSTEM_ERROR";constructor($,h,A){super(`File system ${$} failed for "${h}": ${A.message}`,{operation:$,path:h,originalError:A.name,originalMessage:A.message});this.cause=A}};e5=class e5 extends Q${code="TYPE_GENERATION_ERROR";constructor($,h,A){super(`Failed to generate types from "${$}" to "${h}": ${A.message}`,{configDir:$,outputPath:h,originalError:A.name,originalMessage:A.message});this.cause=A}};jG=class jG extends Q${code="SCHEMA_VALIDATION_ERROR";constructor($,h,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:h,errorCount:h.length})}};$9=class $9 extends Q${code="BROWSER_CONFIG_ERROR";constructor($,h,A,G){super(`Failed to fetch configuration from "${$}": ${h} ${A}`,{endpoint:$,status:h,statusText:A,configName:G})}};h9=class h9 extends Q${code="PLUGIN_ERROR";constructor($,h,A){super(`Plugin "${$}" failed during ${h}: ${A.message}`,{pluginName:$,operation:h,originalError:A.name,originalMessage:A.message});this.cause=A}};V1={configNotFound($,h,A){return new l5($,h,A)},configLoad($,h,A){return new XG($,h,A)},configValidation($,h,A){return new o5($,h,A)},configMerge($,h,A,G){return new t5($,h,A,G)},envVar($,h,A,G){return new EH($,h,A,G)},fileSystem($,h,A){return new a5($,h,A)},typeGeneration($,h,A){return new e5($,h,A)},schemaValidation($,h,A){return new jG($,h,A)},browserConfig($,h,A,G){return new $9($,h,A,G)},plugin($,h,A){return new h9($,h,A)}};KW=/^https?:\/\//;M$=new wG("bunfig",{showTags:!0});bJ=new U9;GF=k$(LG.cwd(),"config"),JF=k$(LG.cwd(),"src/generated")});import W9 from"process";function G0($=v.dialect){return $==="mysql"||$==="singlestore"||$==="vitess"}function Z9($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let h=Object.getPrototypeOf($);return h===Object.prototype||h===null}function YH($,h,A=new Set){let G={...$};A.add(h);for(let J of Object.keys(h)){if(L9.has(J))continue;let H=h[J];if(Z9(H)&&!A.has(H)){let E=G[J];G[J]=YH(Z9(E)?E:{},H,A)}else G[J]=H}return A.delete(h),G}function OG($){if($)return $;let h=W9.env.DB_DIALECT||W9.env.DB_CONNECTION;if(h)return h;return v.dialect||"postgres"}function r($){if(v.dialect==="postgres")return`$${$}`;return"?"}function x0($,h=1){if($<=0)return"";if(v.dialect==="postgres"){let A=`$${h}`;for(let G=1;G<$;G++)A+=`, $${h+G}`;return A}return $===1?"?":`?${", ?".repeat($-1)}`}async function DG(){if(!_G.fileLoaded){_G.fileLoaded=!0;let $=await Y9({name:"query-builder",alias:"qb",defaultConfig:j9}),h={};for(let[A,G]of Object.entries($??{}))if(!_G.explicit.has(A))h[A]=G;F9(h)}return v}function F9($){let h=YH(v,$),A=v;for(let G of Object.keys(h)){if(L9.has(G))continue;A[G]=h[G]}}function R9($){if($.dialect&&nh&&$.dialect!==nh){let h=`${nh}->${$.dialect}`;if(!X9.has(h))X9.add(h),console.warn(`[query-builder] Configuring dialect '${$.dialect}' overrides the previously configured dialect '${nh}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if($.dialect)nh=$.dialect;for(let h of Object.keys($))_G.explicit.add(h);F9($)}function YF($){return $}var j9,L9,IW,v,PW,_G,nh=null,X9;var f0=a(()=>{z9();j9={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},L9=new Set(["__proto__","constructor","prototype"]);IW=Symbol.for("bun-query-builder.config"),v=globalThis[IW]??=YH({},j9),PW=Symbol.for("bun-query-builder.config-state"),_G=globalThis[PW]??={explicit:new Set,fileLoaded:!1};X9=new Set});function TW(){let $=v.sqlite?.pragmas;return Array.isArray($)?$:NW}function uh($){for(let h of TW())try{$.run(h)}catch{}}var NW;var VG=a(()=>{f0();NW=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"]});var{SQL:w9}=globalThis.Bun;import{Database as yW}from"bun:sqlite";import{mkdirSync as qW}from"fs";import{dirname as xW}from"path";import sh from"process";function ih($){return $}function kW($){return $!==null&&typeof $==="object"?$:null}function _9($,h){if(h.length===0||!/\$\d/.test($))return{sql:$,params:h};let A=[],G="",J=0;for(let H=0;H<$.length;H++){let E=$[H];if(E==="'"||E==='"'||E==="`"){let Y=fW($,H,E);G+=$.slice(H,Y),H=Y-1;continue}if(E==="-"&&$[H+1]==="-"){let Y=$.indexOf(`
|
|
66
|
-
`,H),U=Y===-1?$.length:Y;G+=$.slice(H,U),H=U-1;continue}if(E==="/"&&$[H+1]==="*"){let Y=$.indexOf("*/",H+2),U=Y===-1?$.length:Y+2;G+=$.slice(H,U),H=U-1;continue}if(E==="$"){let Y=/^\d+/.exec($.slice(H+1))?.[0];if(Y){let U=Number(Y);if(J=Math.max(J,U),U>=1&&U<=h.length){A.push(h[U-1]),G+="?",H+=Y.length;continue}}}G+=E}if(J>h.length)throw Error(`SQL references $${J} but only ${h.length} value${h.length===1?" was":"s were"} provided`);if(A.length===0)return{sql:$,params:h};return{sql:G,params:A}}function fW($,h,A){for(let G=h+1;G<$.length;G++){if($[G]!==A)continue;if($[G+1]===A){G++;continue}return G+1}return $.length}class M9{db;constructor($){if($!==":memory:"&&!$.startsWith(":")){let h=xW($);if(h&&h!==".")qW(h,{recursive:!0})}this.db=new yW($),uh(this.db)}query($,h=[]){let A=_9($,h);return this.db.prepare(A.sql).all(...A.params)}run($,h=[]){let A=_9($,h);return this.db.prepare(A.sql).run(...A.params)}close(){this.db.close()}get database(){return this.db}}function O9($){return{__raw:!0,value:$,toString:()=>$}}function D9($){let h=$.trimStart();for(;;)if(h.startsWith("--")){let A=h.indexOf(`
|
|
67
|
-
`);h=A===-1?"":h.slice(A+1).trimStart()}else if(h.startsWith("/*")){let A=h.indexOf("*/");h=A===-1?"":h.slice(A+2).trimStart()}else return h}function gW($){let h=[],A="",G=!1,J=!1,H=!1,E=!1;for(let U=0;U<$.length;U++){let z=$[U],W=$[U+1];if(!G&&!J&&!E&&z==="-"&&W==="-"){H=!0,A+=z;continue}if(H&&(z===`
|
|
68
|
-
`||z==="\r")){H=!1,A+=z;continue}if(!G&&!J&&!H&&z==="/"&&W==="*"){E=!0,A+=z;continue}if(E&&z==="*"&&W==="/"){E=!1,A+=z+W,U++;continue}if(H||E){A+=z;continue}if(z==="'"&&!J){if(G&&W==="'"){A+=z+W,U++;continue}G=!G,A+=z;continue}if(z==='"'&&!G){J=!J,A+=z;continue}if(z===";"&&!G&&!J){let Z=D9(A.trim());if(Z)h.push(Z);A="";continue}A+=z}let Y=D9(A.trim());if(Y)h.push(Y);return h}function V9($){let h=new M9($);function A(H,...E){let Y=H[0],U=[];for(let z=0;z<E.length;z++){let W=E[z],Z=kW(W);if(Z&&typeof Z.sql==="string"&&Array.isArray(Z.values))Y+=Z.sql+(H[z+1]||""),U.push(...Z.values);else if(Z&&(Z.__raw||Z.raw)){let F=Z.raw,w=Z.__raw?Z.value:typeof F==="string"?F:F();Y+=w+(H[z+1]||"")}else if(Array.isArray(W)){let F=W.map(()=>"?").join(", ");Y+=F+(H[z+1]||""),U.push(...W)}else Y+=`?${H[z+1]||""}`,U.push(W)}return{sql:Y,values:U,execute:()=>{try{let z=Y.trim().toUpperCase();if(z.startsWith("SELECT")||z.startsWith("PRAGMA")||/\bRETURNING\b/.test(z)){let W=h.query(Y,ih(U));return Promise.resolve(W)}else{let W=h.run(Y,ih(U));return Promise.resolve(W)}}catch(z){return Promise.reject(z)}},raw:()=>Y,toString:()=>Y,cancel:()=>{}}}function G(H,...E){if(Array.isArray(H)&&"raw"in H)return A(H,...E);if(typeof H==="string")return O9(H);return A([""])}G.raw=(H)=>O9(H),G.unsafe=(H,E=[])=>{let Y=()=>{try{let U=H.trim().toUpperCase();if(U.startsWith("SELECT")||U.startsWith("PRAGMA")||/\bRETURNING\b/.test(U)){let z=h.query(H,ih(E));return Promise.resolve(z)}else{let z=h.run(H,ih(E));return Promise.resolve(z)}}catch(U){return Promise.reject(U)}};return{sql:H,values:E,execute:Y,then:(U,z)=>Y().then(U,z),raw:()=>H,toString:()=>H,cancel:()=>{}}},G.close=()=>{return h.close(),Promise.resolve()},G.query=(H,E)=>{try{let Y=h.query(H,ih(E||[]));return Promise.resolve(Y)}catch(Y){return Promise.reject(Y)}},G.file=async(H,E)=>{try{let{readFileSync:Y}=await import("fs"),U=Y(H,"utf-8"),z=gW(U);for(let W of z){let Z=W.trim();if(!Z||Z.startsWith("--"))continue;let F=Z.toUpperCase();if(F.startsWith("SELECT")||F.startsWith("PRAGMA"))h.query(W);else h.run(W)}return Promise.resolve([])}catch(Y){return Promise.reject(Y)}};let J=0;return G.begin=async(H,E)=>{let Y=typeof H==="function"?H:E;if(typeof Y!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let U=J>0,z=`qb_sp_${J}`;if(U)h.run(`SAVEPOINT ${z}`);else h.run("BEGIN");J++;try{let W=await Y(G);if(J--,U)h.run(`RELEASE SAVEPOINT ${z}`);else h.run("COMMIT");return W}catch(W){J--;try{if(U)h.run(`ROLLBACK TO SAVEPOINT ${z}`),h.run(`RELEASE SAVEPOINT ${z}`);else h.run("ROLLBACK")}catch{}throw W}},G.savepoint=G.begin,G.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},G._wrapper=h,G}function vW($){let h=$.replace(/^(?:sqlite|sqlite3|file):/i,"");if(h===$)return $;return(h.startsWith("///")?h.slice(2):h.startsWith("//")?h.slice(2):h)||":memory:"}function MG($=v.database){let h=sh.env.DB_DATABASE||$?.database||"";return String(h).replace(/^['"]|['"]$/g,"")}function bW($,h){if(($==="postgres"||$==="mysql"||$==="singlestore"||$==="vitess")&&sh.env.DB_CONNECTION===$){let z=sh.env,W=(z.DB_DATABASE||h.database||"").replace(/^['"]|['"]$/g,""),Z=z.DB_USERNAME||h.username,F=z.DB_PASSWORD??h.password??"",w=z.DB_HOST||h.host||"localhost",B=z.DB_PORT||h.port,j=$==="postgres"?"postgres":"mysql",O=z.DB_SSL==="true"||z.DB_SSL==="1"||h.ssl?"?ssl=true":"";return`${j}://${Z}:${F}@${w}${B?`:${B}`:""}/${W}${O}`}if(h.url)return $==="sqlite"?vW(h.url):h.url;let{database:A,username:G,password:J,host:H="localhost",port:E,ssl:Y}=h,U=Y||sh.env.DB_SSL==="true"||sh.env.DB_SSL==="1"?"?ssl=true":"";switch($){case"postgres":return`postgres://${G}:${J}@${H}${E?`:${E}`:""}/${A}${U}`;case"mysql":case"singlestore":case"vitess":return`mysql://${G}:${J}@${H}${E?`:${E}`:""}/${A}${U}`;case"sqlite":if(A===":memory:")return":memory:";return A||":memory:";default:throw Error(`Unsupported dialect: ${$}`)}}function S9($){if(!$)return{};let h={},A=(G)=>Math.max(0,Math.round(G/1000));if(typeof $.max==="number"&&Number.isFinite($.max))h.max=$.max;if(typeof $.idleTimeoutMs==="number"&&Number.isFinite($.idleTimeoutMs))h.idleTimeout=A($.idleTimeoutMs);if(typeof $.acquireTimeoutMs==="number"&&Number.isFinite($.acquireTimeoutMs))h.connectionTimeout=A($.acquireTimeoutMs);if(typeof $.maxLifetimeMs==="number"&&Number.isFinite($.maxLifetimeMs))h.maxLifetime=A($.maxLifetimeMs);return h}function cW(){let $=v.dialect,h=bW($,v.database);try{if($==="sqlite")return V9(h);let A=S9(v.database.pool);return Object.keys(A).length>0?new w9(h,A):new w9(h)}catch(A){if(console.error(`[query-builder] Failed to create database connection for dialect '${$}': ${A.message}`),$==="sqlite")return V9(":memory:");throw A}}function mW(){let $=v.database;return JSON.stringify({dialect:v.dialect,database:$.database,username:$.username,password:$.password,host:$.host,port:$.port,url:$.url,pool:S9($.pool)})}function E1($=!1){let h=mW();if($||S1!==null&&zH!==h||!S1){if(S1)Q9();S1=cW(),zH=h}return S1}function dW(){let $=S1;return S1=null,zH=null,$}async function pW($){if(!$||typeof $.close!=="function")return;await $.close()}function Q9(){pW(dW()).catch((h)=>{console.error(`[query-builder] Failed to close database connection: ${h.message}`)})}async function WH($){try{return await $(E1())}catch(h){if(h?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||h?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let A=E1(!0);return await $(A)}throw h}}function nW(){return new Proxy(function(){},{get($,h){let A=E1(),G=A[h];if(typeof G==="function")return G.bind(A);return G},apply($,h,A){return E1()(...A)}})}var S1=null,zH=null,$0;var U1=a(()=>{f0();VG();$0=nW()});async function uW($={}){let h=$.iterations||1000,A=$.operations?.split(",")||["select","insert","update","delete","count"];console.log("-- Running Query Builder Benchmarks"),console.log(`-- Iterations: ${h}`),console.log(`-- Operations: ${A.join(", ")}`),console.log();let G=J0();console.log("-- Setting up test table...");try{await $0.unsafe("DROP TABLE IF EXISTS bench_users").execute(),await $0.unsafe(`
|
|
69
|
-
CREATE TABLE bench_users (
|
|
70
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
71
|
-
name TEXT NOT NULL,
|
|
72
|
-
email TEXT NOT NULL,
|
|
73
|
-
active INTEGER DEFAULT 1,
|
|
74
|
-
created_at TEXT
|
|
75
|
-
)
|
|
76
|
-
`).execute();for(let E=0;E<100;E++)await $0.unsafe(`
|
|
77
|
-
INSERT INTO bench_users (name, email, created_at)
|
|
78
|
-
VALUES (?, ?, ?)
|
|
79
|
-
`,[`User ${E}`,`user${E}@example.com`,new Date().toISOString()]).execute();console.log("-- \u2713 Test table ready with 100 rows"),console.log()}catch(E){throw console.error("-- Failed to setup test table:",E),E}let J=[];if(A.includes("select")){let E=[];for(let Y=0;Y<h;Y++){let U=performance.now();await G.selectFrom("bench_users").where({active:1}).limit(10).execute(),E.push(performance.now()-U)}J.push({operation:"SELECT with WHERE + LIMIT",avgTime:E.reduce((Y,U)=>Y+U,0)/E.length,minTime:Math.min(...E),maxTime:Math.max(...E),iterations:h})}if(A.includes("select")){let E=[];for(let Y=0;Y<h;Y++){let U=performance.now();await G.selectFrom("bench_users").where({id:1}).first(),E.push(performance.now()-U)}J.push({operation:"SELECT by ID (first)",avgTime:E.reduce((Y,U)=>Y+U,0)/E.length,minTime:Math.min(...E),maxTime:Math.max(...E),iterations:h})}if(A.includes("count")){let E=[];for(let Y=0;Y<h;Y++){let U=performance.now();await G.selectFrom("bench_users").count(),E.push(performance.now()-U)}J.push({operation:"COUNT",avgTime:E.reduce((Y,U)=>Y+U,0)/E.length,minTime:Math.min(...E),maxTime:Math.max(...E),iterations:h})}if(A.includes("insert")){let E=[];for(let Y=0;Y<h;Y++){let U=performance.now();await G.insertInto("bench_users").values({name:`Bench User ${Y}`,email:`bench${Y}@example.com`,created_at:new Date().toISOString()}).execute(),E.push(performance.now()-U)}J.push({operation:"INSERT",avgTime:E.reduce((Y,U)=>Y+U,0)/E.length,minTime:Math.min(...E),maxTime:Math.max(...E),iterations:h})}if(A.includes("update")){let E=[];for(let Y=0;Y<h;Y++){let U=performance.now();await G.updateTable("bench_users").set({active:0}).where({id:1}).execute(),E.push(performance.now()-U)}J.push({operation:"UPDATE by ID",avgTime:E.reduce((Y,U)=>Y+U,0)/E.length,minTime:Math.min(...E),maxTime:Math.max(...E),iterations:h})}if(A.includes("delete")){let E=[],Y=[];for(let U=0;U<h;U++){let z=await G.insertInto("bench_users").values({name:"To Delete",email:`delete${U}@example.com`,created_at:new Date().toISOString()}).execute();Y.push(z)}for(let U=0;U<h;U++){let z=performance.now();await G.deleteFrom("bench_users").where({id:Y[U]}).execute(),E.push(performance.now()-z)}J.push({operation:"DELETE by ID",avgTime:E.reduce((U,z)=>U+z,0)/E.length,minTime:Math.min(...E),maxTime:Math.max(...E),iterations:h})}console.log("-- Benchmark Results"),console.log();let H=Math.max(...J.map((E)=>E.operation.length));console.log("Operation".padEnd(H+2)+"Avg (ms)".padStart(12)+"Min (ms)".padStart(12)+"Max (ms)".padStart(12)+"Ops/sec".padStart(12)),console.log("-".repeat(H+2+12+12+12+12));for(let E of J){let Y=E.operation.padEnd(H+2),U=E.avgTime.toFixed(3).padStart(12),z=E.minTime.toFixed(3).padStart(12),W=E.maxTime.toFixed(3).padStart(12),Z=(1000/E.avgTime).toFixed(0).padStart(12);console.log(`${Y}${U}${z}${W}${Z}`)}console.log();try{await $0.unsafe("DROP TABLE IF EXISTS bench_users").execute(),console.log("-- \u2713 Cleanup complete")}catch(E){console.error("-- Warning: Failed to cleanup test table:",E)}}var C9=a(()=>{U1();m0()});function ZH($){let h=String($).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(h.endsWith("y")&&!/[aeou]y$/.test(h))return`${h.slice(0,-1)}ies`;if(h.endsWith("s")||h.endsWith("x")||h.endsWith("ch")||h.endsWith("sh"))return`${h}es`;return`${h}s`}function Y1($){return typeof $?.table==="string"&&$.table.length>0?$.table:ZH(String($?.name??""))}function iW($){return $.endsWith("s")?$.slice(0,-1):$}function sW($){if($.endsWith("ies")&&$.length>3){let h=$.slice(0,-3),A=h[h.length-1];if(A&&!"aeiou".includes(A))return`${h}y`}if($.endsWith("es")&&$.length>2){let h=$.slice(0,-2);if(h.endsWith("s")||h.endsWith("x")||h.endsWith("ch")||h.endsWith("sh"))return h}if($.endsWith("s")&&!$.endsWith("ss")&&!$.endsWith("us")&&!$.endsWith("is"))return $.slice(0,-1);return $}function z1($){if($==="none")return(h)=>h;if($==="inflect")return sW;return iW}function rW($){return z1(v.relations?.singularizeStrategy)($)}function Q1($,h,A,G={}){let J=G.singularize??rW,E=$.relations?.[h]?.belongsToMany?.[A];if(E==null)return null;let Y=typeof E==="object",U=Y?E:null,z=Y?U.model:E,W=$.modelToTable[z]||z,Z,F;if(U?.table)Z=U.table;else if(U?.through){if(F=U.through,Z=$.modelToTable[U.through],!Z)throw Error(`[query-builder] belongsToMany relation '${A}' on '${h}' references unknown through model '${U.through}'. Make sure '${U.through}' is registered via defineModels({...}).`)}else{let R=J(h),S=J(W);Z=[R,S].sort().join("_")}let w=U?.foreignKey??`${J(h)}_id`,B=U?.relatedKey??`${J(W)}_id`,j={};if(U?.pivot?.columns)Object.assign(j,U.pivot.columns);if(F&&G.models){let R=G.models[F],S=R?.definition??R?.getDefinition?.()??R,D=S?.attributes??{};for(let[y,P]of Object.entries(D)){if(y===w||y===B||y===(S?.primaryKey??"id"))continue;j[y]={default:P?.default,nullable:P?.nullable,validation:P?.validation}}}let O=Boolean(U?.pivot?.timestamps),_=Object.keys(j);return{pivotTable:Z,fkParent:w,fkRelated:B,pivotColumns:_,pivotColumnDefs:j,pivotModelName:F,timestamps:O,relatedModelName:z,relatedTable:W,hasConfig:Y}}function*KF($,h={}){let A=$.relations;if(!A)return;for(let[G,J]of Object.entries(A)){let H=J?.belongsToMany;if(!H)continue;for(let E of Object.keys(H)){let Y=Q1($,G,E,h);if(Y)yield{parentTable:G,relationKey:E,resolved:Y}}}}var XH=a(()=>{f0()});function C1($){if($.length===0)return"";let h=[];for(let A of $)if(A.conn==="OR"&&h.length>0)h[h.length-1].push(A);else h.push([A]);return h.map((A,G)=>{let J=A.map((E)=>E.sql).join(" OR "),H=A.length>1&&h.length>1?`(${J})`:J;return G===0?H:`${A[0].conn} ${H}`}).join(" ")}function W$($,h,A,G){if(h.length===0)return A?"1 = 1":"1 = 0";return`${$} ${A?"NOT IN":"IN"} (${G})`}function lW($,h){if(h!=="postgres")return $;let A="",G=0,J=0;while(J<$.length){let H=$[J];if(H==="'"){let E=K9($,J,"'");A+=$.slice(J,E),J=E;continue}if(H==='"'){let E=K9($,J,'"');A+=$.slice(J,E),J=E;continue}if(H==="$"){let E=$.slice(J).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(E){let Y=$.indexOf(E,J+E.length),U=Y===-1?$.length:Y+E.length;A+=$.slice(J,U),J=U;continue}}if(H==="?"){G++,A+=`$${G}`,J++;continue}A+=H,J++}return A}function K9($,h,A){let G=h+1;while(G<$.length){if($[G]===A){if($[G+1]===A){G+=2;continue}return G+1}G++}return $.length}var B9="1 = 0";function n$($){return typeof $==="object"&&$!==null&&"raw"in $&&typeof $.raw==="string"}function SG($){return typeof $==="object"&&$!==null&&"sql"in $&&typeof $.sql==="string"&&(!("parameters"in $)||Array.isArray($.parameters))}function QG($,h){let A=$.parameters??[];if(v.dialect!=="postgres"||A.length===0)return{text:$.sql,parameters:A};let G=0,J=$.sql.replace(/\?/g,(H)=>{if(G>=A.length)return H;return r(h+G++)});if(G!==A.length)throw TypeError(`[query-builder] SQL expression declares ${A.length} parameters but contains only ${G} placeholders`);return{text:J,parameters:A}}function qF($,...h){if(typeof $==="string")return{raw:$};let A=$[0];for(let G=0;G<h.length;G++)A+=p$(h[G])+$[G+1];return{raw:A}}function E$($){return G0(v.dialect)?`\`${$.replace(/`/g,"``")}\``:`"${$.replace(/"/g,'""')}"`}function CG($,h=1){let A=Object.keys($[0]??{}),G=[],J=h,H=$.map((E)=>{return`(${A.map((U)=>{return G.push(E[U]),r(J++)}).join(", ")})`});return{colsSql:A.map(E$).join(", "),valuesSql:H.join(", "),params:G,nextIndex:J}}function rh($){return Boolean($&&($.onSlowQuery||$.slowQueryThresholdMs!=null&&$.slowQueryThresholdMs>=0))}function I9($){if(typeof $==="string")return $;if(n$($))return $.raw;if($&&typeof $==="object"){let h=$;if(typeof h.raw==="function")return String(h.raw());if(typeof h.sql==="string")return h.sql;let A=String($);if(A!=="[object Object]")return A}throw TypeError(`[query-builder] select(): unsupported column ${String($)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function oW($){let h=/\(|\)|\bORDER\s+BY\b/gi,A=0,G;while(G=h.exec($))if(G[0]==="(")A++;else if(G[0]===")")A=Math.max(0,A-1);else if(A===0)return!0;return!1}function i($,h){if(!X0.IDENTIFIER.test($)){let A=h?` in ${h}`:"";throw Error(`[query-builder] Invalid identifier${A}: '${$}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function g0($,h){if(typeof $!=="string")throw TypeError(`[query-builder] ${h}: operator must be a string, got ${typeof $}`);let A=$.toLowerCase();if(!P9.has(A))throw TypeError(`[query-builder] ${h}: refusing to use '${$}' as a SQL operator \u2014 not in the allowed set (${[...P9].join(", ")})`);return $}function _$($,h){if(typeof $!=="string"||$.length===0)throw TypeError(`[query-builder] ${h}: identifier must be a non-empty string, got ${typeof $}`);if($.length>129)throw TypeError(`[query-builder] ${h}: identifier '${$}' too long`);let A=$.split(".");if(A.length>2)throw TypeError(`[query-builder] ${h}: identifier '${$}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let G of A)if(!/^[A-Z_][A-Z0-9_]*$/i.test(G))throw TypeError(`[query-builder] ${h}: identifier segment '${G}' contains characters outside [A-Za-z0-9_]`)}function K1($,h){if(typeof $==="string")return tW(h),$;if($===null||$===void 0)throw TypeError(`[query-builder] ${h}: fragment must be a SqlFragment, got ${$}`);if(n$($))return $.raw;if(typeof $==="object"){let A=$;if(typeof A.raw==="string")return A.raw;if(typeof A.raw==="function"){let J=A.raw();if(typeof J==="string")return J}if(typeof A.sql==="string")return A.sql;let G=String($);if(G!=="[object Object]"&&G!=="[object Promise]")return G}throw TypeError(`[query-builder] ${h}: 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 tW($){if(N9.has($))return;N9.add($),console.warn(`[query-builder] ${$}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function aW($,h=v.dialect){return G0(h)?$.replace(/\\/g,"\\\\").replace(/'/g,"''"):$.replace(/'/g,"''")}function p$($){if($===null)return"NULL";if(typeof $==="number"&&Number.isFinite($))return String($);if(typeof $==="boolean")return $?"1":"0";if(typeof $==="string")return`'${aW($)}'`;if($ instanceof Date)return`'${$.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof $}`)}function eW($,h){let A=Array.isArray($)?$:$?[$]:[],G=[];if(A.length)G.push(`PARTITION BY ${A.join(", ")}`);if(h&&h.length)G.push(`ORDER BY ${h.map(([J,H])=>`${J} ${H==="desc"?"DESC":"ASC"}`).join(", ")}`);return G.length?`OVER (${G.join(" ")})`:"OVER ()"}class T9{cache=new Map;maxSize=100;get($){let h=this.cache.get($);if(!h)return null;if(Date.now()>h.expiresAt)return this.cache.delete($),null;return this.cache.delete($),this.cache.set($,h),h.data}set($,h,A){if(this.cache.has($))this.cache.delete($);if(this.cache.size>=this.maxSize){let G=Date.now(),J=!1;for(let[H,E]of this.cache)if(G>E.expiresAt){if(this.cache.delete(H),J=!0,this.cache.size<this.maxSize)break}if(!J){let H=this.cache.keys().next().value;if(H!==void 0)this.cache.delete(H)}}this.cache.set($,{data:h,expiresAt:Date.now()+A})}clear(){this.cache.clear()}setMaxSize($){this.maxSize=Math.max(0,Math.floor($));while(this.cache.size>this.maxSize){let h=this.cache.keys().next().value;if(h===void 0)break;this.cache.delete(h)}}}function $Z($){let h=String($?.message||"").toLowerCase();return h.includes("deadlock")||h.includes("serialization failure")||h.includes("could not serialize access")||h.includes("deadlock found when trying to get lock")||h.includes("lock wait timeout exceeded")||h.includes("database is locked")||h.includes("busy")}function hZ($,h){if(!h||h.length===0)return!1;let A=$&&($.code||$.sqlState||$.sqlstate);if(!A)return!1;return h.includes(A)}function AZ($){return new Promise((h)=>setTimeout(h,$))}function lh($){let h=KG.get($);if(h!==void 0)return h;let A=JZ($);if(KG.size>=GZ)KG.clear();return KG.set($,A),A}function JZ($){let h=[{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}],A=[],G=0,J=!1,H="";for(let W=0;W<$.length;W++){let Z=$[W];if(J){if(Z===H){if($[W+1]===H){W++;continue}J=!1}continue}if(Z==="'"||Z==='"'||Z==="`"){J=!0,H=Z;continue}if(Z==="("){G++;continue}if(Z===")"){G--;continue}if(G!==0)continue;if(W===0||!/\s/.test($[W-1]))continue;let F=$.charCodeAt(W)&-33;if(F!==71&&F!==79&&F!==72&&F!==76&&F!==87)continue;let w=$.slice(W);for(let{key:B,tokens:j}of h){let O=w.match(j);if(!O)continue;A.push({key:B,start:W}),W+=O[0].length-1;break}}if(A.length<=1)return $;let E=$.slice(0,A[0].start).trimEnd(),Y={};for(let W=0;W<A.length;W++){let Z=A[W].start,F=W+1<A.length?A[W+1].start:$.length,w=$.slice(Z,F).trim();if(!Y[A[W].key])Y[A[W].key]=[];Y[A[W].key].push(w)}let z=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((W)=>Y[W]).map((W)=>Y[W].join(" ")).join(" ");return z?`${E} ${z}`:E}function HZ($,h){let A=Math.max(1,h?.baseMs??50),G=Math.max(1,h?.factor??2),J=Math.max(A,h?.maxMs??2000),H=Math.min(J,A*G**Math.max(0,$-1));if(h?.jitter)H=Math.min(J,H*(0.9+Math.random()*0.2));return Math.floor(H)}function J0($){let h=$?.sql??E1(),A=$?.meta,G=$?.schema;function J(j){if(typeof j==="number")return j;let O=String(j),_=7;for(let R=0;R<O.length;R++)_=_*31+O.charCodeAt(R)|0;return Math.abs(_)}function H(){if(!$?.hooks)return v.hooks;return{...v.hooks,...$.hooks}}let E=new Map;function Y(j){if(Array.isArray(j)){let[D,y,P]=j;i(D,"where(column)");let T=String(D);switch(y){case"in":if(Array.isArray(P)){let C=x0(P.length);return h.unsafe(`${T} IN (${C})`,P)}return h.unsafe(`${T} IN (${r(1)})`,[P]);case"not in":if(Array.isArray(P)){let C=x0(P.length);return h.unsafe(`${T} NOT IN (${C})`,P)}return h.unsafe(`${T} NOT IN (${r(1)})`,[P]);case"like":return h.unsafe(`${T} LIKE ${r(1)}`,[P]);case"is":case"is not":{if(P!==null&&P!==void 0)throw TypeError(`[query-builder] where(..., '${y}', ?): operator '${y}' only accepts NULL/undefined as value, got ${typeof P} (${String(P)})`);return h.unsafe(`${T} IS ${y==="is not"?"NOT ":""}NULL`)}case"!=":return h.unsafe(`${T} <> ${r(1)}`,[P]);case"<":case">":case"<=":case">=":case"=":return h.unsafe(`${T} ${y} ${r(1)}`,[P]);default:throw TypeError(`[query-builder] where(..., '${String(y)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in j)return j.raw;let O=Object.keys(j);if(O.length===0)return h.unsafe("");let _=[],R=[],S=1;for(let D of O){i(D,"where(object key)");let y=j[D];if(Array.isArray(y)){let P=x0(y.length,S);_.push(`${D} IN (${P})`),R.push(...y),S+=y.length}else _.push(`${D} = ${r(S++)}`),R.push(y)}return h.unsafe(_.join(" AND "),R)}function U(j,O,_){if(!_)return O;let R=Y(_);return h`${O} WHERE ${R}`}function z(j){let O=v.debug?.captureText;if(v.debug)v.debug.captureText=!0;let _=String(j);if(v.debug)v.debug.captureText=O;return _}function W(j){if(!j||typeof j!=="object")return;if(Array.isArray(j.values))return j.values;if(Array.isArray(j.parameters))return j.parameters;if(Array.isArray(j.params))return j.params;return}function Z(j,O,_){let R=H(),S=R?.slowQueryThresholdMs,D=S!=null&&S>=0,y=Boolean(R?.onSlowQuery||D),P=R&&(R.onQueryStart||R.onQueryEnd||R.onQueryError||R.startSpan||y),T=_?.timeoutMs&&_.timeoutMs>0||_?.signal;if(!P&&!T)return j.execute();let C=z(j),Q=W(j),N=Date.now(),K;try{if(R?.onQueryStart?.({sql:C,params:Q,kind:O}),R?.startSpan)K=R.startSpan({sql:C,params:Q,kind:O})}catch{}let x=!1,p=(d,u)=>{if(x)return;x=!0;let f=Date.now()-N;try{if(d)R?.onQueryError?.({sql:C,params:Q,error:d,durationMs:f,kind:O});else if(R?.onQueryEnd?.({sql:C,params:Q,durationMs:f,rowCount:u,kind:O}),D&&f>=S)if(R?.onSlowQuery)R.onSlowQuery({sql:C,params:Q,durationMs:f,kind:O});else console.warn(`[query-builder] slow query (${f}ms >= ${S}ms): ${C}`)}catch{}try{K?.end(d)}catch{}},s=j.execute(),o=[s],q;if(_?.timeoutMs&&_.timeoutMs>0){let d=new Promise((u,f)=>{q=setTimeout(()=>{try{j.cancel?.()}catch{}let h0=Error(`Query timed out after ${_.timeoutMs}ms`);h0.code="EBQBTIMEOUT",f(h0)},_.timeoutMs)});o.push(d)}if(_?.signal){if(_.signal.aborted){try{j.cancel?.()}catch{}let u=Error("Query aborted");return u.code="EBQBABORT",p(u),Promise.reject(u)}let d=()=>{try{j.cancel?.()}catch{}};_.signal.addEventListener("abort",d,{once:!0}),s.finally(()=>{_.signal?.removeEventListener("abort",d)})}return Promise.race(o).then((d)=>{clearTimeout(q);let u=Array.isArray(d)?d.length:typeof d==="number"?d:void 0;return p(void 0,u),d}).catch((d)=>{throw clearTimeout(q),p(d),d})}function F(j){if(typeof j==="number")return Number.isFinite(j)?j:0;if(typeof j==="bigint")return Number(j);if(!j||typeof j!=="object")return 0;let O=j;for(let _ of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(O[_]!==void 0&&O[_]!==null)return F(O[_]);if(Array.isArray(j))return j.reduce((_,R)=>_+F(R),0);return 0}function w(j,O){let _=O??z(j);return{sql:_,toString:()=>_,execute:()=>j.execute(),values:()=>j.values(),raw:()=>j.raw()}}function B(j,O){let _=h,R=O&&O.length>0?`SELECT ${O.join(", ")} FROM ${String(j)}`:`SELECT * FROM ${String(j)}`,S=[],D=[],y=!1,P=null,T=()=>{if(P===null){let X=lh(x());P=D.length>0?h.unsafe(X,D):h.unsafe(X)}return P},C=(X,L)=>{S.push({conn:X,sql:L}),P=null},Q=(X,L)=>{C(X==="OR"?"OR":"AND",L)},N=/\(|\)|\b(?:GROUP\s+BY|HAVING|ORDER\s+BY|LIMIT|OFFSET|WINDOW|UNION|INTERSECT|EXCEPT|FOR\s+UPDATE|FOR\s+SHARE|LOCK\s+IN\s+SHARE\s+MODE)\b/gi,K=(X)=>{N.lastIndex=0;let L=0,V;while(V=N.exec(X))if(V[0]==="(")L++;else if(V[0]===")")L=Math.max(0,L-1);else if(L===0)return V.index;return-1},x=(X)=>{let L=C1(X?[...S,X]:S);if(!L)return R;if(y){let M=X0.WHERE.test(R)?"AND":"WHERE";return`${R} ${M} ${L}`}let V=K(R);return V>=0?`${R.slice(0,V)}WHERE ${L} ${R.slice(V)}`:`${R} WHERE ${L}`},p=(X,L)=>{let V=B(j);L(V);let M=V.__whereState?.();if(!M||!M.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let I=D.length,k=I>0&&v.dialect==="postgres"?M.body.replace(/\$(\d+)/g,(b,c)=>`$${Number(c)+I}`):M.body;D.push(...M.params),C(X,`(${k})`)},s=(X,L,V,M,I,k)=>{if(typeof M==="string"&&I!==void 0){i(String(M),`${V}(column)`),g0(I,`${V}(operator)`);let b=D.length+1;return D.push(k),C(L,`${String(M)} ${String(I)} ${r(b)}`),X}if(Array.isArray(M)){let[b,c,n]=M,g=String(b);i(g,`${V}(column)`);let m=g0(c,`${V}(operator)`);if(m==="in"||m==="not in"){let l=Array.isArray(n)?n:[n],H0=x0(l.length,D.length+1),y0=W$(g,l,m==="not in",H0);D.push(...l),C(L,y0)}else{let l=D.length+1;D.push(n),C(L,`${g} ${m} ${r(l)}`)}return X}if(typeof M==="function")return p(L,M),X;if(M&&typeof M==="object"&&!("raw"in M)){let b=[];for(let c of Object.keys(M)){i(c,`${V}(column)`);let n=M[c];if(Array.isArray(n)){let g=x0(n.length,D.length+1);b.push(W$(c,n,!1,g)),D.push(...n)}else{let g=D.length+1;b.push(`${c} = ${r(g)}`),D.push(n)}}if(b.length>0)C(L,b.length>1?`(${b.join(" AND ")})`:b[0]);return X}if(M&&typeof M.raw<"u")return C(L,M.raw),X;return X},o=(X,L)=>{if(S.length>0)R=x(),S.length=0;y=!0;let V=L.__rawState?.();if(V){let M=D.length,I=v.dialect==="postgres"?V.sql.replace(/\$(\d+)/g,(k,b)=>`$${Number(b)+M}`):V.sql;R+=` ${X} ${I}`,D.push(...V.params)}else R+=` ${X} ${String(L.toSQL())}`;P=null},q=(X)=>{let L=/\(|\)|\b(?:WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|OFFSET|UNION)\b/gi,V=0,M=-1,I;while(I=L.exec(R))if(I[0]==="(")V++;else if(I[0]===")")V=Math.max(0,V-1);else if(V===0){M=I.index;break}R=M>=0?`${R.slice(0,M)}${X} ${R.slice(M)}`:`${R} ${X}`,P=null},d=new Set,u,f,h0=!1,t=!1,K0=!1,j0=new Map,e0=new Set,A1=60000,V0=(X)=>z1(v.relations.singularizeStrategy)(X),L$=(X)=>{if(!A)return null;return Q1(A,String(j),X,{singularize:V0,models:A.models})},w1=(X)=>{if(!X||typeof X!=="object"||e0.size===0)return X;let L;for(let V of Object.keys(X))if(V.startsWith("pivot_")){if(!L)L={};L[V.slice(6)]=X[V],delete X[V]}if(L)X.pivot=L;return X},_1=(X)=>{if(e0.size===0||!X)return X;if(Array.isArray(X))for(let L=0;L<X.length;L++)w1(X[L]);else w1(X);return X},x$=(X)=>{if(!A)return;if(d.has(X.pivotTable))return;let L=String(j),V=A.primaryKeys[L]??"id";i(X.pivotTable,"wherePivot auto-join (pivot table)"),i(X.fkParent,"wherePivot auto-join (parent FK)"),i(L,"wherePivot auto-join (parent table)"),i(V,"wherePivot auto-join (parent PK)"),P=_`${T()} LEFT JOIN ${_(X.pivotTable)} ON ${_(`${X.pivotTable}.${X.fkParent}`)} = ${_(`${L}.${V}`)}`,R=`${R} LEFT JOIN ${X.pivotTable} ON ${X.pivotTable}.${X.fkParent} = ${L}.${V}`,d.add(X.pivotTable)},yh=(X)=>{if(X0.SELECT_STAR.test(R))R=R.replace(X0.SELECT_STAR,`SELECT *, ${X}`);else if(X0.SELECT.test(R))R=R.replace(X0.SELECT_FROM,`SELECT $1, ${X} FROM`);let L=String(T());if(X0.SELECT_STAR.test(L)){let V=L.replace(X0.SELECT_STAR,`SELECT *, ${X}`);P=h.unsafe(V)}else if(X0.SELECT.test(L)){if(X0.SELECT_FROM.exec(L)){let M=L.replace(X0.SELECT_FROM,`SELECT $1, ${X} FROM`);P=h.unsafe(M)}}},P$=(X,L,V,M)=>{yh(`${X} ${eW(V,M)} AS ${L}`)},BA=(X,L,V,M)=>{i(X,"relationship subquery (parent table)"),i(L,"relationship subquery (target table)"),i(V,"relationship subquery (primary key)");let I=`${X.endsWith("s")?X.slice(0,-1):X}_id`;i(I,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${L} WHERE ${L}.${I} = ${X}.${V}`;if(M){let c=M({where:(n,g,m)=>{return i(n,"relationship subquery condition"),`${L}.${n} ${g0(g,"whereHas callback")} ${p$(m)}`}});if(c)k+=` AND ${c}`}return k},IA=(X,L,V,M)=>{i(X,"relationship subquery (parent table)"),i(L,"relationship subquery (target table)"),i(V,"relationship subquery (primary key)");let I=`${L.endsWith("s")?L.slice(0,-1):L}_id`;i(I,"relationship subquery (foreign key)");let k=`SELECT 1 FROM ${L} WHERE ${L}.${V} = ${X}.${I}`;if(M){let c=M({where:(n,g,m)=>{return i(n,"relationship subquery condition"),`${L}.${n} ${g0(g,"whereHas callback")} ${p$(m)}`}});if(c)k+=` AND ${c}`}return k},PA=(X,L,V,M,I,k)=>{i(X,"relationship subquery (parent table)"),i(L,"relationship subquery (target table)"),i(V,"relationship subquery (primary key)"),i(M,"relationship subquery (target primary key)");let b=k&&A?Q1(A,X,k,{singularize:V0,models:A.models}):null,c=V0(X),n=V0(L),g=b?.pivotTable??[c,n].sort().join("_"),m=b?.fkParent??`${c}_id`,l=b?.fkRelated??`${n}_id`;i(g,"relationship subquery (pivot table)"),i(m,"relationship subquery (foreign key A)"),i(l,"relationship subquery (foreign key B)");let H0=`SELECT 1 FROM ${g} JOIN ${L} ON ${L}.${M} = ${g}.${l} WHERE ${g}.${m} = ${X}.${V}`;if(I){let e=I({where:(q0,$$,J$)=>{return i(q0,"relationship subquery condition"),`${L}.${q0} ${g0($$,"whereHas callback")} ${p$(J$)}`}});if(e)H0+=` AND ${e}`}return H0},t8=(X,L,V)=>{i(X,"withCount (parent table)"),i(L,"withCount (target table)"),i(V,"withCount (primary key)");let M=`${X.endsWith("s")?X.slice(0,-1):X}_id`;return i(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${M} = ${X}.${V})`},a8=(X,L,V,M)=>{i(X,"withCount (parent table)"),i(L,"withCount (target table)"),i(V,"withCount (primary key)");let I=M&&A?Q1(A,X,M,{singularize:V0,models:A.models}):null,k=V0(X),b=V0(L),c=I?.pivotTable??[k,b].sort().join("_"),n=I?.fkParent??`${k}_id`;return i(c,"withCount (pivot table)"),i(n,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${n} = ${X}.${V})`},NA=(X,L,V)=>{if(!A)return;i(V,`with${X[0]}${X.slice(1).toLowerCase()} (column)`);let M=String(j),I=A.relations?.[M];if(!I)return;let k=Object.entries(I).find(([e,q0])=>q0&&typeof q0==="object"&&(L in q0));if(!k)return;let[b,c]=k,n=c[L],g=typeof n==="string"?n:n?.model||n?.target||n,m=A.modelToTable[g]||g,l=A.primaryKeys[M]??"id";i(m,`with${X} (target table)`);let H0=`${X}(${m}.${V})`,y0;if(b==="hasMany"||b==="hasOne"){let e=`${M.endsWith("s")?M.slice(0,-1):M}_id`;i(e,`with${X} (foreign key)`),y0=`(SELECT ${H0} FROM ${m} WHERE ${m}.${e} = ${M}.${l})`}else if(b==="belongsToMany"){let e=A?Q1(A,M,L,{singularize:V0,models:A.models}):null,q0=V0(M),$$=V0(m),J$=e?.pivotTable??[q0,$$].sort().join("_"),t0=e?.fkParent??`${q0}_id`,E0=e?.fkRelated??`${$$}_id`,qh=A.primaryKeys[m]??"id";i(J$,`with${X} (pivot table)`),i(t0,`with${X} (foreign key)`),i(E0,`with${X} (related key)`),y0=`(SELECT ${H0} FROM ${J$} JOIN ${m} ON ${m}.${qh} = ${J$}.${E0} WHERE ${J$}.${t0} = ${M}.${l})`}else return;yh(`${y0} AS ${L}_${X.toLowerCase()}_${V}`)},VE=()=>{if(j0.size===0)return;let X=[];for(let[L,V]of j0.entries()){let M=L$(L);if(!M)continue;for(let k of V)i(k,"withPivot");let I=V.map((k)=>`${M.pivotTable}.${k} AS pivot_${k}`);X.push(...I)}if(X.length>0){let L=X.join(", ");yh(L)}};return new Proxy({distinct(){return R=R.replace(/^SELECT\s+/i,"SELECT DISTINCT "),P=null,this},distinctOn(...X){let L=X.map(String).join(", ");return R=R.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${L}) `),P=null,this},selectRaw(X){let L=K1(X,"selectRaw(fragment)"),V=R.indexOf(" FROM ");if(V!==-1)R=`${R.substring(0,V)}, ${L}${R.substring(V)}`;else R+=`, ${L}`;return P=null,this},rowNumber(X="row_number",L,V){let M=[];if(L){let c=Array.isArray(L)?L:[L];M.push(`PARTITION BY ${c.join(", ")}`)}if(V&&V.length)M.push(`ORDER BY ${V.map(([c,n])=>`${c} ${n==="desc"?"DESC":"ASC"}`).join(", ")}`);let k=`ROW_NUMBER() ${M.length?`OVER (${M.join(" ")})`:"OVER ()"} AS ${X}`,b=R.indexOf(" FROM ");if(b!==-1)R=`${R.substring(0,b)}, ${k}${R.substring(b)}`;else R+=`, ${k}`;return P=null,this},denseRank(X="dense_rank",L,V){let M=Array.isArray(L)?L:L?[L]:[],I=[];if(M.length)I.push(`PARTITION BY ${M.join(", ")}`);if(V&&V.length)I.push(`ORDER BY ${V.map(([n,g])=>`${n} ${g==="desc"?"DESC":"ASC"}`).join(", ")}`);let b=`DENSE_RANK() ${I.length?`OVER (${I.join(" ")})`:"OVER ()"} AS ${X}`,c=R.indexOf(" FROM ");if(c!==-1)R=`${R.substring(0,c)}, ${b}${R.substring(c)}`;else R+=`, ${b}`;return P=null,this},rank(X="rank",L,V){let M=Array.isArray(L)?L:L?[L]:[],I=[];if(M.length)I.push(`PARTITION BY ${M.join(", ")}`);if(V&&V.length)I.push(`ORDER BY ${V.map(([n,g])=>`${n} ${g==="desc"?"DESC":"ASC"}`).join(", ")}`);let b=`RANK() ${I.length?`OVER (${I.join(" ")})`:"OVER ()"} AS ${X}`,c=R.indexOf(" FROM ");if(c!==-1)R=`${R.substring(0,c)}, ${b}${R.substring(c)}`;else R+=`, ${b}`;return P=null,this},over(X,L,V={}){return P$(X,L,V.partitionBy,V.orderBy),this},lag(X,L={}){let V=[X,String(L.offset??1)];if(L.defaultValue!==void 0)V.push(String(L.defaultValue));return P$(`LAG(${V.join(", ")})`,L.alias??`${X}_lag`,L.partitionBy,L.orderBy),this},lead(X,L={}){let V=[X,String(L.offset??1)];if(L.defaultValue!==void 0)V.push(String(L.defaultValue));return P$(`LEAD(${V.join(", ")})`,L.alias??`${X}_lead`,L.partitionBy,L.orderBy),this},sumOver(X,L={}){return P$(`SUM(${X})`,L.alias??`${X}_sum`,L.partitionBy,L.orderBy),this},avgOver(X,L={}){return P$(`AVG(${X})`,L.alias??`${X}_avg`,L.partitionBy,L.orderBy),this},countOver(X="*",L={}){return P$(`COUNT(${X})`,L.alias??"count_over",L.partitionBy,L.orderBy),this},minOver(X,L={}){return P$(`MIN(${X})`,L.alias??`${X}_min`,L.partitionBy,L.orderBy),this},maxOver(X,L={}){return P$(`MAX(${X})`,L.alias??`${X}_max`,L.partitionBy,L.orderBy),this},firstValue(X,L={}){return P$(`FIRST_VALUE(${X})`,L.alias??`${X}_first`,L.partitionBy,L.orderBy),this},lastValue(X,L={}){return P$(`LAST_VALUE(${X})`,L.alias??`${X}_last`,L.partitionBy,L.orderBy),this},selectAll(){return this},select(X){if(!X)return this;let L=Array.isArray(X)?X:[X];if(L.length===0)return this;let V=L.map(I9),M=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(R),I=M?M[1]:"",k=R.indexOf(" FROM ");if(k!==-1)R=`SELECT ${I}${V.join(", ")}${R.substring(k)}`;else R=`SELECT ${I}${V.join(", ")} FROM ${j}`;return P=null,this},addSelect(...X){if(!X.length)return this;let L=X.map(I9),V=R.indexOf(" FROM ");if(V!==-1)R=`${R.substring(0,V)}, ${L.join(", ")}${R.substring(V)}`;else R+=`, ${L.join(", ")}`;return P=null,this},with(...X){if(!A||!X||X.length===0)return this;let L=[];for(let g of X){if(!g)continue;if(typeof g==="string")L.push({name:g});else if(typeof g==="object"&&!Array.isArray(g))for(let[m,l]of Object.entries(g))if(typeof l==="function")L.push({name:m,callback:l});else L.push({name:m})}if(L.length===0)return this;let V=v.relations.maxEagerLoad??50;if(L.length>V)throw Error(`[query-builder] Too many relationships to eager load (${L.length}). Maximum allowed: ${V}`);let M=String(j),I=new Set,k=new Set,b=new Map,c=(g)=>{let m=A.relations?.[g];if(!m)return[];return[...Object.keys(m.hasOne||{}),...Object.keys(m.hasMany||{}),...Object.keys(m.belongsTo||{}),...Object.keys(m.belongsToMany||{}),...Object.keys(m.hasOneThrough||{}),...Object.keys(m.hasManyThrough||{}),...Object.keys(m.morphOne||{}),...Object.keys(m.morphMany||{}),...Object.keys(m.morphToMany||{}),...Object.keys(m.morphedByMany||{})]},n=(g,m,l=0,H0)=>{let y0=v.relations.maxDepth??10;if(l>=y0)throw Error(`[query-builder] Maximum relationship depth (${y0}) exceeded at '${m}'. Consider using separate queries or increasing maxDepth.`);let e=A.relations?.[g];if(!e)return g;let q0=(U0)=>{if(v.softDeletes?.enabled&&v.softDeletes?.defaultFilter){let Y0=v.softDeletes.column||"deleted_at";return` AND ${U0}.${Y0} IS NULL`}return""},$$=(U0)=>{if(!H0)return"";let Y0=[],P0=(Z0,H$,N$)=>{i(String(Z0),"with() constraint column");let q1=g0(H$,"with() constraint operator");Y0.push(`${U0}.${String(Z0)} ${q1} ${p$(N$)}`)},M0=(Z0)=>()=>{throw Error(`[query-builder] with('${m}', ...): ${Z0} 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.)`)},T0={where:(Z0,H$,N$)=>{if(Array.isArray(Z0))P0(Z0[0],Z0[1],Z0[2]);else if(Z0&&typeof Z0==="object")for(let q1 of Object.keys(Z0))P0(q1,"=",Z0[q1]);else if(H$!==void 0&&N$!==void 0)P0(Z0,H$,N$);else if(H$!==void 0)P0(Z0,"=",H$);return T0},whereIn:(Z0,H$)=>{return i(String(Z0),"with() constraint column"),Y0.push(`${U0}.${String(Z0)} IN (${H$.map(p$).join(", ")})`),T0},whereNull:(Z0)=>{return i(String(Z0),"with() constraint column"),Y0.push(`${U0}.${String(Z0)} IS NULL`),T0},whereNotNull:(Z0)=>{return i(String(Z0),"with() constraint column"),Y0.push(`${U0}.${String(Z0)} IS NOT NULL`),T0},orderBy:M0("orderBy()"),limit:M0("limit()"),offset:M0("offset()"),take:M0("take()")};return H0(T0),Y0.length?` AND ${Y0.join(" AND ")}`:""},J$=()=>{let U0=(M0)=>{let T0=M0?.[m];return T0?A.modelToTable[T0]:void 0},Y0=(M0)=>{let T0=M0?.[m],Z0=typeof T0==="string"?T0:T0?.model;return Z0?A.modelToTable[Z0]:void 0},P0=(M0)=>{let T0=M0?.[m];return T0?.target?A.modelToTable[T0.target]:void 0};return U0(e?.hasOne)||U0(e?.hasMany)||U0(e?.belongsTo)||Y0(e?.belongsToMany)||P0(e?.hasOneThrough)||P0(e?.hasManyThrough)||U0(e?.morphOne)||U0(e?.morphMany)||U0(e?.morphToMany)||U0(e?.morphedByMany)},t0=J$()??(A.modelToTable[m]||A.tableToModel[m]?A.modelToTable[m]??m:m),E0=String(t0);if(!t0||!J$()&&!A.modelToTable[m]&&!A.tableToModel[m]){let U0=c(g);if(U0.length>0&&!U0.includes(m)){let Y0=` Available relationships: ${U0.join(", ")}`;throw Error(`[query-builder] Relationship '${m}' not found on table '${g}'.${Y0}`)}}if(v.relations.detectCycles!==!1){let U0=`${g}->${E0}`;if(I.has(U0))throw Error(`[query-builder] Circular relationship detected: ${U0}. This would cause an infinite loop.`);I.add(U0)}if(!E0||E0===g)return g;let qh=e?.hasOneThrough?.[m]||e?.hasManyThrough?.[m];if(qh){let{through:U0,target:Y0}=qh,P0=A.modelToTable[U0]||U0,M0=A.modelToTable[Y0]||Y0,T0=A.primaryKeys[g]??"id",Z0=A.primaryKeys[P0]??"id",H$=`${V0(g)}_id`,N$=`${V0(P0)}_id`;return q(`LEFT JOIN ${P0} ON ${P0}.${H$} = ${g}.${T0} LEFT JOIN ${M0} ON ${M0}.${N$} = ${P0}.${Z0}`),d.add(P0),d.add(M0),M0}if(Boolean(e?.belongsToMany?.[m])){let U0=Q1(A,g,m,{singularize:V0,models:A.models}),Y0=U0?.pivotTable??[V0(g),V0(E0)].sort().join("_"),P0=A.primaryKeys[g]??"id",M0=A.primaryKeys[E0]??"id",T0=U0?.fkParent??`${V0(g)}_id`,Z0=U0?.fkRelated??`${V0(E0)}_id`;return q(`LEFT JOIN ${Y0} ON ${Y0}.${T0} = ${g}.${P0} LEFT JOIN ${E0} ON ${E0}.${M0} = ${Y0}.${Z0}${$$(E0)}`),d.add(Y0),d.add(E0),E0}if(Boolean(e?.morphToMany?.[m])){let U0=m,Y0=`${V0(E0)}_${U0}`,P0=A.primaryKeys[g]??"id",M0=A.primaryKeys[E0]??"id",T0=`${U0}_type`,Z0=`${U0}_id`,H$=`${V0(E0)}_id`,N$=p$(A.tableToModel[g]||g);return q(`LEFT JOIN ${Y0} ON ${Y0}.${Z0} = ${g}.${P0} AND ${Y0}.${T0} = ${N$} LEFT JOIN ${E0} ON ${E0}.${M0} = ${Y0}.${H$}`),d.add(Y0),d.add(E0),E0}if(Boolean(e?.morphedByMany?.[m])){let U0=e.morphedByMany?.[m]||m,Y0=A.modelToTable[U0]||U0,P0=V0(g),M0=`${V0(Y0)}_${P0}`,T0=A.primaryKeys[g]??"id",Z0=A.primaryKeys[Y0]??"id",H$=`${P0}_type`,N$=`${P0}_id`,q1=`${V0(Y0)}_id`,Jz=p$(A.tableToModel[Y0]||Y0);return q(`LEFT JOIN ${M0} ON ${M0}.${q1} = ${g}.${T0} LEFT JOIN ${Y0} ON ${Y0}.${Z0} = ${M0}.${N$} AND ${M0}.${H$} = ${Jz}`),d.add(M0),d.add(Y0),Y0}if(Boolean(e?.belongsTo?.[m])){let U0=`${V0(E0)}_id`,Y0=A.primaryKeys[E0]??"id";return q(`LEFT JOIN ${E0} ON ${g}.${U0} = ${E0}.${Y0}${$$(E0)}`),d.add(E0),E0}let e8=Boolean(e?.morphOne?.[m]),$z=Boolean(e?.morphMany?.[m]);if(e8||$z){let U0=`${m}_type`,Y0=`${m}_id`,P0=A.primaryKeys[g]??"id",M0=p$(A.tableToModel[g]||g);return q(`LEFT JOIN ${E0} ON ${E0}.${Y0} = ${g}.${P0} AND ${E0}.${U0} = ${M0}`),d.add(E0),E0}let hz=`${V0(g)}_id`,Az=A.primaryKeys[g]??"id",Gz=`${q0(E0)}${$$(E0)}`;return q(`LEFT JOIN ${E0} ON ${E0}.${hz} = ${g}.${Az}${Gz}`),d.add(E0),E0};for(let g of L){let m=g.name.trim();if(g.callback)b.set(m,g.callback);let l=m.split("."),H0=M,y0=0;for(let e of l){if(!e||e.trim().length===0)continue;let q0=e.trim(),$$=b.get(q0);H0=n(H0,q0,y0,$$)||H0,y0++}k.add(m)}if(j0.size>0){let g=[];for(let[m,l]of j0.entries()){let H0=L$(m);if(!H0)continue;let y0=l.map((e)=>`${H0.pivotTable}.${e} AS pivot_${e}`);g.push(...y0)}if(g.length>0){let m=g.join(", ");yh(m)}}return P=null,this},whereHas(X,L){if(!A)return this;let V=String(j),M=A.relations?.[V];if(!M)throw Error(`[query-builder] No relationships defined for table '${V}'`);let I=Object.entries(M).find(([l,H0])=>H0&&typeof H0==="object"&&(X in H0));if(!I)throw Error(`[query-builder] Relationship '${X}' not found on table '${V}'`);let[k,b]=I,c=b[X],n=typeof c==="string"?c:c?.model||c?.target||c,g=A.modelToTable[n]||n,m;if(k==="hasMany"||k==="hasOne"){let l=A.primaryKeys[V]??"id";m=BA(V,g,l,L)}else if(k==="belongsTo"){let l=A.primaryKeys[g]??"id";m=IA(V,g,l,L)}else if(k==="belongsToMany"){let l=A.primaryKeys[V]??"id",H0=A.primaryKeys[g]??"id";m=PA(V,g,l,H0,L,X)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereHas`);return Q("WHERE",`EXISTS (${m})`),this},whereDoesntHave(X,L){if(!A)return this;let V=String(j),M=A.relations?.[V];if(!M)throw Error(`[query-builder] No relationships defined for table '${V}'`);let I=Object.entries(M).find(([l,H0])=>H0&&typeof H0==="object"&&(X in H0));if(!I)throw Error(`[query-builder] Relationship '${X}' not found on table '${V}'`);let[k,b]=I,c=b[X],n=typeof c==="string"?c:c?.model||c?.target||c,g=A.modelToTable[n]||n,m;if(k==="hasMany"||k==="hasOne"){let l=A.primaryKeys[V]??"id";m=BA(V,g,l,L)}else if(k==="belongsTo"){let l=A.primaryKeys[g]??"id";m=IA(V,g,l,L)}else if(k==="belongsToMany"){let l=A.primaryKeys[V]??"id",H0=A.primaryKeys[g]??"id";m=PA(V,g,l,H0,L,X)}else throw Error(`[query-builder] Unsupported relationship type '${k}' for whereDoesntHave`);return Q("WHERE",`NOT EXISTS (${m})`),this},has(X){if(!A)return this;let L=String(j),V=A.relations?.[L];if(!V)throw Error(`[query-builder] No relationships defined for table '${L}'`);let M=Object.entries(V).find(([m,l])=>l&&typeof l==="object"&&(X in l));if(!M)throw Error(`[query-builder] Relationship '${X}' not found on table '${L}'`);let[I,k]=M,b=k[X],c=typeof b==="string"?b:b?.model||b?.target||b,n=A.modelToTable[c]||c,g;if(I==="hasMany"||I==="hasOne"){let m=A.primaryKeys[L]??"id";g=BA(L,n,m)}else if(I==="belongsTo"){let m=A.primaryKeys[n]??"id";g=IA(L,n,m)}else if(I==="belongsToMany"){let m=A.primaryKeys[L]??"id",l=A.primaryKeys[n]??"id";g=PA(L,n,m,l,void 0,X)}else throw Error(`[query-builder] Unsupported relationship type '${I}' for has`);return Q("WHERE",`EXISTS (${g})`),this},doesntHave(X){if(!A)return this;let L=String(j),V=A.relations?.[L];if(!V)throw Error(`[query-builder] No relationships defined for table '${L}'`);let M=Object.entries(V).find(([m,l])=>l&&typeof l==="object"&&(X in l));if(!M)throw Error(`[query-builder] Relationship '${X}' not found on table '${L}'`);let[I,k]=M,b=k[X],c=typeof b==="string"?b:b?.model||b?.target||b,n=A.modelToTable[c]||c,g;if(I==="hasMany"||I==="hasOne"){let m=A.primaryKeys[L]??"id";g=BA(L,n,m)}else if(I==="belongsTo"){let m=A.primaryKeys[n]??"id";g=IA(L,n,m)}else if(I==="belongsToMany"){let m=A.primaryKeys[L]??"id",l=A.primaryKeys[n]??"id";g=PA(L,n,m,l,void 0,X)}else throw Error(`[query-builder] Unsupported relationship type '${I}' for doesntHave`);return Q("WHERE",`NOT EXISTS (${g})`),this},withCount(...X){if(!A||!X||X.length===0)return this;let L=String(j);for(let V of X){let M=A.relations?.[L];if(!M)continue;let I=Object.entries(M).find(([y0,e])=>e&&typeof e==="object"&&(V in e));if(!I)continue;let[k,b]=I,c=b[V],n=typeof c==="string"?c:c?.model||c?.target||c,g=A.modelToTable[n]||n,m=A.primaryKeys[L]??"id",l;if(k==="hasMany"||k==="hasOne")l=t8(L,g,m);else if(k==="belongsToMany")l=a8(L,g,m,V);else continue;let H0=`${V}_count`;yh(`${l} AS ${H0}`)}return this},withSum(X,L){return NA("SUM",X,L),this},withAvg(X,L){return NA("AVG",X,L),this},withMax(X,L){return NA("MAX",X,L),this},withMin(X,L){return NA("MIN",X,L),this},applyPivotColumns(){return VE(),this},withPivot(X,...L){if(!A)return this;let V=String(j),M=L$(X);if(!M)throw Error(`[query-builder] Relationship '${X}' is not a belongsToMany relationship on table '${V}'`);let I=L&&L.length>0?L:M.hasConfig?M.pivotColumns:[];if(I.length===0)return this;if(j0.set(X,I),M.hasConfig)e0.add(X);return VE(),this},wherePivot(X,L,V,M){if(!A)return this;let I=L$(X);if(!I)throw Error(`[query-builder] Relationship '${X}' is not a belongsToMany relationship on table '${String(j)}'`);i(I.pivotTable,"wherePivot (pivot table)"),i(L,"wherePivot (column)"),x$(I);let k=M===void 0?"=":String(V),b=M===void 0?V:M,c=D.length+1,n=`${I.pivotTable}.${L} ${k} ${r(c)}`;if(D.push(b),C("AND",n),I.hasConfig)e0.add(X);return this},wherePivotIn(X,L,V){if(!A||!Array.isArray(V))return this;let M=L$(X);if(!M)throw Error(`[query-builder] Relationship '${X}' is not a belongsToMany relationship on table '${String(j)}'`);i(M.pivotTable,"wherePivotIn (pivot table)"),i(L,"wherePivotIn (column)"),x$(M);let I=x0(V.length,D.length+1),k=W$(`${M.pivotTable}.${L}`,V,!1,I);if(D.push(...V),C("AND",k),M.hasConfig)e0.add(X);return this},wherePivotNotIn(X,L,V){if(!A||!Array.isArray(V)||V.length===0)return this;let M=L$(X);if(!M)throw Error(`[query-builder] Relationship '${X}' is not a belongsToMany relationship on table '${String(j)}'`);i(M.pivotTable,"wherePivotNotIn (pivot table)"),i(L,"wherePivotNotIn (column)"),x$(M);let I=x0(V.length,D.length+1),k=`${M.pivotTable}.${L} NOT IN (${I})`;if(D.push(...V),C("AND",k),M.hasConfig)e0.add(X);return this},wherePivotNull(X,L){if(!A)return this;let V=L$(X);if(!V)throw Error(`[query-builder] Relationship '${X}' is not a belongsToMany relationship on table '${String(j)}'`);if(i(V.pivotTable,"wherePivotNull (pivot table)"),i(L,"wherePivotNull (column)"),x$(V),C("AND",`${V.pivotTable}.${L} IS NULL`),V.hasConfig)e0.add(X);return this},wherePivotNotNull(X,L){if(!A)return this;let V=L$(X);if(!V)throw Error(`[query-builder] Relationship '${X}' is not a belongsToMany relationship on table '${String(j)}'`);if(i(V.pivotTable,"wherePivotNotNull (pivot table)"),i(L,"wherePivotNotNull (column)"),x$(V),C("AND",`${V.pivotTable}.${L} IS NOT NULL`),V.hasConfig)e0.add(X);return this},where(X,L,V){if(typeof X==="string"&&L!==void 0){i(String(X),"where(column)"),g0(L,"where(operator)");let M=String(L).toLowerCase();if(M==="in"||M==="not in"){let k=Array.isArray(V)?V:[V],b=x0(k.length,D.length+1),c=W$(String(X),k,M==="not in",b);return D.push(...k),C("AND",c),this}let I=D.length+1;return D.push(V),C("AND",`${String(X)} ${String(L)} ${r(I)}`),this}if(Array.isArray(X)){let[M,I,k]=X,b=String(M);i(b,"where(column)");let c=g0(I,"where(operator)");if(c==="in"||c==="not in"){let n=Array.isArray(k)?k:[k],g=x0(n.length,D.length+1),m=W$(b,n,c==="not in",g);D.push(...n),C("AND",m)}else{let n=D.length+1;D.push(k),C("AND",`${b} ${c} ${r(n)}`)}return this}if(X&&typeof X==="object"&&!n$(X)){let M=X,I=Object.keys(M),k=[];for(let b of I){i(b,"where(column)");let c=M[b];if(Array.isArray(c)){let n=x0(c.length,D.length+1);k.push(W$(b,c,!1,n)),D.push(...c)}else{let n=D.length+1;k.push(`${b} = ${r(n)}`),D.push(c)}}if(k.length>0)C("AND",k.length>1?`(${k.join(" AND ")})`:k[0]);return this}if(n$(X))return C("AND",X.raw),this;if(typeof X==="function")return p("AND",X),this;if(X===void 0||X===null)throw TypeError("where() was called with no condition.");if(typeof X==="string")throw TypeError(`where(${JSON.stringify(X)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof X}.`)},whereNull(X){return i(String(X),"whereNull(column)"),C("AND",`${String(X)} IS NULL`),this},whereNotNull(X){return i(String(X),"whereNotNull(column)"),C("AND",`${String(X)} IS NOT NULL`),this},orWhereNull(X){return i(String(X),"orWhereNull(column)"),C("OR",`${String(X)} IS NULL`),this},orWhereNotNull(X){return i(String(X),"orWhereNotNull(column)"),C("OR",`${String(X)} IS NOT NULL`),this},whereBetween(X,L,V){i(String(X),"whereBetween(column)");let M=D.length+1;return D.push(L,V),C("AND",`${String(X)} BETWEEN ${r(M)} AND ${r(M+1)}`),this},orWhereBetween(X,L,V){i(String(X),"orWhereBetween(column)");let M=D.length+1;return D.push(L,V),C("OR",`${String(X)} BETWEEN ${r(M)} AND ${r(M+1)}`),this},whereExists(X){return C("AND",`EXISTS (${X.toSQL()})`),this},orWhereExists(X){return C("OR",`EXISTS (${X.toSQL()})`),this},whereGroup(X){return p("AND",X),this},orWhereGroup(X){return p("OR",X),this},__whereState(){return{body:C1(S),params:[...D]}},whereJsonContains(X,L){i(String(X),"whereJsonContains(column)");let V=v.dialect,M=D.length+1;if(V==="postgres"){let k=typeof L==="number"||typeof L==="boolean"?`to_jsonb(${r(M)})`:r(M);if(v.sql?.jsonContainsMode==="function")C("AND",`jsonb_contains(${X}, ${k})`);else C("AND",`${X} @> ${k}`);D.push(L)}else if(G0(V))C("AND",`JSON_CONTAINS(${X}, ${r(M)})`),D.push(JSON.stringify(L));else if(Array.isArray(L)){let I=L.map((k,b)=>`EXISTS (SELECT 1 FROM json_each(${X}) WHERE json_each.value = ${r(M+b)})`);C("AND",`(${I.join(" AND ")})`);for(let k of L)D.push(k)}else if(L!==null&&typeof L==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else C("AND",`EXISTS (SELECT 1 FROM json_each(${X}) WHERE json_each.value = ${r(M)})`),D.push(L);return this},whereJsonPath(X,L,V){if(g0(L,"whereJsonPath(op)"),typeof X!=="string"||X.length===0||X.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof X==="string"?`'${X.slice(0,32)}...'`:typeof X}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(X))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${X}' \u2014 contains characters outside the allowed JSON-path set`);let M=v.dialect,I=D.length+1;if(M==="postgres")C("AND",`${X} ${L} ${r(I)}`);else if(G0(M))C("AND",`JSON_EXTRACT(${X}) ${L} ${r(I)}`);else C("AND",`json_extract(${X}) ${L} ${r(I)}`);return D.push(V),this},whereLike(X,L,V=!1){let M=r(D.length+1);return Q("WHERE",`${V?String(X):`LOWER(${String(X)})`} LIKE ${V?M:`LOWER(${M})`}`),D.push(L),P=null,this},whereILike(X,L){let V=r(D.length+1);if(v.dialect==="postgres")Q("WHERE",`${String(X)} ILIKE ${V}`);else Q("WHERE",`LOWER(${String(X)}) LIKE LOWER(${V})`);return D.push(L),P=null,this},orWhereLike(X,L,V=!1){let M=r(D.length+1);return Q("OR",`${V?String(X):`LOWER(${String(X)})`} LIKE ${V?M:`LOWER(${M})`}`),D.push(L),P=null,this},orWhereILike(X,L){let V=r(D.length+1);if(v.dialect==="postgres")Q("OR",`${String(X)} ILIKE ${V}`);else Q("OR",`LOWER(${String(X)}) LIKE LOWER(${V})`);return D.push(L),P=null,this},whereNotLike(X,L,V=!1){let M=r(D.length+1);return Q("WHERE",`${V?String(X):`LOWER(${String(X)})`} NOT LIKE ${V?M:`LOWER(${M})`}`),D.push(L),P=null,this},whereNotILike(X,L){let V=r(D.length+1);if(v.dialect==="postgres")Q("WHERE",`${String(X)} NOT ILIKE ${V}`);else Q("WHERE",`LOWER(${String(X)}) NOT LIKE LOWER(${V})`);return D.push(L),P=null,this},orWhereNotLike(X,L,V=!1){let M=r(D.length+1);return Q("OR",`${V?String(X):`LOWER(${String(X)})`} NOT LIKE ${V?M:`LOWER(${M})`}`),D.push(L),P=null,this},orWhereNotILike(X,L){let V=r(D.length+1);if(v.dialect==="postgres")Q("OR",`${String(X)} NOT ILIKE ${V}`);else Q("OR",`LOWER(${String(X)}) NOT LIKE LOWER(${V})`);return D.push(L),P=null,this},whereAny(X,L,V){if(X.length===0)return C("AND",`(${B9})`),this;let M=D.length+1,I=X.map((k,b)=>`${k} ${L} ${r(M+b)}`);for(let k=0;k<X.length;k++)D.push(V);return C("AND",`(${I.join(" OR ")})`),this},whereAll(X,L,V){if(X.length===0)return this;let M=D.length+1,I=X.map((k,b)=>`${k} ${L} ${r(M+b)}`);for(let k=0;k<X.length;k++)D.push(V);return C("AND",`(${I.join(" AND ")})`),this},whereNone(X,L,V){if(X.length===0)return this;let M=D.length+1,I=X.map((k,b)=>`${k} ${L} ${r(M+b)}`);for(let k=0;k<X.length;k++)D.push(V);return C("AND",`NOT (${I.join(" OR ")})`),this},whereNotBetween(X,L,V){i(String(X),"whereNotBetween(column)");let M=D.length+1;return D.push(L,V),C("AND",`${X} NOT BETWEEN ${r(M)} AND ${r(M+1)}`),this},whereDate(X,L,V){i(X,"whereDate(column)");let M=V instanceof Date?V.toISOString():typeof V==="string"?V:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof V}`)})(),I=D.length+1;return D.push(M),C("AND",`${X} ${L} ${r(I)}`),this},whereRaw(X){return C("AND",K1(X,"whereRaw(fragment)")),this},orWhereRaw(X){return C("OR",K1(X,"orWhereRaw(fragment)")),this},whereColumn(X,L,V){return i(X,"whereColumn(left)"),i(V,"whereColumn(right)"),C("AND",`${X} ${L} ${V}`),this},orWhereColumn(X,L,V){return i(X,"orWhereColumn(left)"),i(V,"orWhereColumn(right)"),C("OR",`${X} ${L} ${V}`),this},whereIn(X,L){if(i(String(X),"whereIn(column)"),Array.isArray(L)){let V=x0(L.length,D.length+1),M=W$(X,L,!1,V);D.push(...L),C("AND",M)}else C("AND",`${X} IN (${String(L.toSQL())})`);return this},orWhereIn(X,L){if(i(String(X),"orWhereIn(column)"),Array.isArray(L)){let V=x0(L.length,D.length+1),M=W$(X,L,!1,V);D.push(...L),C("OR",M)}else C("OR",`${X} IN (${String(L.toSQL())})`);return this},whereNotIn(X,L){if(i(String(X),"whereNotIn(column)"),Array.isArray(L)){let V=x0(L.length,D.length+1),M=W$(X,L,!0,V);D.push(...L),C("AND",M)}else C("AND",`${X} NOT IN (${String(L.toSQL())})`);return this},orWhereNotIn(X,L){if(i(String(X),"orWhereNotIn(column)"),Array.isArray(L)){let V=x0(L.length,D.length+1),M=W$(X,L,!0,V);D.push(...L),C("OR",M)}else C("OR",`${X} NOT IN (${String(L.toSQL())})`);return this},whereNested(X){let L=X.toSQL?String(X.toSQL()):String(X);return C("AND",`(${L})`),this},orWhereNested(X){let L=X.toSQL?String(X.toSQL()):String(X);return C("OR",`(${L})`),this},andWhere(X,L,V){return s(this,"AND","andWhere",X,L,V)},orWhere(X,L,V){return s(this,"OR","orWhere",X,L,V)},orderBy(X,L="asc"){let V=L==="asc"?"ASC":"DESC";return R=X0.ORDER_BY.test(R)?`${R}, ${X} ${V}`:`${R} ORDER BY ${X} ${V}`,P=null,this},orderByDesc(X){return R=X0.ORDER_BY.test(R)?`${R}, ${X} DESC`:`${R} ORDER BY ${X} DESC`,P=null,this},inRandomOrder(){let X=v.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return R=X0.ORDER_BY.test(R)?`${R}, ${X}`:`${R} ORDER BY ${X}`,P=null,this},reorder(X,L="asc"){return R=R.replace(/ORDER BY[\s\S]*$/i,""),R+=` ORDER BY ${X} ${L==="asc"?"ASC":"DESC"}`,P=null,this},latest(X){let L=X??v.timestamps.defaultOrderColumn;return R=X0.ORDER_BY.test(R)?`${R}, ${L} DESC`:`${R} ORDER BY ${L} DESC`,P=null,this},oldest(X){let L=X??v.timestamps.defaultOrderColumn;return R=X0.ORDER_BY.test(R)?`${R}, ${L} ASC`:`${R} ORDER BY ${L} ASC`,P=null,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 R=X0.LIMIT.test(R)?R.replace(X0.LIMIT,` LIMIT ${X}`):`${R} LIMIT ${X}`,P=null,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 R=X0.OFFSET.test(R)?R.replace(X0.OFFSET,` OFFSET ${X}`):`${R} OFFSET ${X}`,P=null,this},join(X,L,V,M){return i(X,"join(table)"),_$(L,"join(onLeft)"),_$(M,"join(onRight)"),g0(V,"join(operator)"),q(`JOIN ${X} ON ${L} ${V} ${M}`),d.add(X),this},joinSub(X,L,V,M,I){return i(L,"joinSub(alias)"),_$(V,"joinSub(onLeft)"),_$(I,"joinSub(onRight)"),g0(M,"joinSub(operator)"),q(`JOIN (${String(X.toSQL())}) AS ${L} ON ${V} ${M} ${I}`),d.add(L),this},innerJoin(X,L,V,M){return i(X,"innerJoin(table)"),_$(L,"innerJoin(onLeft)"),_$(M,"innerJoin(onRight)"),g0(V,"innerJoin(operator)"),q(`INNER JOIN ${X} ON ${L} ${V} ${M}`),d.add(X),this},leftJoin(X,L,V,M){return i(X,"leftJoin(table)"),_$(L,"leftJoin(onLeft)"),_$(M,"leftJoin(onRight)"),g0(V,"leftJoin(operator)"),q(`LEFT JOIN ${X} ON ${L} ${V} ${M}`),d.add(X),this},leftJoinSub(X,L,V,M,I){return i(L,"leftJoinSub(alias)"),_$(V,"leftJoinSub(onLeft)"),_$(I,"leftJoinSub(onRight)"),g0(M,"leftJoinSub(operator)"),q(`LEFT JOIN (${String(X.toSQL())}) AS ${L} ON ${V} ${M} ${I}`),d.add(L),this},rightJoin(X,L,V,M){return i(X,"rightJoin(table)"),_$(L,"rightJoin(onLeft)"),_$(M,"rightJoin(onRight)"),g0(V,"rightJoin(operator)"),q(`RIGHT JOIN ${X} ON ${L} ${V} ${M}`),d.add(X),this},crossJoin(X){return i(X,"crossJoin(table)"),q(`CROSS JOIN ${X}`),d.add(X),this},crossJoinSub(X,L){return i(L,"crossJoinSub(alias)"),q(`CROSS JOIN (${String(X.toSQL())}) AS ${L}`),d.add(L),this},selectAllRelations(){if(!G)return this;let X=String(j),L=Object.keys(G[X]?.columns??{}),V=[];if(L.length>0)V.push(_`${_(X)}.*`);for(let M of d){let I=Object.keys(G[M]?.columns??{});for(let k of I){let b=v.aliasing.relationColumnAliasFormat==="camelCase"?`${M}_${k}`.replace(/_([a-z])/g,(c,n)=>n.toUpperCase()):v.aliasing.relationColumnAliasFormat==="table.dot.column"?`${M}.${k}`:`${M}_${k}`;V.push(_`${_(`${M}.${k}`)} AS ${_(b)}`)}}if(V.length>0){let M=L.length>0?`${X}.*`:"",I=[];for(let c of d){let n=Object.keys(G[c]?.columns??{});for(let g of n){let m=v.aliasing.relationColumnAliasFormat==="camelCase"?`${c}_${g}`.replace(/_([a-z])/g,(l,H0)=>H0.toUpperCase()):v.aliasing.relationColumnAliasFormat==="table.dot.column"?`${c}.${g}`:`${c}_${g}`;I.push(`${c}.${g} AS ${m}`)}}let k=[M,...I].filter(Boolean).join(", "),b=R.indexOf(" FROM ");if(b!==-1)R=`SELECT ${k}${R.substring(b)}`;else R=`SELECT ${k} FROM ${X}`;P=null}return this},groupBy(...X){if(X.length)R=X0.GROUP_BY.test(R)?`${R}, ${X.join(", ")}`:`${R} GROUP BY ${X.join(", ")}`,P=null;return this},groupByRaw(X){let L=K1(X,"groupByRaw(fragment)");return R=X0.GROUP_BY.test(R)?`${R}, ${L}`:`${R} GROUP BY ${L}`,P=null,this},having(X){let L=/\bHAVING\b/i.test(R)?"AND":"HAVING";if(Array.isArray(X)){let V=D.length+1;R=`${R} ${L} ${X[0]} ${X[1]} ${r(V)}`,D.push(X[2]),P=null}else if(X&&typeof X==="object"&&!("raw"in X)){let V=Object.keys(X),M=V.length;if(M){let I=D.length,k=Array.from({length:M});for(let b=0;b<M;b++){let c=V[b];k[b]=`${c} = ${r(I+b+1)}`,D.push(X[c])}R=`${R} ${L} ${k.join(" AND ")}`,P=null}}else if(X&&typeof X.raw<"u")R+=` ${L} ${X.raw}`,P=null;return this},havingRaw(X){let L=K1(X,"havingRaw(fragment)"),V=/\bHAVING\b/i.test(R)?"AND":"HAVING";return R+=` ${V} ${L}`,P=null,this},orderByRaw(X){let L=K1(X,"orderByRaw(fragment)");return R=X0.ORDER_BY.test(R)?`${R}, ${L}`:`${R} ORDER BY ${L}`,P=null,this},$call(X){return X(this),this},union(X){return o("UNION",X),this},unionAll(X){return o("UNION ALL",X),this},intersect(X){return o("INTERSECT",X),this},intersectAll(X){return o("INTERSECT ALL",X),this},except(X){return o("EXCEPT",X),this},exceptAll(X){return o("EXCEPT ALL",X),this},forPage(X,L){let V=Math.max(1,Math.floor(X)),M=Math.max(1,Math.floor(L));return R+=` LIMIT ${M} OFFSET ${(V-1)*M}`,P=null,this},toSQL(){let X=lh(x());return{sql:X,toString:()=>X,execute:()=>T().execute(),values:()=>T().values(),raw:()=>T().raw()}},async value(X){let L=_`${T()} LIMIT 1`,V=await Z(L,"select",{signal:f,timeoutMs:u}),[M]=V;return M?.[X]},async pluck(X,L){let V=await Z(T(),"select",{signal:f,timeoutMs:u});if(L){let M={};for(let I of V){let k=String(I?.[L]);if(Object.prototype.hasOwnProperty.call(M,k))throw Error(`[query-builder] pluck(${X}, ${L}): duplicate key '${k}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);M[k]=I?.[X]}return M}return V.map((M)=>M?.[X])},async exists(){let X=_`SELECT EXISTS (${T()}) as e`,L=await Z(X,"select",{signal:f,timeoutMs:u}),[V]=L;return Boolean(V?.e)},async doesntExist(){return!await this.exists()},async paginate(X,L=1,V={}){if(!Number.isFinite(X)||X<=0||!Number.isInteger(X))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${X}`);if(!Number.isFinite(L)||L<1||!Number.isInteger(L))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${L}`);if(V.tx){let l=lh(x()),H0=[...D],y0=await V.tx.unsafe(`SELECT COUNT(*) as c FROM (${l}) as sub`,H0),e=Number(y0?.[0]?.c??0),q0=Math.max(1,Math.ceil(e/X)),$$=Math.max(1,Math.min(L,q0)),J$=($$-1)*X;return{data:await V.tx.unsafe(`${l} LIMIT ${X} OFFSET ${J$}`,H0),meta:{perPage:X,page:$$,total:e,lastPage:q0}}}let M=_`SELECT COUNT(*) as c FROM (${T()}) as sub`,I=await Z(M,"select",{signal:f,timeoutMs:u}),[k]=I,b=Number(k?.c??0),c=Math.max(1,Math.ceil(b/X)),n=Math.max(1,Math.min(L,c)),g=(n-1)*X;return{data:await Z(_`${T()} LIMIT ${X} OFFSET ${g}`,"select",{signal:f,timeoutMs:u}),meta:{perPage:X,page:n,total:b,lastPage:c}}},async simplePaginate(X,L=1){let V=Math.max(1,L),M=(V-1)*X,I=await Z(_`${T()} LIMIT ${X+1} OFFSET ${M}`,"select",{signal:f,timeoutMs:u}),k=I.length>X;return{data:k?I.slice(0,X):I,meta:{perPage:X,page:V,hasMore:k}}},async cursorPaginate(X,L,V="id",M="asc"){if(!Number.isInteger(X)||X<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${X}`);let I=(Array.isArray(V)?V:[V]).map(String);for(let t0 of I)i(t0,"cursorPaginate(column)");let k=M==="asc"?">":"<",b=M==="asc"?"ASC":"DESC",c=[...D],n="";if(L!==void 0&&L!==null)if(Array.isArray(V)){let t0=L.map((E0)=>{return c.push(E0),r(c.length)});n=`(${I.join(", ")}) ${k} (${t0.join(", ")})`}else c.push(L),n=`${I[0]} ${k} ${r(c.length)}`;let g=lh(n?x({conn:"AND",sql:n}):x()),m=I.map((t0)=>`${t0} ${b}`).join(", ");if(oW(g))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${m} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let l=c.length>0?h.unsafe(`${g} ORDER BY ${m} LIMIT ${X+1}`,c):h.unsafe(`${g} ORDER BY ${m} LIMIT ${X+1}`),H0=await Z(l,"select",{signal:f,timeoutMs:u}),y0=H0.length>X,e=H0.slice(0,X),q0=e[e.length-1],$$=y0&&q0?Array.isArray(V)?V.map((t0)=>q0[t0]):q0[V]:null,J$=e.length?Array.isArray(V)?V.map((t0)=>e[0]?.[t0]):e[0]?.[V]:null;return{data:e,meta:{perPage:X,nextCursor:$$??null,prevCursor:J$}}},async chunk(X,L){let V=1;while(!0){let{data:M,meta:I}=await this.paginate(X,V);if(M.length===0)break;if(await L(M),V>=I.lastPage)break;V+=1}},async chunkById(X,L="id",V){let M;while(!0){let{data:I,meta:k}=await this.cursorPaginate(X,M,L,"asc");if(I.length===0)break;if(V)await V(I);if(M=k.nextCursor,!M)break}},async eachById(X,L="id",V){await this.chunkById(X,L,async(M)=>{for(let I of M)await V?.(I)})},withTimeout(X){return u=Math.max(1,Math.floor(X)),this},abort(X){return f=X,this},withTrashed(){return h0=!0,t=!1,this},onlyTrashed(){h0=!0,t=!0;let X=v.softDeletes?.column||"deleted_at",L=(I,k)=>{let b=I.toUpperCase(),c=0;for(let n=0;n<I.length;n++){let g=I[n];if(g==="(")c++;else if(g===")")c--;else if(c===0&&b.substring(n,n+5)==="WHERE"&&(n===0||/\s/.test(I[n-1]??""))&&/\s/.test(I[n+5]??""))return`${I.substring(0,n)}WHERE ${k} AND ${I.substring(n+6)}`}return`${I} WHERE ${k}`},V=`${j}.${X} IS NOT NULL`;R=L(R,V);let M=String(T());return P=_([L(M,V)]),this},scope(X,L){let V=String(j),I=A?.scopes?.[V]?.[X];if(I)return I(this,L);return this},when(X,L,V){if(X)return L(this);if(V)return V(this);return this},tap(X){return X(this),this},dump(){return console.log(String(T())),this},dd(){throw console.log(String(T())),Error("Dump and Die")},cache(X=60000){return A1=X,K0=!0,this},async explain(){let X=_`EXPLAIN ${T()}`;return await Z(X,"select",{signal:f,timeoutMs:u})},simple(){return T().simple()},toText(){return x()},async get(){let X=H(),L=X&&(X.onQueryStart||X.onQueryEnd||X.onQueryError||X.startSpan||rh(X));if(!v.softDeletes?.enabled&&!K0&&!u&&!f&&!L){let b=h._prepareStatement;if(b){let c=b(x());return _1(D.length>0?c.all(...D):c.all())}}let V=x();if(P=D.length>0?h.unsafe(V,D):h.unsafe(V),!v.softDeletes?.enabled&&!K0&&!u&&!f&&!L){let b=T()._stmt,c=T()._params;if(b)return _1(c&&c.length>0?b.all(...c):b.all());return _1(await T().execute())}if(!v.softDeletes?.enabled&&!K0&&!u&&!f)return _1(await Z(T(),"select"));let M=T();if(v.softDeletes?.enabled&&v.softDeletes.defaultFilter&&!h0){let b=v.softDeletes.column,c=String(j);if((G?Boolean(G[c]?.columns?.[b]):!0)&&!X0.DELETED_AT.test(x()))Q("WHERE",`${String(b)} IS ${t?"NOT ":""}NULL`),M=T()}let I=K0?`${String(M)}\x00${JSON.stringify(D)}`:"";if(K0){let b=BG.get(I);if(b)return b}let k=await Z(M,"select",{signal:f,timeoutMs:u});if(K0)BG.set(I,k,A1);return _1(k)},async executeTakeFirst(){let X=await Z(T(),"select",{signal:f,timeoutMs:u});return w1(Array.isArray(X)?X[0]:X)},async executeTakeFirstOrThrow(){let X=await this.executeTakeFirst();if(!X)throw Error("Record not found");return X},async first(){let X=H(),L=X&&(X.onQueryStart||X.onQueryEnd||X.onQueryError||X.startSpan||rh(X));if(!v.softDeletes?.enabled&&!K0&&!u&&!f&&!L){let I=h._prepareStatement;if(I){let k=x(),b=k.includes(" LIMIT ")?k:`${k} LIMIT 1`,c=I(b),n=D.length>0?c.all(...D):c.all();return w1(n[0])}}let V=await Z(_`${T()} LIMIT 1`,"select",{signal:f,timeoutMs:u}),[M]=V;return w1(M)},async firstOrFail(){let X=await this.first();if(!X)throw Error("Record not found");return X},async find(X){let L=A?.primaryKeys[String(j)]??"id",V=await Z(_`${T()} WHERE ${_(L)} = ${X} LIMIT 1`,"select",{signal:f,timeoutMs:u}),[M]=V;return M},async findOrFail(X){let L=await this.find(X);if(!L)throw Error("Record not found");return L},async findMany(X){let L=A?.primaryKeys[String(j)]??"id";return await Z(_`${T()} WHERE ${_(String(L))} IN ${_(X)}`,"select",{signal:f,timeoutMs:u})},async*lazy(){let X,L=A?.primaryKeys[String(j)]??"id";while(!0){let M=await(X==null?_`${T()} ORDER BY ${_(String(L))} ASC LIMIT 100`:_`${T()} WHERE ${_(String(L))} > ${X} ORDER BY ${_(String(L))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let I of M)yield I;if(X=M[M.length-1]?.[L],X==null)break}},async*lazyById(){let X=A?.primaryKeys[String(j)]??"id",L;while(!0){let M=await(L==null?_`${T()} ORDER BY ${_(String(X))} ASC LIMIT 100`:_`${T()} WHERE ${_(String(X))} > ${L} ORDER BY ${_(String(X))} ASC LIMIT 100`).execute();if(M.length===0)break;for(let I of M)yield I;if(L=M[M.length-1]?.[X],L==null)break}},pipe(X){return X(this)},async count(){let X=x(),L=X.indexOf(" FROM "),V=/ GROUP BY /i.test(X),M;if(V)M=`SELECT COUNT(*) as c FROM (${X}) AS _bqb_count_sub`;else if(L!==-1)M=`SELECT COUNT(*) as c${X.substring(L)}`;else M=`SELECT COUNT(*) as c FROM ${j}`;let I=H(),k=I&&(I.onQueryStart||I.onQueryEnd||I.onQueryError||I.startSpan||rh(I));if(!v.softDeletes?.enabled&&!K0&&!u&&!f&&!k){let g=h._prepareStatement;if(g){let m=g(M),l=D.length>0?m.all(...D):m.all();return Number(l[0]?.c??0)}}let b=D.length>0?h.unsafe(M,D):h.unsafe(M),c=await Z(b,"select",{signal:f,timeoutMs:u}),[n]=c;return Number(n?.c??0)},async avg(X){let L=x(),V=L.indexOf(" FROM "),M=V!==-1?`SELECT AVG(${X}) as a${L.substring(V)}`:`SELECT AVG(${X}) as a FROM ${j}`,I=H(),k=I&&(I.onQueryStart||I.onQueryEnd||I.onQueryError||I.startSpan||rh(I));if(!v.softDeletes?.enabled&&!K0&&!u&&!f&&!k){let g=h._prepareStatement;if(g){let m=g(M),l=D.length>0?m.all(...D):m.all();return Number(l[0]?.a??0)}}let b=D.length>0?h.unsafe(M,D):h.unsafe(M),c=await Z(b,"select",{signal:f,timeoutMs:u}),[n]=c;return Number(n?.a??0)},async sum(X){let L=x(),V=L.indexOf(" FROM "),M=V!==-1?`SELECT SUM(${X}) as s${L.substring(V)}`:`SELECT SUM(${X}) as s FROM ${j}`,I=D.length>0?h.unsafe(M,D):h.unsafe(M),k=await Z(I,"select",{signal:f,timeoutMs:u}),[b]=k;return Number(b?.s??0)},async max(X){let L=x(),V=L.indexOf(" FROM "),M=V!==-1?`SELECT MAX(${X}) as m${L.substring(V)}`:`SELECT MAX(${X}) as m FROM ${j}`,I=D.length>0?h.unsafe(M,D):h.unsafe(M),k=await Z(I,"select",{signal:f,timeoutMs:u}),[b]=k;return b?.m},async min(X){let L=x(),V=L.indexOf(" FROM "),M=V!==-1?`SELECT MIN(${X}) as m${L.substring(V)}`:`SELECT MIN(${X}) as m FROM ${j}`,I=D.length>0?h.unsafe(M,D):h.unsafe(M),k=await Z(I,"select",{signal:f,timeoutMs:u}),[b]=k;return b?.m},lockForUpdate(){return R+=" FOR UPDATE",P=null,this},sharedLock(){let X=v.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return R+=` ${X}`,P=null,this},withCTE(X,L){return i(X,"withCTE(name)"),R=`WITH ${X} AS (${String(L.toSQL())}) ${R}`,P=null,this},withRecursive(X,L){return i(X,"withRecursive(name)"),R=`WITH RECURSIVE ${X} AS (${String(L.toSQL())}) ${R}`,P=null,this},execute(){return Z(T(),"select",{signal:f,timeoutMs:u})},values(){return T().values()},toParams(){return[...D]},__rawState(){return{sql:lh(x()),params:[...D]}},raw(){return T().raw()},get rows(){return},get row(){return},cancel(){try{T().cancel()}catch{}}},{get(X,L,V){let M=Reflect.get(X,L,V);if(M!==void 0)return M;if(typeof L==="string"&&(L.startsWith("where")||L.startsWith("orWhere")||L.startsWith("andWhere"))){let I=L.startsWith("orWhere"),k=L.startsWith("andWhere"),b=`${String(j)}|${L}`,c=E.get(b);if(c===void 0){let g=L.replace(/^(?:or|and)?where/i,"");if(!g)E.set(b,""),c="";else{let m=g.charAt(0).toLowerCase()+g.slice(1),l=g.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),H0=G?Object.keys(G[String(j)]?.columns??{}):[];c=[l,m,m.toLowerCase()].find((y0)=>H0.includes(y0))??l,E.set(b,c)}}if(c==="")return()=>V;let n=c;return(g)=>{if(Array.isArray(g)){let m=x0(g.length,D.length+1);Q(I?"OR":k?"AND":"WHERE",`${n} IN (${m})`),D.push(...g)}else{let m=r(D.length+1);Q(I?"OR":k?"AND":"WHERE",`${n} = ${m}`),D.push(g)}return V}}return Reflect.get(X,L,V)}})}return{configure(j){return R9(j),this},id(j){if(!X0.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 h(String(j))},ids(...j){for(let O of j)if(!X0.IDENTIFIER.test(O))throw Error(`[query-builder] Invalid identifier: '${O}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return h(j)},select(j,...O){return B(j,O)},selectFrom(j){return B(j)},selectFromSub(j,O){function _(Q){return()=>{throw Error(`[query-builder] selectFromSub(...).${Q}() is not supported. Apply ${Q}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}i(String(O),"selectFromSub(alias)");let R=typeof j.__rawState==="function"?j.__rawState():null,S=j.toSQL(),D=R?.sql??(typeof S==="string"?S:S?.sql??String(S)),y=R?.params??(Array.isArray(S?.values)?S.values:[]),P=`SELECT * FROM (${D}) AS ${String(O)}`,T=(Q,N,K,x)=>{let p=[...Q],s=(q,d,u)=>{i(q,"selectFromSub where(column)");let f=g0(d,"selectFromSub where(operator)");if(f==="in"||f==="not in"){let t=Array.isArray(u)?u:[u],K0=x0(t.length,p.length+1);return p.push(...t),`${q} ${f.toUpperCase()} (${K0})`}let h0=r(p.length+1);return p.push(u),`${q} ${f} ${h0}`},o;if(typeof N==="string"&&K!==void 0)o=s(N,K,x);else if(Array.isArray(N)&&N.length===3)o=s(N[0],N[1],N[2]);else if(N&&typeof N==="object"){let q=Object.entries(N).map(([d,u])=>s(d,"=",u));o=q.length>1?`(${q.join(" AND ")})`:q[0]}else return{clause:null,params:Q};return{clause:o,params:p}};function C(Q,N,K,x=""){let p=C1(N),s=p?`${Q} WHERE ${p}${x}`:`${Q}${x}`,o=()=>K.length>0?h.unsafe(s,K):h.unsafe(s),q=(f,h0,t,K0)=>{let j0=T(K,h0,t,K0);return j0.clause===null?C(Q,N,K,x):C(Q,[...N,{conn:f,sql:j0.clause}],j0.params,x)},d=(f,h0)=>{let t=[],K0=[...K],j0=(V0)=>(L$,w1,_1)=>{let x$=T(K0,L$,w1,_1);if(x$.clause!==null)t.push({conn:V0,sql:x$.clause}),K0=x$.params;return e0},e0={where:j0("AND"),andWhere:j0("AND"),orWhere:j0("OR")};h0(e0);let A1=C1(t);if(!A1)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return C(Q,[...N,{conn:f,sql:`(${A1})`}],K0,x)},u={distinct(){return C(Q.replace(/^SELECT\s+/i,"SELECT DISTINCT "),N,K,x)},distinctOn(...f){let h0=f.map(String).join(", ");return C(Q.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${h0}) `),N,K,x)},selectRaw(f){let h0=K1(f,"selectFromSub.selectRaw(fragment)"),t=Q.indexOf(" FROM "),K0=t!==-1?`${Q.slice(0,t)}, ${h0}${Q.slice(t)}`:`${Q}, ${h0}`;return C(K0,N,K,x)},$call(f){return f(this)??this},where(f,h0,t){return q("AND",f,h0,t)},andWhere(f,h0,t){return q("AND",f,h0,t)},orWhere(f,h0,t){return q("OR",f,h0,t)},whereGroup(f){return d("AND",f)},orWhereGroup(f){return d("OR",f)},orderBy(f,h0="asc"){i(String(f),"selectFromSub.orderBy(column)");let t=h0==="asc"?"ASC":"DESC",K0=X0.ORDER_BY.test(x)?`${x}, ${f} ${t}`:`${x} ORDER BY ${f} ${t}`;return C(Q,N,K,K0)},limit(f){if(!Number.isInteger(f)||f<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${f}`);let h0=X0.LIMIT.test(x)?x.replace(X0.LIMIT,` LIMIT ${f}`):`${x} LIMIT ${f}`;return C(Q,N,K,h0)},offset(f){if(!Number.isInteger(f)||f<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${f}`);let h0=X0.OFFSET.test(x)?x.replace(X0.OFFSET,` OFFSET ${f}`):`${x} OFFSET ${f}`;return C(Q,N,K,h0)},toSQL(){return w(o(),s)},async execute(){return Z(o(),"select")},async executeTakeFirst(){let f=await Z(o(),"select");return Array.isArray(f)?f[0]:f},async executeTakeFirstOrThrow(){let f=await Z(o(),"select"),h0=Array.isArray(f)?f[0]:f;if(!h0)throw Error("Record not found");return h0},async get(){return Z(o(),"select")},async first(){let f=await Z(o(),"select");return Array.isArray(f)?f[0]:f},async firstOrFail(){let f=await Z(o(),"select"),h0=Array.isArray(f)?f[0]:f;if(!h0)throw Error("No rows found");return h0},async count(){let f=K.length>0?h.unsafe(`SELECT COUNT(*) as c FROM (${s}) as sub`,K):h.unsafe(`SELECT COUNT(*) as c FROM (${s}) as sub`),h0=await Z(f,"select");return Number(h0?.[0]?.c??0)},async exists(){let f=K.length>0?h.unsafe(`SELECT EXISTS(${s}) as e`,K):h.unsafe(`SELECT EXISTS(${s}) as e`),h0=await Z(f,"select");return Boolean(h0?.[0]?.e)},async doesntExist(){return!await u.exists()},values(){return o().values()},raw(){return o().raw()},cancel(){try{o().cancel()}catch{}},whereRaw:_("whereRaw"),whereColumn:_("whereColumn"),orWhereColumn:_("orWhereColumn"),whereIn:_("whereIn"),orWhereIn:_("orWhereIn"),whereNotIn:_("whereNotIn"),orWhereNotIn:_("orWhereNotIn"),whereLike:_("whereLike"),whereILike:_("whereILike"),orWhereLike:_("orWhereLike"),orWhereILike:_("orWhereILike"),whereNotLike:_("whereNotLike"),whereNotILike:_("whereNotILike"),orWhereNotLike:_("orWhereNotLike"),orWhereNotILike:_("orWhereNotILike"),whereAny:_("whereAny"),whereAll:_("whereAll"),whereNone:_("whereNone"),whereNested:_("whereNested"),orWhereNested:_("orWhereNested"),whereDate:_("whereDate"),whereBetween:_("whereBetween"),whereNotBetween:_("whereNotBetween"),whereJsonContains:_("whereJsonContains"),whereJsonPath:_("whereJsonPath"),whereNull:_("whereNull"),orWhereNull:_("orWhereNull"),whereNotNull:_("whereNotNull"),orWhereNotNull:_("orWhereNotNull"),whereExists:_("whereExists"),orWhereExists:_("orWhereExists"),orWhereBetween:_("orWhereBetween"),orWhereRaw:_("orWhereRaw"),whereJsonDoesntContain:_("whereJsonDoesntContain"),whereJsonContainsKey:_("whereJsonContainsKey"),whereJsonDoesntContainKey:_("whereJsonDoesntContainKey"),whereJsonLength:_("whereJsonLength"),join:_("join"),joinSub:_("joinSub"),innerJoin:_("innerJoin"),leftJoin:_("leftJoin"),leftJoinSub:_("leftJoinSub"),rightJoin:_("rightJoin"),crossJoin:_("crossJoin"),crossJoinSub:_("crossJoinSub"),groupBy:_("groupBy"),groupByRaw:_("groupByRaw"),having:_("having"),havingRaw:_("havingRaw"),addSelect:_("addSelect"),select:_("select"),selectAll:_("selectAll"),orderByDesc:_("orderByDesc"),inRandomOrder:_("inRandomOrder"),reorder:_("reorder"),orderByRaw:_("orderByRaw"),union:_("union"),unionAll:_("unionAll"),forPage:_("forPage"),selectAllRelations:_("selectAllRelations"),with:_("with"),value:_("value"),pluck:_("pluck"),cursorPaginate:_("cursorPaginate"),paginate:_("paginate"),simplePaginate:_("simplePaginate"),chunk:_("chunk"),chunkById:_("chunkById"),eachById:_("eachById"),avg:_("avg"),sum:_("sum"),max:_("max"),min:_("min"),find:_("find"),findOrFail:_("findOrFail"),findMany:_("findMany"),latest:_("latest"),oldest:_("oldest"),lazy:_("lazy"),lazyById:_("lazyById"),pipe:(f)=>f(u),when:_("when"),tap:()=>u,dump:()=>u,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>o().simple(),toText:()=>s,toParams:()=>[...K],withTimeout:()=>u,abort:()=>u,lockForUpdate:()=>u,sharedLock:()=>u,withCTE:()=>u,withRecursive:()=>u,cache:()=>u,clone:()=>u,withTrashed:()=>u,onlyTrashed:()=>u,scope:()=>u,get rows(){return[]},get row(){return}};return u}return C(P,[],y)},insertInto(j){let O,_="",R=[],S=!1,D=()=>P?[]:{changes:0,lastInsertRowid:0},y=()=>{let Q=async()=>{return},N=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>y(),andWhere:()=>y(),orWhere:()=>y(),orderBy:()=>y(),limit:()=>y(),offset:()=>y(),toSQL:()=>w(null,""),execute:async()=>[],get:async()=>[],first:Q,executeTakeFirst:Q,firstOrFail:N,executeTakeFirstOrThrow:N}},P=v.dialect==="postgres",T=P?(Q)=>`"${String(Q).replace(/"/g,'""')}"`:G0(v.dialect)?(Q)=>`\`${String(Q).replace(/`/g,"``")}\``:(Q)=>`"${String(Q).replace(/"/g,'""')}"`,C=P?(Q)=>`$${Q+1}`:(Q)=>"?";return{values(Q){let N=Array.isArray(Q)?Q:[Q],K=N.length;if(K===0)return S=!0,O=null,_="",R.length=0,this;S=!1;let x=N[0],p=Object.keys(x),s=p.length,o=K*s;R.length=o;let q=P?p.map((d)=>T(d)).join(","):p.join(",");if(K===1)if(!P){let d=T(p[0]),u="?";R[0]=x[p[0]];for(let f=1;f<s;f++)d+=`,${T(p[f])}`,u+=",?",R[f]=x[p[f]];_=`INSERT INTO ${T(j)}(${d})VALUES(${u})`}else{_=`INSERT INTO ${T(j)}(${q})VALUES(`;for(let d=0;d<s;d++){if(d>0)_+=",";_+=C(d),R[d]=x[p[d]]}_+=")"}else{let d=p.map((f)=>T(f)).join(",");_=`INSERT INTO ${T(j)}(${d})VALUES`;let u=0;for(let f=0;f<K;f++){let h0=N[f];if(f===0)_+="(";else _+="),(";for(let t=0;t<s;t++){if(t>0)_+=",";_+=C(u),R[u++]=h0[p[t]]}}_+=")"}if(!h._prepareStatement)O=h.unsafe(_,R);return this},returning(...Q){if(S)return y();let N=`${_} RETURNING ${Q.join(", ")}`,K=h.unsafe(N,R),x=async()=>{let p=await Z(K,"insert");return Array.isArray(p)?p[0]:p};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>w(K,N),execute:()=>Z(K,"insert"),get:()=>Z(K,"insert"),first:x,executeTakeFirst:x,async firstOrFail(){let p=await x();if(!p)throw Error("Insert with RETURNING returned no rows");return p},async executeTakeFirstOrThrow(){let p=await x();if(!p)throw Error("Insert with RETURNING returned no rows");return p}}},toSQL(){if(S)return w(null,"");if(!O)O=h.unsafe(_,R);return w(O,_)},execute(){if(S)return Promise.resolve(D());let Q=H();if(!(Q&&(Q.onQueryStart||Q.onQueryEnd||Q.onQueryError||Q.startSpan||Q.beforeCreate||Q.afterCreate||rh(Q)))){let K=h._prepareStatement;if(K){let x=K(_);return R.length>0?x.run(...R):x.run()}}if(!O)O=h.unsafe(_,R);return Z(O,"insert")},async executeTakeFirst(){if(S)return D();if(!O)O=h.unsafe(_,R);return await Z(O,"insert")},async executeTakeFirstOrThrow(){if(S)throw Error("Insert failed");if(!O)O=h.unsafe(_,R);let Q=await Z(O,"insert");if(!Q)throw Error("Insert failed");return Q},returningAll(){if(S)return y();let Q=`${_} RETURNING *`,N=h.unsafe(Q,R),K=async()=>{let x=await Z(N,"insert");return Array.isArray(x)?x[0]:x};return{toSQL:()=>w(N,Q),execute:()=>Z(N,"insert"),get:()=>Z(N,"insert"),first:K,executeTakeFirst:K,async firstOrFail(){let x=await K();if(!x)throw Error("Insert with RETURNING returned no rows");return x},async executeTakeFirstOrThrow(){let x=await K();if(!x)throw Error("Insert with RETURNING returned no rows");return x}}}}},updateTable(j){let O,_=[],R=(D)=>{let y=String(D);if(G0(v.dialect))return`\`${y.replace(/`/g,"``")}\``;return`"${y.replace(/"/g,'""')}"`},S=`UPDATE ${R(String(j))}`;return{set(D){let y=Object.keys(D),P=y.length,T=Array.from({length:P});for(let C=0;C<P;C++){let Q=y[C],N=D[Q];if(n$(N))T[C]=`${R(Q)} = ${N.raw}`;else if(SG(N)){let K=QG(N,_.length+1);T[C]=`${R(Q)} = ${K.text}`,_.push(...K.parameters)}else T[C]=`${R(Q)} = ${r(_.length+1)}`,_.push(N)}return S=`${S} SET ${T.join(", ")}`,O=h.unsafe(S,_),this},where(D,y,P){let T=()=>X0.WHERE.test(S)?"AND":"WHERE";if(y!==void 0&&(typeof D==="string"||n$(D)||SG(D))){let C=g0(y,"updateTable.where"),Q;if(typeof D==="string")Q=R(D);else if(n$(D))Q=D.raw;else{let K=QG(D,_.length+1);Q=K.text,_.push(...K.parameters)}if(C.toLowerCase()==="in"||C.toLowerCase()==="not in"){let K=Array.isArray(P)?P:[P],x=x0(K.length,_.length+1);return S=`${S} ${T()} ${Q} ${C.toUpperCase()} (${x})`,_.push(...K),O=h.unsafe(S,_),this}let N=_.length+1;return S=`${S} ${T()} ${Q} ${C} ${r(N)}`,_.push(P),O=h.unsafe(S,_),this}if(Array.isArray(D)){let[C,Q,N]=D,K=g0(Q,"updateTable.where");if(K.toLowerCase()==="in"||K.toLowerCase()==="not in"){let p=Array.isArray(N)?N:[N],s=x0(p.length,_.length+1);return S=`${S} ${T()} ${R(String(C))} ${K.toUpperCase()} (${s})`,_.push(...p),O=h.unsafe(S,_),this}let x=_.length+1;return S=`${S} ${T()} ${R(String(C))} ${K} ${r(x)}`,_.push(N),O=h.unsafe(S,_),this}if(n$(D))return S=`${S} ${T()} ${D.raw}`,O=h.unsafe(S,_),this;if(SG(D)){let C=QG(D,_.length+1);return S=`${S} ${T()} ${C.text}`,_.push(...C.parameters),O=h.unsafe(S,_),this}if(D&&typeof D==="object"){let C=Object.keys(D);if(C.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let Q=C.length,N=_.length,K=Array.from({length:Q});for(let x=0;x<Q;x++)K[x]=`${R(C[x])} = ${r(N+x+1)}`,_.push(D[C[x]]);return S=`${S} ${T()} ${K.join(" AND ")}`,O=h.unsafe(S,_),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${D===null?"null":typeof D}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(D){let y=X0.WHERE.test(S)?"AND":"WHERE";return S=`${S} ${y} ${R(String(D))} IS NULL`,O=h.unsafe(S,_),this},whereNotNull(D){let y=X0.WHERE.test(S)?"AND":"WHERE";return S=`${S} ${y} ${R(String(D))} IS NOT NULL`,O=h.unsafe(S,_),this},returning(...D){let y=this,P=()=>`${S} RETURNING ${D.join(", ")}`,T=()=>_.length>0?h.unsafe(P(),_):h.unsafe(P()),C=async()=>{let K=await Z(T(),"update");return Array.isArray(K)?K[0]:K},Q=(K)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${K}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},N={where:(...K)=>{return y.where(...K),N},andWhere:(...K)=>{return y.where(...K),N},whereNull:(...K)=>{return y.whereNull(...K),N},whereNotNull:(...K)=>{return y.whereNotNull(...K),N},orWhere:Q("orWhere"),orderBy:Q("orderBy"),limit:Q("limit"),offset:Q("offset"),toSQL:()=>w(T(),P()),execute:()=>Z(T(),"update"),get:()=>Z(T(),"update"),first:C,executeTakeFirst:C,async firstOrFail(){let K=await C();if(!K)throw Error("Update with RETURNING returned no rows");return K},async executeTakeFirstOrThrow(){let K=await C();if(!K)throw Error("Update with RETURNING returned no rows");return K}};return N},toSQL(){if(!O)O=_.length>0?h.unsafe(S,_):h.unsafe(S);return w(O,S)},async execute(){let D=await Z(O,"update");return F(D)},async executeTakeFirst(){return{numUpdatedRows:F(await Z(O,"update"))}},async executeTakeFirstOrThrow(){let D=F(await Z(O,"update"));if(D===0)throw Error("No rows updated");return{numUpdatedRows:D}},returningAll(){let D=()=>`${S} RETURNING *`,y=()=>_.length>0?h.unsafe(D(),_):h.unsafe(D());return{toSQL:()=>w(y(),D()),execute:()=>Z(y(),"update"),async executeTakeFirst(){let P=await Z(y(),"update");return Array.isArray(P)?P[0]:P},async executeTakeFirstOrThrow(){let P=await Z(y(),"update"),T=Array.isArray(P)?P[0]:P;if(!T)throw Error("Update with RETURNING failed");return T}}}}},deleteFrom(j){let O=(C)=>{let Q=String(C);if(G0(v.dialect))return`\`${Q.replace(/`/g,"``")}\``;return`"${Q.replace(/"/g,'""')}"`},R=`DELETE FROM ${O(String(j))}`,S=null,D=[],y=null,P=()=>X0.WHERE.test(R)?"AND":"WHERE",T=()=>{if(S===null)S=D.length>0?h.unsafe(R,D):h.unsafe(R);return S};return{where(C,Q,N){if(y=C,typeof C==="string"&&Q!==void 0){let K=g0(Q,"deleteFrom.where");if(K.toLowerCase()==="in"||K.toLowerCase()==="not in"){let p=Array.isArray(N)?N:[N],s=x0(p.length,D.length+1);return R+=` ${P()} ${O(C)} ${K.toUpperCase()} (${s})`,D.push(...p),S=null,this}let x=D.length+1;return R+=` ${P()} ${O(C)} ${K} ${r(x)}`,D.push(N),S=null,this}if(Array.isArray(C)){let[K,x,p]=C,s=g0(x,"deleteFrom.where");if(s.toLowerCase()==="in"||s.toLowerCase()==="not in"){let q=Array.isArray(p)?p:[p],d=x0(q.length,D.length+1);return R+=` ${P()} ${O(String(K))} ${s.toUpperCase()} (${d})`,D.push(...q),S=null,this}let o=D.length+1;return R+=` ${P()} ${O(String(K))} ${s} ${r(o)}`,D.push(p),S=null,this}if(n$(C))return R+=` ${P()} ${C.raw}`,S=null,this;if(SG(C)){let K=QG(C,D.length+1);return R+=` ${P()} ${K.text}`,D.push(...K.parameters),S=null,this}if(C&&typeof C==="object"){let K=Object.keys(C);if(K.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let x=[];for(let p of K){let s=D.length+1;x.push(`${O(p)} = ${r(s)}`),D.push(C[p])}return R+=` ${P()} ${x.join(" AND ")}`,S=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${C===null?"null":typeof C}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(C){return R+=` ${P()} ${O(String(C))} IS NULL`,S=null,this},whereNotNull(C){return R+=` ${P()} ${O(String(C))} IS NOT NULL`,S=null,this},returning(...C){let Q=this,N=()=>`${R} RETURNING ${C.join(", ")}`,K=()=>D.length>0?h.unsafe(N(),D):h.unsafe(N()),x=async()=>{await H()?.beforeDelete?.({table:String(j),where:y});let q=await Z(K(),"delete");try{await H()?.afterDelete?.({table:String(j),where:y,result:q})}catch{}return q},p=async()=>{let q=await x();return Array.isArray(q)?q[0]:q},s=(q)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${q}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},o={where:(...q)=>{return Q.where(...q),o},andWhere:(...q)=>{return Q.where(...q),o},whereNull:(...q)=>{return Q.whereNull(...q),o},whereNotNull:(...q)=>{return Q.whereNotNull(...q),o},orWhere:s("orWhere"),orderBy:s("orderBy"),limit:s("limit"),offset:s("offset"),toSQL:()=>w(K(),N()),execute:()=>x(),get:()=>x(),first:p,executeTakeFirst:p,async firstOrFail(){let q=await p();if(!q)throw Error("Delete with RETURNING returned no rows");return q},async executeTakeFirstOrThrow(){let q=await p();if(!q)throw Error("Delete with RETURNING returned no rows");return q}};return o},toSQL(){return w(T(),R)},async execute(){try{await H()?.beforeDelete?.({table:String(j),where:y})}catch(Q){throw Q}let C=F(await Z(T(),"delete"));try{await H()?.afterDelete?.({table:String(j),where:y,result:C})}catch{}return C},async executeTakeFirst(){return{numDeletedRows:F(await Z(T(),"delete"))}},async executeTakeFirstOrThrow(){let C=F(await Z(T(),"delete"));if(C===0)throw Error("No rows deleted");return{numDeletedRows:C}},returningAll(){let C=()=>`${R} RETURNING *`,Q=()=>D.length>0?h.unsafe(C(),D):h.unsafe(C());return{toSQL:()=>w(Q(),C()),execute:()=>Z(Q(),"delete"),async executeTakeFirst(){let N=await Z(Q(),"delete");return Array.isArray(N)?N[0]:N},async executeTakeFirstOrThrow(){let N=await Z(Q(),"delete"),K=Array.isArray(N)?N[0]:N;if(!K)throw Error("Delete with RETURNING failed");return K}}}}},table(j){let O=this;return{insert(_){return O.insertInto(j).values(_)},update(_){return O.updateTable(j).set(_)},delete(){return O.deleteFrom(j)},select(..._){if(_.length===0)return O.selectFrom(j);return O.select(j,..._)}}},sql:h,raw(j,...O){return h(j,...O)},simple(j,...O){return h(j,...O).simple()},async advisoryLock(j){if(v.dialect==="postgres"){let O=J(j),_=h`SELECT pg_advisory_lock(${O})`;await Z(_,"raw");return}if(G0(v.dialect)){let O=`bqb:${String(j)}`,_=h`SELECT GET_LOCK(${O}, -1) AS ok`;await Z(_,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(j){if(v.dialect==="postgres"){let O=J(j),_=h`SELECT pg_try_advisory_lock(${O}) as ok`,R=await Z(_,"raw");return Boolean(R?.[0]?.ok)}if(G0(v.dialect)){let O=`bqb:${String(j)}`,_=h`SELECT GET_LOCK(${O}, 0) AS ok`,R=await Z(_,"raw");return Number(R?.[0]?.ok)===1}return!1},async advisoryUnlock(j){if(v.dialect==="postgres"){let O=J(j),_=h`SELECT pg_advisory_unlock(${O}) as ok`,R=await Z(_,"raw");return Boolean(R?.[0]?.ok)}if(G0(v.dialect)){let O=`bqb:${String(j)}`,_=h`SELECT RELEASE_LOCK(${O}) AS ok`,R=await Z(_,"raw");return Number(R?.[0]?.ok)===1}return!1},unsafe(j,O){return h.unsafe(j,O)},file(j,O){return h.file(j,O)},async reserve(){let j=await $0.reserve(),O=J0({sql:j,meta:A,schema:G,hooks:$?.hooks});return O.release=()=>j.release(),O},async close(j){await $0.close(j)},async listen(j,O){},async unlisten(j){},async notify(j,O){},async copyTo(j,O){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(j,O,_){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let j=h`SELECT 1`;return await Z(j,"select"),!0}catch{return!1}},async waitForReady(j){let O=Math.max(1,j?.attempts??10),_=Math.max(10,j?.delayMs??100);for(let R=0;R<O;R++){if(await this.ping())return;await new Promise((S)=>setTimeout(S,_))}throw Error("Database not ready after waiting")},async transaction(j,O){let R={...$?.txDefaults,...O},S=$?.sql??$0,D=$?.inTransaction===!0,y=D&&typeof S?.savepoint==="function"?"savepoint":"begin",P=async(Q)=>{R.logger?.({type:"start",attempt:Q});let N=Date.now();return await S[y](async(K)=>{let x=J0({sql:K,meta:A,schema:G,hooks:$?.hooks,inTransaction:!0});if(R?.isolation&&!D){let o=R.isolation,q=o==="read committed"?"READ COMMITTED":o==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(v.dialect==="postgres")await K.unsafe(`SET TRANSACTION ISOLATION LEVEL ${q}`);else if(G0(v.dialect))await K.unsafe(`SET TRANSACTION ISOLATION LEVEL ${q}`);else if(o!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${o}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(R?.readOnly)if(v.dialect==="postgres")await K.unsafe("SET TRANSACTION READ ONLY");else if(G0(v.dialect))await K.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let p=await j(x),s=Date.now()-N;return R.logger?.({type:"commit",attempt:Q,durationMs:s}),p})},T=Math.max(0,R?.retries??0),C=0;for(;;)try{let Q=await P(C+1);return R?.afterCommit?.(),Q}catch(Q){let N=$Z(Q)||hZ(Q,R.sqlStates);if(C<T&&N){C++,R?.onRetry?.(C,Q);let K=HZ(C,R.backoff);if(K>0)await AZ(K);continue}try{R.onRollback?.(Q)}catch{}try{R.afterRollback?.()}catch{}throw Q}},async savepoint(j){if($?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let O=h;if(!O||typeof O.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await O.savepoint(async(_)=>{let R=J0({sql:_,meta:A,schema:G,hooks:$?.hooks,inTransaction:!0});return await j(R)})},async beginDistributed(j,O){return await($?.sql??$0).beginDistributed(j,async(S)=>{let D=J0({sql:S,meta:A,schema:G,hooks:$?.hooks});return await O(D)})},async commitDistributed(j){await $0.commitDistributed(j)},async rollbackDistributed(j){await $0.rollbackDistributed(j)},setTransactionDefaults(j){$={...$,txDefaults:{...$?.txDefaults,...j}}},transactional(j,O){return(..._)=>{return this.transaction((R)=>j(R,..._),O)}},async insertOrIgnore(j,O){let _=Array.isArray(O)?O:[O];if(!_.length)return;let{colsSql:R,valuesSql:S,params:D}=CG(_),y=E$(String(j)),P=G0(v.dialect)?`INSERT IGNORE INTO ${y} (${R}) VALUES ${S}`:`INSERT INTO ${y} (${R}) VALUES ${S} ON CONFLICT DO NOTHING`;return h.unsafe(P,D).execute()},async insertGetId(j,O,_="id"){let{colsSql:R,valuesSql:S,params:D}=CG([O]),y=E$(String(j));if(G0(v.dialect)){await h.unsafe(`INSERT INTO ${y} (${R}) VALUES ${S}`,D).execute();let[T]=await h.unsafe("SELECT LAST_INSERT_ID() as id").execute();return T?.id}if(v.dialect==="sqlite"){let T=await h.unsafe(`INSERT INTO ${y} (${R}) VALUES ${S}`,D).execute();if(T?.lastInsertRowid!=null)return T.lastInsertRowid;let[C]=await h.unsafe("SELECT last_insert_rowid() as id").execute();return C?.id}let[P]=await h.unsafe(`INSERT INTO ${y} (${R}) VALUES ${S} RETURNING ${E$(String(_))} as id`,D).execute();return P?.id},async updateOrInsert(j,O,_){let R=E$(String(j)),S=Object.keys(O),D=1,y=S.map((K)=>`${E$(K)} = ${r(D++)}`).join(" AND "),P=S.map((K)=>O[K]);if((await h.unsafe(`SELECT 1 FROM ${R} WHERE ${y} LIMIT 1`,P).execute()).length){let K=Object.keys(_),x=1,p=K.map((q)=>`${E$(q)} = ${r(x++)}`).join(", "),s=S.map((q)=>`${E$(q)} = ${r(x++)}`).join(" AND "),o=[...K.map((q)=>_[q]),...S.map((q)=>O[q])];return await h.unsafe(`UPDATE ${R} SET ${p} WHERE ${s}`,o).execute(),!0}let{colsSql:C,valuesSql:Q,params:N}=CG([{...O,..._}]);return await h.unsafe(`INSERT INTO ${R} (${C}) VALUES ${Q}`,N).execute(),!0},async upsert(j,O,_,R){let S=_.map((p)=>String(p)),D=(R??[]).map((p)=>String(p)),y=O;if(!y.length)return;let{colsSql:P,valuesSql:T,params:C}=CG(y),Q=E$(String(j)),N=`INSERT INTO ${Q} (${P}) VALUES ${T}`;if(G0(v.dialect)){if(D.length===0)return h.unsafe(`INSERT IGNORE INTO ${Q} (${P}) VALUES ${T}`,C).execute();let p=D.map((s)=>`${E$(s)} = VALUES(${E$(s)})`).join(", ");return h.unsafe(`${N} ON DUPLICATE KEY UPDATE ${p}`,C).execute()}let K=S.map(E$).join(", ");if(D.length===0)return h.unsafe(`${N} ON CONFLICT (${K}) DO NOTHING`,C).execute();let x=D.map((p)=>`${E$(p)} = EXCLUDED.${E$(p)}`).join(", ");return h.unsafe(`${N} ON CONFLICT (${K}) DO UPDATE SET ${x}`,C).execute()},async save(j,O){let _=A?.primaryKeys[String(j)]??"id",R=O[_];if(R!=null)if(await this.selectFrom(j).find(R)){await this.updateTable(j).set(O).where({[_]:R}).execute();let D=await this.selectFrom(j).find(R);if(!D)throw Error("save() failed to retrieve updated row");return D}else return await this.create(j,O);return await this.create(j,O)},async remove(j,O){return await this.deleteFrom(j).where({id:O}).execute()},async find(j,O){return await this.selectFrom(j).find(O)},async findOrFail(j,O){return await this.selectFrom(j).findOrFail(O)},async findMany(j,O){return await this.selectFrom(j).findMany(O)},async latest(j,O){return await this.selectFrom(j).latest(O).first()},async oldest(j,O){return await this.selectFrom(j).oldest(O).first()},skip(j,O){return this.selectFrom(j).offset(O)},async rawQuery(j){let O=Date.now();try{H()?.onQueryStart?.({sql:j,kind:"raw"});let _=await h.unsafe(j);return H()?.onQueryEnd?.({sql:j,durationMs:Date.now()-O,kind:"raw"}),_}catch(_){throw H()?.onQueryError?.({sql:j,error:_,durationMs:Date.now()-O,kind:"raw"}),_}},async create(j,O){let _=A?.primaryKeys[String(j)]??"id";try{await H()?.beforeCreate?.({table:String(j),data:O})}catch(R){throw R}if(v.dialect==="postgres"){let R=h`INSERT INTO ${h(String(j))} ${h(O)} RETURNING ${h(String(_))} as id`,[S]=await R.execute();if(!S?.id)throw console.error(`create() failed to get insert ID for table ${String(j)}`),console.error("Inserted values:",O),Error(`create() failed to get insert ID for table ${String(j)}`);let D=await this.selectFrom(j).find(S.id);if(!D)throw console.error(`create() failed to retrieve inserted row for table ${String(j)} with id ${S.id}`),console.error("Inserted values:",O),Error(`create() failed to retrieve inserted row for table ${String(j)} with id ${S.id}`);try{await H()?.afterCreate?.({table:String(j),data:O,result:D})}catch{}return D}else{let R=await this.insertGetId(j,O,_);if(R==null)throw Error(`create() failed to get insert ID for table ${String(j)}`);let S=await this.selectFrom(j).find(R);if(!S)throw console.error(`create() failed to retrieve inserted row for table ${String(j)} with id ${R}`),console.error("Inserted values:",O),Error(`create() failed to retrieve inserted row for table ${String(j)} with id ${R}`);try{await H()?.afterCreate?.({table:String(j),data:O,result:S})}catch{}return S}},async createMany(j,O){if(!O?.length)return;let _=O[0],R=Object.keys(_),S=R.length,D=O.length,y=Array.from({length:D*S}),P=G0(v.dialect)?(Q)=>`\`${String(Q).replace(/`/g,"``")}\``:(Q)=>`"${String(Q).replace(/"/g,'""')}"`,T=`INSERT INTO ${P(String(j))}(${R.map(P).join(",")})VALUES`,C=0;for(let Q=0;Q<D;Q++){if(Q>0)T+=",";T+="(";let N=O[Q];for(let K=0;K<S;K++){if(K>0)T+=",";T+=r(C+1),y[C++]=N[R[K]]}T+=")"}return h.unsafe(T,y).execute()},async insertMany(j,O){if(!O?.length)return;let _=O[0],R=Object.keys(_),S=R.length,D=O.length,y=D*S,P=Array(y),T=v.dialect==="postgres",C;if(!T){let K=Array(S);for(let x=0;x<S;x++)K[x]="?";C=`(${K.join(",")})`}else C="";let Q=Array(D+2);Q[0]=`INSERT INTO ${j}(${R.join(",")})VALUES`;let N=0;if(!T){for(let K=0;K<D;K++){let x=O[K];Q[K+1]=C;for(let p=0;p<S;p++)P[N++]=x[R[p]]}return h.unsafe(Q[0]+Q.slice(1,D+1).join(","),P).execute()}for(let K=0;K<D;K++){let x=O[K],p=Array(S);for(let s=0;s<S;s++)p[s]=`$${N+1}`,P[N++]=x[R[s]];Q[K+1]=`(${p.join(",")})`}return h.unsafe(Q[0]+Q.slice(1,D+1).join(","),P).execute()},async updateMany(j,O,_){let R=Object.keys(_),S=R.length;if(S===0)return 0;let D=[],y=Array.from({length:S});for(let T=0;T<S;T++)y[T]=`${R[T]}=${r(T+1)}`,D.push(_[R[T]]);let P=`UPDATE ${j} SET ${y.join(",")}`;if(Array.isArray(O))P+=` WHERE ${O[0]}${O[1]}${r(D.length+1)}`,D.push(O[2]);else if(O&&typeof O==="object"&&!("raw"in O)){let T=Object.keys(O),C=T.length;if(C>0){let Q=D.length,N=Array.from({length:C});for(let K=0;K<C;K++)N[K]=`${T[K]}=${r(Q+K+1)}`,D.push(O[T[K]]);P+=` WHERE ${N.join(" AND ")}`}}return h.unsafe(P,D).execute()},async deleteMany(j,O){if(!Array.isArray(O)||O.length===0)return 0;let _=A?.primaryKeys[String(j)]??"id",R=O.length;if(v.dialect==="postgres"){let D=Array(R);for(let y=0;y<R;y++)D[y]=`$${y+1}`;return h.unsafe(`DELETE FROM ${j} WHERE ${_} IN (${D.join(",")})`,O).execute()}let S=Array(R);for(let D=0;D<R;D++)S[D]="?";return h.unsafe(`DELETE FROM ${j} WHERE ${_} IN (${S.join(",")})`,O).execute()},async firstOrCreate(j,O,_){let R=await this.selectFrom(j).where(O).first();if(R)return R;return await this.create(j,{...O,..._})},async updateOrCreate(j,O,_){let R=await this.selectFrom(j).where(O).first();if(R){await this.updateTable(j).set(_).where(O).execute();let S=A?.primaryKeys[String(j)]??"id",D=R[S],y=D!=null?await this.selectFrom(j).find(D):await this.selectFrom(j).where(O).first();if(!y)throw Error("updateOrCreate() failed to retrieve updated row");return y}return await this.create(j,{...O,..._})},async count(j,O){let _=O?h(String(O)):h`*`,R=h`SELECT COUNT(${_}) as c FROM ${h(String(j))}`,[S]=await R.execute();return Number(S?.c??0)},async sum(j,O){let _=h`SELECT SUM(${h(String(O))}) as s FROM ${h(String(j))}`,[R]=await _.execute();return Number(R?.s??0)},async avg(j,O){let _=h`SELECT AVG(${h(String(O))}) as a FROM ${h(String(j))}`,[R]=await _.execute();return Number(R?.a??0)},async min(j,O){let _=h`SELECT MIN(${h(String(O))}) as m FROM ${h(String(j))}`,[R]=await _.execute();return R?.m},async max(j,O){let _=h`SELECT MAX(${h(String(O))}) as m FROM ${h(String(j))}`,[R]=await _.execute();return R?.m},getRelationships(j){if(!A?.relations)return{};let O=A.relations[j];if(!O)return{};let _={};for(let[R,S]of Object.entries(O))if(S&&typeof S==="object"&&Object.keys(S).length>0)_[R]=S;return _},hasRelationship(j,O){if(!A?.relations)return!1;let _=A.relations[j];if(!_)return!1;return Object.values(_).some((R)=>R&&typeof R==="object"&&(O in R))},getRelationshipType(j,O){if(!A?.relations)return null;let _=A.relations[j];if(!_)return null;for(let[R,S]of Object.entries(_))if(S&&typeof S==="object"&&O in S)return R;return null},getRelationshipTarget(j,O){if(!A?.relations)return null;let _=A.relations[j];if(!_)return null;for(let[R,S]of Object.entries(_))if(S&&typeof S==="object"&&O in S){let D=S[O];if(typeof D==="string")return A.modelToTable[D]||D;else if(D&&typeof D==="object"){if("model"in D)return A.modelToTable[D.model]||D.model;if("target"in D)return A.modelToTable[D.target]||D.target}}return null}}}function k9(){BG.clear()}function y9($){BG.setMaxSize($)}var X0,P9,N9,BG,KG,GZ=500;var oh=a(()=>{f0();U1();XH();X0={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},P9=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);N9=new Set;BG=new T9;KG=new Map});async function EZ(){console.log("-- Clearing query cache..."),k9(),console.log("-- \u2713 Query cache cleared")}async function UZ(){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 YZ($={}){if(console.log("-- Configuring query cache..."),console.log(),$.size!==void 0){let h=Number($.size);if(Number.isNaN(h)||h<=0)throw console.error("-- Error: Cache size must be a positive number"),Error("Invalid cache size");y9(h),console.log(`-- \u2713 Cache max size set to: ${h}`)}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 q9=a(()=>{oh()});import IG from"process";import{createInterface as zZ}from"readline";async function x9(){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 $=J0(),h=zZ({input:IG.stdin,output:IG.stdout,prompt:"qb> "}),A="",G=!1,J=`
|
|
80
|
-
Available Commands:
|
|
81
|
-
.help Show this help message
|
|
82
|
-
.exit Exit the console
|
|
83
|
-
.tables List all tables
|
|
84
|
-
.clear Clear the screen
|
|
85
|
-
|
|
86
|
-
Query Examples:
|
|
87
|
-
qb.selectFrom('users').where({ active: true }).limit(10).execute()
|
|
88
|
-
qb.selectFrom('users').count()
|
|
89
|
-
qb.insertInto('users').values({ name: 'John' }).execute()
|
|
90
|
-
qb.selectFrom('users').where('id', '=', 1).first()
|
|
91
|
-
qb.unsafe("SELECT * FROM users WHERE id = $1", [1]).execute()
|
|
92
|
-
|
|
93
|
-
Tips:
|
|
94
|
-
- Use 'qb' to access the query builder
|
|
95
|
-
- Use 'await' for async operations
|
|
96
|
-
- Multi-line input: end with \\ to continue on next line
|
|
97
|
-
- Press Enter on an empty line to execute multi-line input
|
|
98
|
-
`,H=async(Y)=>{try{let W=await new(Object.getPrototypeOf(async()=>{})).constructor("qb",`return (${Y})`)($);if(W!==void 0)if(Array.isArray(W))console.log(`-- ${W.length} row(s) returned`),console.table(W);else if(typeof W==="object"&&W!==null)console.log(W);else console.log(W)}catch(U){console.error("Error:",U.message)}},E=async(Y)=>{let U=Y.trim();if(U.startsWith(".")){let z=U.toLowerCase();if(z===".exit"||z===".quit")console.log("Goodbye!"),h.close(),IG.exit(0);else if(z===".help")console.log(J);else if(z===".clear")console.clear();else if(z===".tables")try{let W=await $.unsafe(`
|
|
99
|
-
SELECT name FROM sqlite_master
|
|
100
|
-
WHERE type = 'table'
|
|
101
|
-
AND name NOT LIKE 'sqlite_%'
|
|
102
|
-
ORDER BY name
|
|
103
|
-
`);if(W.length>0){console.log("Tables:");for(let Z of W)console.log(` - ${Z.name}`)}else console.log("No tables found")}catch(W){console.error("Error listing tables:",W.message)}else console.log(`Unknown command: ${U}`),console.log("Type .help for available commands");return}if(U.endsWith("\\")){G=!0,A+=`${U.slice(0,-1)}
|
|
104
|
-
`;return}if(G){if(U==="")await H(A),A="",G=!1;else A+=`${U}
|
|
105
|
-
`;return}if(U)await H(U)};h.on("line",async(Y)=>{await E(Y),h.prompt()}),h.on("SIGINT",()=>{if(G)console.log(`
|
|
106
|
-
-- Multi-line input cancelled`),A="",G=!1,h.prompt();else console.log(`
|
|
107
|
-
-- Type .exit to quit`),h.prompt()}),h.on("close",()=>{console.log(`
|
|
108
|
-
Goodbye!`),IG.exit(0)}),h.prompt()}async function WZ(){return x9()}var f9=a(()=>{m0()});import{existsSync as ZZ,readFileSync as XZ,writeFileSync as th}from"fs";async function jZ($,h={}){let A=h.format||"json",G=h.output||`${$}.${A}`,J=h.limit;if(console.log(`-- Exporting data from table: ${$}`),console.log(`-- Format: ${A}`),console.log(`-- Output: ${G}`),J)console.log(`-- Limit: ${J} rows`);console.log();try{let E=J0().selectFrom($);if(J)E=E.limit(J);let Y=await E.execute();if(console.log(`-- Retrieved ${Y.length} rows`),A==="json")th(G,JSON.stringify(Y,null,2)),console.log(`-- \u2713 Exported to JSON: ${G}`);else if(A==="csv"){if(Y.length===0){th(G,""),console.log(`-- \u2713 Exported to CSV: ${G} (empty)`);return}let U=Object.keys(Y[0]),z=[U.join(",")];for(let W of Y){let Z=U.map((F)=>{let w=W[F];if(w===null||w===void 0)return"";let B=String(w);if(B.includes(",")||B.includes('"')||B.includes(`
|
|
109
|
-
`))return`"${B.replace(/"/g,'""')}"`;return B});z.push(Z.join(","))}th(G,z.join(`
|
|
110
|
-
`)),console.log(`-- \u2713 Exported to CSV: ${G}`)}else if(A==="sql"){let U=[];for(let z of Y){let W=Object.keys(z),Z=W.map((F)=>{let w=z[F];if(w===null||w===void 0)return"NULL";if(typeof w==="number")return String(w);return`'${String(w).replace(/'/g,"''")}'`});U.push(`INSERT INTO ${$} (${W.join(", ")}) VALUES (${Z.join(", ")});`)}th(G,U.join(`
|
|
111
|
-
`)),console.log(`-- \u2713 Exported to SQL: ${G}`)}}catch(H){throw console.error(`-- Failed to export data from ${$}:`,H),H}}async function LZ($,h,A={}){if(!ZZ(h))throw console.error(`-- File not found: ${h}`),Error(`File not found: ${h}`);let G=A.format||(h.endsWith(".json")?"json":"csv"),J=A.truncate??!1;console.log(`-- Importing data into table: ${$}`),console.log(`-- Format: ${G}`),console.log(`-- File: ${h}`),console.log(`-- Truncate: ${J}`),console.log();try{let H=J0();if(J)await H.deleteFrom($).execute(),console.log("-- Table truncated");let E=XZ(h,"utf8"),Y=[];if(G==="json"){if(Y=JSON.parse(E),!Array.isArray(Y))throw TypeError("JSON file must contain an array of objects")}else if(G==="csv"){let W=E.split(`
|
|
112
|
-
`).filter((F)=>F.trim());if(W.length<2){console.log("-- No data to import (CSV is empty or has only headers)");return}let Z=W[0].split(",").map((F)=>F.trim());for(let F=1;F<W.length;F++){let w=W[F].split(",").map((j)=>j.trim()),B={};for(let j=0;j<Z.length;j++){let O=w[j];if(O.startsWith('"')&&O.endsWith('"'))O=O.slice(1,-1).replace(/""/g,'"');if(O==="")O=null;else if(!Number.isNaN(Number(O)))O=Number(O);B[Z[j]]=O}Y.push(B)}}if(Y.length===0){console.log("-- No data to import");return}let U=100,z=0;for(let W=0;W<Y.length;W+=U){let Z=Y.slice(W,W+U);await H.insertInto($).values(Z).execute(),z+=Z.length,console.log(`-- Imported ${z}/${Y.length} rows...`)}console.log(`-- \u2713 Successfully imported ${Y.length} rows`)}catch(H){throw console.error(`-- Failed to import data into ${$}:`,H),H}}async function FZ($={}){let h=v.dialect||"postgres",A=$.output||`dump-${Date.now()}.sql`,G=$.tables?.split(",").map((J)=>J.trim());if(console.log("-- Dumping database"),console.log(`-- Dialect: ${h}`),console.log(`-- Output: ${A}`),G)console.log(`-- Tables: ${G.join(", ")}`);console.log();try{let J=J0(),H=[];if(h==="sqlite")H=(await J.unsafe(`
|
|
113
|
-
SELECT name FROM sqlite_master
|
|
114
|
-
WHERE type = 'table'
|
|
115
|
-
AND name NOT LIKE 'sqlite_%'
|
|
116
|
-
ORDER BY name
|
|
117
|
-
`)).map((U)=>U.name);else if(h==="postgres")H=(await J.unsafe(`
|
|
118
|
-
SELECT table_name
|
|
119
|
-
FROM information_schema.tables
|
|
120
|
-
WHERE table_schema = 'public'
|
|
121
|
-
AND table_type = 'BASE TABLE'
|
|
122
|
-
ORDER BY table_name
|
|
123
|
-
`)).map((U)=>U.table_name);else if(G0(h))H=(await J.unsafe(`
|
|
124
|
-
SELECT table_name
|
|
125
|
-
FROM information_schema.tables
|
|
126
|
-
WHERE table_schema = DATABASE()
|
|
127
|
-
AND table_type = 'BASE TABLE'
|
|
128
|
-
ORDER BY table_name
|
|
129
|
-
`)).map((U)=>U.table_name);if(G)H=H.filter((Y)=>G.includes(Y));if(H.length===0){console.log("-- No tables to dump");return}console.log(`-- Dumping ${H.length} table(s)`);let E=[];E.push("-- Database dump"),E.push(`-- Generated at: ${new Date().toISOString()}`),E.push(`-- Dialect: ${h}`),E.push("");for(let Y of H){console.log(`-- Dumping table: ${Y}`);let U=await J.selectFrom(Y).execute();E.push(`-- Table: ${Y}`),E.push(`-- Rows: ${U.length}`),E.push("");for(let z of U){let W=Object.keys(z),Z=W.map((F)=>{let w=z[F];if(w===null||w===void 0)return"NULL";if(typeof w==="number")return String(w);return`'${String(w).replace(/'/g,"''")}'`});E.push(`INSERT INTO ${Y} (${W.join(", ")}) VALUES (${Z.join(", ")});`)}E.push("")}th(A,E.join(`
|
|
130
|
-
`)),console.log(),console.log(`-- \u2713 Database dump saved to: ${A}`)}catch(J){throw console.error("-- Failed to dump database:",J),J}}var g9=a(()=>{f0();oh()});async function v9(){let $=v.dialect||"postgres",h=v.database?.database||"unknown";console.log("-- Database Information"),console.log(`-- Dialect: ${$}`),console.log(`-- Database: ${h}`),console.log();try{let A=J0(),G=[],J=[];if($==="postgres")J=(await A.unsafe(`
|
|
131
|
-
SELECT table_name
|
|
132
|
-
FROM information_schema.tables
|
|
133
|
-
WHERE table_schema = 'public'
|
|
134
|
-
AND table_type = 'BASE TABLE'
|
|
135
|
-
ORDER BY table_name
|
|
136
|
-
`)).map((Y)=>Y.table_name);else if(G0($))J=(await A.unsafe(`
|
|
137
|
-
SELECT table_name
|
|
138
|
-
FROM information_schema.tables
|
|
139
|
-
WHERE table_schema = DATABASE()
|
|
140
|
-
AND table_type = 'BASE TABLE'
|
|
141
|
-
ORDER BY table_name
|
|
142
|
-
`)).map((Y)=>Y.table_name);else if($==="sqlite")J=(await A.unsafe(`
|
|
143
|
-
SELECT name
|
|
144
|
-
FROM sqlite_master
|
|
145
|
-
WHERE type = 'table'
|
|
146
|
-
AND name NOT LIKE 'sqlite_%'
|
|
147
|
-
ORDER BY name
|
|
148
|
-
`)).map((Y)=>Y.name);for(let E of J)try{let Y=await A.unsafe(`SELECT COUNT(*) as count FROM ${E}`),U=Number(Y[0]?.count||0),z=0,W=0;if($==="postgres"){let Z=await A.unsafe(`
|
|
149
|
-
SELECT COUNT(*) as count
|
|
150
|
-
FROM information_schema.columns
|
|
151
|
-
WHERE table_name = $1
|
|
152
|
-
`,[E]);z=Number(Z[0]?.count||0);let F=await A.unsafe(`
|
|
153
|
-
SELECT COUNT(*) as count
|
|
154
|
-
FROM pg_indexes
|
|
155
|
-
WHERE tablename = $1
|
|
156
|
-
`,[E]);W=Number(F[0]?.count||0)}else if(G0($)){let Z=await A.unsafe(`
|
|
157
|
-
SELECT COUNT(*) as count
|
|
158
|
-
FROM information_schema.columns
|
|
159
|
-
WHERE table_name = ?
|
|
160
|
-
AND table_schema = DATABASE()
|
|
161
|
-
`,[E]);z=Number(Z[0]?.count||0);let F=await A.unsafe(`
|
|
162
|
-
SELECT COUNT(*) as count
|
|
163
|
-
FROM information_schema.statistics
|
|
164
|
-
WHERE table_name = ?
|
|
165
|
-
AND table_schema = DATABASE()
|
|
166
|
-
`,[E]);W=Number(F[0]?.count||0)}else if($==="sqlite")z=(await A.unsafe(`PRAGMA table_info(${E})`)).length,W=(await A.unsafe(`PRAGMA index_list(${E})`)).length;G.push({name:E,rowCount:U,columns:z,indexes:W})}catch(Y){console.error(`-- Error getting info for table ${E}:`,Y)}let H=G.reduce((E,Y)=>E+Y.rowCount,0);if(console.log(`-- Total Tables: ${G.length}`),console.log(`-- Total Rows: ${H.toLocaleString()}`),console.log(),G.length>0){console.log("Tables:"),console.log();let E=Math.max(...G.map((z)=>z.name.length)),Y=E+2,U="Table".padEnd(Y)+"Rows".padStart(12)+"Columns".padStart(10)+"Indexes".padStart(10);console.log(U),console.log("-".repeat(U.length));for(let z of G){let W=z.name.padEnd(E+2),Z=z.rowCount.toLocaleString().padStart(12),F=(z.columns||0).toString().padStart(10),w=(z.indexes||0).toString().padStart(10);console.log(`${W}${Z}${F}${w}`)}}else console.log("-- No tables found");return{dialect:$,database:h,tables:G,totalTables:G.length,totalRows:H}}catch(A){throw console.error("-- Failed to get database info:",A),A}}async function RZ(){return v9()}var b9=a(()=>{f0();m0()});async function c9($={}){let h=OG($.dialect),A=$.aggressive||!1;if($.verbose)console.log(`Optimizing ${h} database${A?" (aggressive mode)":""}...`);try{if(h==="postgres"){if($.tables&&$.tables.length>0)for(let G of $.tables){if($.verbose)console.log(`Analyzing table: ${G}`);if(A)await $0`VACUUM FULL ANALYZE ${$0(G)}`;else await $0`VACUUM ANALYZE ${$0(G)}`}else{if($.verbose)console.log("Running VACUUM and ANALYZE on all tables...");if(A)await $0`VACUUM FULL`,await $0`ANALYZE`;else await $0`VACUUM ANALYZE`}console.log("\u2713 PostgreSQL optimization complete")}else if(G0(h)){if($.tables&&$.tables.length>0)for(let G of $.tables){if($.verbose)console.log(`Optimizing table: ${G}`);await $0`OPTIMIZE TABLE ${$0(G)}`,await $0`ANALYZE TABLE ${$0(G)}`}else{let G=MG(),J=await $0`
|
|
167
|
-
SELECT table_name
|
|
168
|
-
FROM information_schema.tables
|
|
169
|
-
WHERE table_schema = ${G}
|
|
170
|
-
`;for(let H of J){let E=H.table_name||H.TABLE_NAME;if($.verbose)console.log(`Optimizing table: ${E}`);await $0`OPTIMIZE TABLE ${$0(E)}`,await $0`ANALYZE TABLE ${$0(E)}`}}console.log("\u2713 MySQL optimization complete")}else if(h==="sqlite"){if($.verbose)console.log("Running VACUUM on SQLite database...");if(await $0`VACUUM`,$.tables&&$.tables.length>0)for(let G of $.tables){if($.verbose)console.log(`Analyzing table: ${G}`);await $0`ANALYZE ${$0(G)}`}else await $0`ANALYZE`;if(A){if($.verbose)console.log("Running aggressive SQLite optimizations...");await $0`PRAGMA optimize`,await $0`PRAGMA wal_checkpoint(TRUNCATE)`}console.log("\u2713 SQLite optimization complete")}else console.error(`Unsupported dialect: ${h}`)}catch(G){throw console.error("Error optimizing database:",G.message),G}}var m9=a(()=>{f0();U1()});async function d9($={}){let h=OG($.dialect);if($.verbose)console.log(`Wiping all tables from ${h} database...`);try{let A=[];if(h==="postgres")A=(await $0`
|
|
171
|
-
SELECT tablename
|
|
172
|
-
FROM pg_tables
|
|
173
|
-
WHERE schemaname = 'public'
|
|
174
|
-
`).map((J)=>J.tablename);else if(G0(h)){let G=MG();A=(await $0`
|
|
175
|
-
SELECT table_name
|
|
176
|
-
FROM information_schema.tables
|
|
177
|
-
WHERE table_schema = ${G}
|
|
178
|
-
`).map((H)=>H.table_name||H.TABLE_NAME)}else if(h==="sqlite")A=(await $0`
|
|
179
|
-
SELECT name
|
|
180
|
-
FROM sqlite_master
|
|
181
|
-
WHERE type = 'table'
|
|
182
|
-
AND name NOT LIKE 'sqlite_%'
|
|
183
|
-
`).map((J)=>J.name);if(A.length===0){console.log("No tables found to drop.");return}if($.verbose)console.log(`Found ${A.length} tables: ${A.join(", ")}`);if(h==="postgres")for(let G of A){if($.verbose)console.log(`Dropping table: ${G}`);await $0`DROP TABLE IF EXISTS ${$0(G)} CASCADE`}else if(G0(h)){await $0`SET FOREIGN_KEY_CHECKS = 0`;for(let G of A){if($.verbose)console.log(`Dropping table: ${G}`);await $0`DROP TABLE IF EXISTS ${$0(G)}`}await $0`SET FOREIGN_KEY_CHECKS = 1`}else if(h==="sqlite"){await $0`PRAGMA foreign_keys = OFF`;for(let G of A){if($.verbose)console.log(`Dropping table: ${G}`);await $0`DROP TABLE IF EXISTS ${$0(G)}`}await $0`PRAGMA foreign_keys = ON`}console.log(`\u2713 Dropped ${A.length} tables`)}catch(A){throw console.error("Error wiping database:",A.message),A}}var p9=a(()=>{f0();U1()});async function wZ($){let G=await(J0().raw([$]).simple()?.execute?.()??Promise.resolve([]));return console.log(JSON.stringify(G,null,2)),G}var n9=a(()=>{m0()});async function _Z($,h={}){let A=J0(),G=h.params?JSON.parse(h.params):void 0,J=await A.file($,G);return console.log(JSON.stringify(J)),J}var u9=a(()=>{m0()});async function i9($,h={}){let A=v.dialect||"postgres",G=h.verbose??!0;if(G)console.log(`-- Inspecting table: ${$}`),console.log(`-- Dialect: ${A}`),console.log();try{let J=J0(),H=[],E=[],Y=await J.unsafe(`SELECT COUNT(*) as count FROM ${$}`),U=Number(Y[0]?.count||0);if(A==="postgres"){let z=await J.unsafe(`
|
|
184
|
-
SELECT
|
|
185
|
-
c.column_name,
|
|
186
|
-
c.data_type,
|
|
187
|
-
c.is_nullable,
|
|
188
|
-
c.column_default,
|
|
189
|
-
CASE
|
|
190
|
-
WHEN pk.column_name IS NOT NULL THEN true
|
|
191
|
-
ELSE false
|
|
192
|
-
END as is_primary_key,
|
|
193
|
-
CASE
|
|
194
|
-
WHEN fk.column_name IS NOT NULL THEN true
|
|
195
|
-
ELSE false
|
|
196
|
-
END as is_foreign_key
|
|
197
|
-
FROM information_schema.columns c
|
|
198
|
-
LEFT JOIN (
|
|
199
|
-
SELECT ku.column_name
|
|
200
|
-
FROM information_schema.table_constraints tc
|
|
201
|
-
JOIN information_schema.key_column_usage ku
|
|
202
|
-
ON tc.constraint_name = ku.constraint_name
|
|
203
|
-
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
204
|
-
AND tc.table_name = $1
|
|
205
|
-
) pk ON c.column_name = pk.column_name
|
|
206
|
-
LEFT JOIN (
|
|
207
|
-
SELECT ku.column_name
|
|
208
|
-
FROM information_schema.table_constraints tc
|
|
209
|
-
JOIN information_schema.key_column_usage ku
|
|
210
|
-
ON tc.constraint_name = ku.constraint_name
|
|
211
|
-
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
212
|
-
AND tc.table_name = $1
|
|
213
|
-
) fk ON c.column_name = fk.column_name
|
|
214
|
-
WHERE c.table_name = $1
|
|
215
|
-
ORDER BY c.ordinal_position
|
|
216
|
-
`,[$]);for(let Z of z)H.push({name:Z.column_name,type:Z.data_type,nullable:Z.is_nullable==="YES",default:Z.column_default,isPrimaryKey:Z.is_primary_key,isForeignKey:Z.is_foreign_key});let W=await J.unsafe(`
|
|
217
|
-
SELECT
|
|
218
|
-
i.indexname as name,
|
|
219
|
-
i.indexdef,
|
|
220
|
-
ix.indisunique as is_unique
|
|
221
|
-
FROM pg_indexes i
|
|
222
|
-
JOIN pg_class c ON c.relname = i.indexname
|
|
223
|
-
JOIN pg_index ix ON ix.indexrelid = c.oid
|
|
224
|
-
WHERE i.tablename = $1
|
|
225
|
-
`,[$]);for(let Z of W){let F=Z.indexdef?.match(/\(([^)]+)\)/),B=(F?F[1]:"").split(",").map((j)=>j.trim());E.push({name:Z.name,columns:B,unique:Z.is_unique})}}else if(G0(A)){let z=await J.unsafe(`
|
|
226
|
-
SELECT
|
|
227
|
-
COLUMN_NAME as column_name,
|
|
228
|
-
DATA_TYPE as data_type,
|
|
229
|
-
IS_NULLABLE as is_nullable,
|
|
230
|
-
COLUMN_DEFAULT as column_default,
|
|
231
|
-
COLUMN_KEY as column_key
|
|
232
|
-
FROM information_schema.COLUMNS
|
|
233
|
-
WHERE TABLE_NAME = ?
|
|
234
|
-
AND TABLE_SCHEMA = DATABASE()
|
|
235
|
-
ORDER BY ORDINAL_POSITION
|
|
236
|
-
`,[$]);for(let F of z)H.push({name:F.column_name,type:F.data_type,nullable:F.is_nullable==="YES",default:F.column_default,isPrimaryKey:F.column_key==="PRI",isForeignKey:F.column_key==="MUL"});let W=await J.unsafe(`
|
|
237
|
-
SHOW INDEXES FROM ${$}
|
|
238
|
-
`),Z=new Map;for(let F of W){let w=F.Key_name;if(!Z.has(w))Z.set(w,{columns:[],unique:F.Non_unique===0});Z.get(w).columns.push(F.Column_name)}for(let[F,w]of Z)E.push({name:F,columns:w.columns,unique:w.unique})}else if(A==="sqlite"){let z=await J.unsafe(`PRAGMA table_info(${$})`);for(let Z of z)H.push({name:Z.name,type:Z.type,nullable:Z.notnull===0,default:Z.dflt_value,isPrimaryKey:Z.pk===1});let W=await J.unsafe(`PRAGMA index_list(${$})`);for(let Z of W){let F=await J.unsafe(`PRAGMA index_info(${Z.name})`);E.push({name:Z.name,columns:F.map((w)=>w.name),unique:Z.unique===1})}}if(G){console.log(`Table: ${$}`),console.log(`Rows: ${U.toLocaleString()}`),console.log(),console.log("Columns:"),console.log();let z=Math.max(...H.map((B)=>B.name.length),10),W=Math.max(...H.map((B)=>B.type.length),10),Z=z+2,F=W+2,w=`${"Name".padEnd(Z)+"Type".padEnd(F)+"Nullable".padEnd(10)+"Default".padEnd(20)}Flags`;console.log(w),console.log("-".repeat(w.length));for(let B of H){let j=B.name.padEnd(Z),O=B.type.padEnd(F),_=(B.nullable?"YES":"NO").padEnd(10),R=String(B.default||"").padEnd(20),S=[B.isPrimaryKey?"PK":"",B.isForeignKey?"FK":""].filter(Boolean).join(", ");console.log(`${j}${O}${_}${R}${S}`)}if(console.log(),E.length>0){console.log("Indexes:"),console.log();for(let B of E){let j=B.unique?" (UNIQUE)":"";console.log(` - ${B.name}${j}: [${B.columns.join(", ")}]`)}console.log()}}return{tableName:$,rowCount:U,columns:H,indexes:E}}catch(J){throw console.error(`-- Failed to inspect table ${$}:`,J),J}}async function OZ($,h={}){return i9($,h)}var s9=a(()=>{f0();m0()});async function DZ($,h={}){let A=await C$({modelsDir:$}),G=PG(A);return console.log(JSON.stringify(G,null,2)),{models:A,schema:G}}var r9=a(()=>{m0()});function l9($){let h=$.toLowerCase();if(/^bool|boolean|tinyint\(1\)/.test(h))return"boolean";if(/int|serial|numeric|decimal|double|real|float|money/.test(h))return"number";if(/timestamp|datetime|date|time/.test(h))return"datetime";if(/json/.test(h))return"json";return"string"}function VZ($){if(/ies$/i.test($))return $.replace(/ies$/i,"y");if(/ses$/i.test($))return $.replace(/es$/i,"");if(/s$/i.test($)&&!/ss$/i.test($))return $.replace(/s$/i,"");return $}function MZ($){return $.replace(/[-_\s]+/g," ").split(" ").filter(Boolean).map((h)=>h.charAt(0).toUpperCase()+h.slice(1)).join("")}function jH($){return MZ(VZ($))}async function o9($,h){if(h==="postgres")return(await $.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")).map((J)=>J.table_name);if(G0(h))return(await $.unsafe("SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' ORDER BY table_name")).map((J)=>J.table_name??J.TABLE_NAME);return(await $.unsafe("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")).map((G)=>G.name)}async function SZ($,h,A){if(h==="sqlite")return(await $.unsafe(`PRAGMA table_info(${A})`)).map((H)=>({name:H.name,sqlType:String(H.type||""),nullable:Number(H.notnull)===0,isPrimaryKey:Number(H.pk)>0}));if(h==="postgres")return(await $.unsafe(`SELECT c.column_name, c.data_type, c.is_nullable,
|
|
239
|
-
(SELECT COUNT(*) FROM information_schema.table_constraints tc
|
|
240
|
-
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
|
|
241
|
-
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
|
|
242
|
-
FROM information_schema.columns c
|
|
243
|
-
WHERE c.table_name = $1 AND c.table_schema = 'public'
|
|
244
|
-
ORDER BY c.ordinal_position`,[A])).map((H)=>({name:H.column_name,sqlType:String(H.data_type||""),nullable:String(H.is_nullable).toUpperCase()==="YES",isPrimaryKey:Number(H.is_pk)>0}));return(await $.unsafe(`SELECT column_name, data_type, is_nullable, column_key
|
|
245
|
-
FROM information_schema.columns
|
|
246
|
-
WHERE table_name = ? AND table_schema = DATABASE()
|
|
247
|
-
ORDER BY ordinal_position`,[A])).map((J)=>({name:J.column_name??J.COLUMN_NAME,sqlType:String(J.data_type??J.DATA_TYPE??""),nullable:String(J.is_nullable??J.IS_NULLABLE).toUpperCase()==="YES",isPrimaryKey:String(J.column_key??J.COLUMN_KEY).toUpperCase()==="PRI"}))}function t9($,h){let A=jH($),G=h.find((H)=>H.isPrimaryKey)?.name??"id",J=h.map((H)=>{let E=[`type: '${l9(H.sqlType)}'`];if(!H.nullable&&!H.isPrimaryKey)E.push("required: true");return` ${H.name}: { ${E.join(", ")} },`}).join(`
|
|
248
|
-
`);return`export const ${A} = defineModel({
|
|
249
|
-
name: '${A}',
|
|
250
|
-
table: '${$}',
|
|
251
|
-
primaryKey: '${G}',
|
|
252
|
-
attributes: {
|
|
253
|
-
${J}
|
|
254
|
-
},
|
|
255
|
-
})
|
|
256
|
-
`}async function LH($={}){let h=v.dialect||"postgres",A=J0(),G=$.tables?.length?$.tables:await o9(A,h),J=[];for(let H of G){let E=await SZ(A,h,H);if(!E.length)continue;J.push({table:H,modelName:jH(H),primaryKey:E.find((Y)=>Y.isPrimaryKey)?.name??"id",columns:E,source:t9(H,E)})}return J}function FH($,h,A){if(A?.enumValues&&A.enumValues.length>0)return"enum";let G=String($||"").toLowerCase().trim(),J=G.replace(/\(.*$/,"").replace(/\s+/g," ").trim();if(G0(h)&&/^tinyint\(1\)/.test(G))return"boolean";if(/^bool/.test(J))return"boolean";if(J==="int8"||J==="bigint"||J==="bigserial")return"bigint";if(/^(?:int|integer|smallint|mediumint|serial|int2|int4|tinyint)/.test(J))return"integer";if(/^(?:varchar|character varying|nvarchar|nchar|char|character|bpchar)/.test(J)){let H=G.match(/\((\d+)\)/),E=H?Number(H[1]):void 0;if(G0(h))return"string";return E!==void 0&&E>255?"text":"string"}if(/text|clob/.test(J))return"text";if(J==="float8"||/^double/.test(J))return"double";if(/^(?:real|float4|float)/.test(J))return"float";if(/^(?:numeric|decimal|money)/.test(J))return"decimal";if(J==="date")return"date";if(J==="timestamptz"||/\bwith time zone\b/.test(G))return"timestamptz";if(/^(?:timestamp|datetime)/.test(J))return"datetime";if(/^time/.test(J))return"string";if(/json/.test(J))return"json";if(/^enum/.test(J))return"enum";return"string"}function QZ($,h,A){return FH(String(h||$||""),"mysql",{enumValues:A})}function CZ($){let h=String($||"").trim().match(/^varchar\((\d+)\)/i);if(!h)return;let A=Number(h[1]);return Number.isSafeInteger(A)&&A>0?A:void 0}function o1($){let h=String($??"").toLowerCase().trim();if(h==="cascade"||h==="restrict"||h==="set null")return h;return}async function KZ($,h){let A=await $.unsafe(`PRAGMA table_info(${JSON.stringify(h)})`),G=await $.unsafe(`PRAGMA index_list(${JSON.stringify(h)})`),J=await $.unsafe(`PRAGMA foreign_key_list(${JSON.stringify(h)})`),H=await $.unsafe("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",[h]),E=String(H?.[0]?.sql??""),Y=new Map;for(let Z of J)Y.set(String(Z.from),{table:String(Z.table),column:String(Z.to??"id"),onDelete:o1(Z.on_delete),onUpdate:o1(Z.on_update)});let U=[],z=new Set;for(let Z of G){let F=String(Z.origin??""),w=String(Z.name??"");if(F==="pk"||w.startsWith("sqlite_autoindex_"))continue;let j=(await $.unsafe(`PRAGMA index_info(${JSON.stringify(w)})`)).map((_)=>String(_.name)).filter(Boolean);if(j.length===0)continue;let O=Number(Z.unique)===1;if(O&&j.length===1)z.add(j[0]);U.push({name:w,columns:j,type:O?"unique":"index"})}let W=A.map((Z)=>{let F=String(Z.name),w=BZ(E,F),B=Number(Z.pk)>0,j=Z.dflt_value,O=j!==null&&j!==void 0;return{name:F,type:FH(String(Z.type??""),"sqlite",{enumValues:w}),isPrimaryKey:B,isUnique:z.has(F),isNullable:B?!1:Number(Z.notnull)===0,hasDefault:O,defaultValue:O?RH(j):void 0,enumValues:w,references:Y.get(F)}});return{table:h,columns:W,indexes:U}}function BZ($,h){if(!$)return;let A=new RegExp(`(?:"${h}"|\`${h}\`|\\b${h}\\b)\\s+IN\\s*\\(([^)]*)\\)`,"i"),G=$.match(A);if(!G)return;let J=G[1].split(",").map((H)=>H.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((H)=>H.length>0);return J.length>0?J:void 0}function RH($){if(typeof $==="number"||typeof $==="boolean")return $;return String($)}async function a9($){let h=await $.unsafe(`SELECT t.typname AS type_name, e.enumlabel AS label
|
|
257
|
-
FROM pg_type t
|
|
258
|
-
JOIN pg_enum e ON e.enumtypid = t.oid
|
|
259
|
-
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
260
|
-
WHERE n.nspname = 'public'
|
|
261
|
-
ORDER BY t.typname, e.enumsortorder`),A=new Map;for(let G of h){let J=String(G.type_name),H=A.get(J);if(H)H.push(String(G.label));else A.set(J,[String(G.label)])}return A}function IZ($,h,A){let G=A.get(h),J=FH(String($||h||""),"postgres",{enumValues:G});return G?{type:J,enumValues:G,enumTypeName:h}:{type:J}}async function PZ($,h,A){let G=A??await a9($),J=await $.unsafe(`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length,
|
|
262
|
-
(SELECT COUNT(*) FROM information_schema.table_constraints tc
|
|
263
|
-
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name
|
|
264
|
-
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_name = c.table_name AND k.column_name = c.column_name) AS is_pk
|
|
265
|
-
FROM information_schema.columns c
|
|
266
|
-
WHERE c.table_name = $1 AND c.table_schema = 'public'
|
|
267
|
-
ORDER BY c.ordinal_position`,[h]),H=await $.unsafe(`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
|
|
268
|
-
a.attname AS column_name, array_position(ix.indkey, a.attnum) AS ord,
|
|
269
|
-
pg_get_expr(ix.indpred, ix.indrelid) AS where_clause
|
|
270
|
-
FROM pg_class t
|
|
271
|
-
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
272
|
-
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
273
|
-
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
|
|
274
|
-
WHERE t.relname = $1 AND t.relkind = 'r'
|
|
275
|
-
ORDER BY i.relname, ord`,[h]),E=await $.unsafe(`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column,
|
|
276
|
-
tc.constraint_name, rc.delete_rule, rc.update_rule
|
|
277
|
-
FROM information_schema.table_constraints tc
|
|
278
|
-
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name
|
|
279
|
-
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name
|
|
280
|
-
JOIN information_schema.referential_constraints rc ON rc.constraint_name = tc.constraint_name
|
|
281
|
-
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1 AND tc.table_schema = 'public'`,[h]),Y=new Map,U=new Map;for(let F of E){let w=String(F.constraint_name);U.set(w,(U.get(w)??0)+1)}for(let F of E){let w=String(F.column_name),B=Y.get(w),j=String(F.constraint_name),O=U.get(j)===1?[...new Set([...B?.constraintNames??[],j])]:B?.constraintNames;Y.set(w,B?{...B,constraintNames:O}:{table:String(F.ref_table),column:String(F.ref_column??"id"),onDelete:o1(F.delete_rule),onUpdate:o1(F.update_rule),constraintNames:O})}let{indexes:z,uniqueColumns:W}=e9(h,H.map((F)=>({indexName:String(F.index_name),isUnique:F.is_unique===!0||F.is_unique==="t",isPrimary:F.is_primary===!0||F.is_primary==="t",column:String(F.column_name),where:F.where_clause?String(F.where_clause):void 0}))),Z=J.map((F)=>{let w=String(F.column_name),B=Number(F.is_pk)>0,j=F.column_default==null?null:String(F.column_default),O=j!=null&&/nextval\(/i.test(j),_=j!=null&&!O;return{name:w,...IZ(String(F.data_type??""),F.udt_name==null?"":String(F.udt_name),G),isPrimaryKey:B,isUnique:W.has(w),isNullable:B?!1:String(F.is_nullable).toUpperCase()==="YES",hasDefault:_,defaultValue:_?RH(j):void 0,references:Y.get(w)}});return{table:h,columns:Z,indexes:z}}async function NZ($,h){let A=await $.unsafe(`SELECT column_name, data_type, column_type, is_nullable, column_default, column_key
|
|
282
|
-
FROM information_schema.columns
|
|
283
|
-
WHERE table_name = ? AND table_schema = DATABASE()
|
|
284
|
-
ORDER BY ordinal_position`,[h]),G=await $.unsafe(`SELECT index_name, non_unique, seq_in_index, column_name
|
|
285
|
-
FROM information_schema.statistics
|
|
286
|
-
WHERE table_name = ? AND table_schema = DATABASE()
|
|
287
|
-
ORDER BY index_name, seq_in_index`,[h]),J=await $.unsafe(`SELECT kcu.column_name, kcu.referenced_table_name AS ref_table, kcu.referenced_column_name AS ref_column,
|
|
288
|
-
kcu.constraint_name, rc.delete_rule, rc.update_rule
|
|
289
|
-
FROM information_schema.key_column_usage kcu
|
|
290
|
-
JOIN information_schema.referential_constraints rc
|
|
291
|
-
ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.table_schema
|
|
292
|
-
WHERE kcu.table_name = ? AND kcu.table_schema = DATABASE() AND kcu.referenced_table_name IS NOT NULL`,[h]),H=new Map,E=new Map;for(let W of J){let Z=String(W.constraint_name??W.CONSTRAINT_NAME);E.set(Z,(E.get(Z)??0)+1)}for(let W of J){let Z=String(W.column_name??W.COLUMN_NAME),F=H.get(Z),w=String(W.constraint_name??W.CONSTRAINT_NAME),B=E.get(w)===1?[...new Set([...F?.constraintNames??[],w])]:F?.constraintNames;H.set(Z,F?{...F,constraintNames:B}:{table:String(W.ref_table??W.REF_TABLE),column:String(W.ref_column??W.REF_COLUMN??"id"),onDelete:o1(W.delete_rule??W.DELETE_RULE),onUpdate:o1(W.update_rule??W.UPDATE_RULE),constraintNames:B})}let{indexes:Y,uniqueColumns:U}=e9(h,G.map((W)=>({indexName:String(W.index_name??W.INDEX_NAME),isUnique:Number(W.non_unique??W.NON_UNIQUE)===0,isPrimary:String(W.index_name??W.INDEX_NAME).toUpperCase()==="PRIMARY",column:String(W.column_name??W.COLUMN_NAME)}))),z=A.map((W)=>{let Z=String(W.column_name??W.COLUMN_NAME),F=String(W.column_type??W.COLUMN_TYPE??""),w=TZ(F),j=String(W.column_key??W.COLUMN_KEY??"").toUpperCase()==="PRI",O=W.column_default??W.COLUMN_DEFAULT,_=O!=null;return{name:Z,type:QZ(W.data_type??W.DATA_TYPE,F,w),isPrimaryKey:j,isUnique:U.has(Z),isNullable:j?!1:String(W.is_nullable??W.IS_NULLABLE).toUpperCase()==="YES",hasDefault:_,defaultValue:_?RH(O):void 0,enumValues:w,maxLength:CZ(F),references:H.get(Z)}});return{table:h,columns:z,indexes:Y}}function TZ($){let h=$.match(/^enum\((.*)\)$/i);if(!h)return;return h[1].split(",").map((A)=>A.trim().replace(/^'(.*)'$/s,"$1").replace(/''/g,"'")).filter((A)=>A.length>0)}function e9($,h){let A=new Map;for(let H of h){if(H.isPrimary)continue;let E=A.get(H.indexName)??{isUnique:H.isUnique,isPrimary:H.isPrimary,columns:[],where:H.where};E.columns.push(H.column),A.set(H.indexName,E)}let G=[],J=new Set;for(let[H,E]of A){if(E.columns.length===0)continue;if(E.isUnique&&E.columns.length===1)J.add(E.columns[0]);G.push({name:H,columns:E.columns,type:E.isUnique?"unique":"index",where:E.where})}return{indexes:G,uniqueColumns:J}}async function $U($,h={}){let A=$||v.dialect||"postgres",G=J0(),H=((h.tables?.length)?h.tables:await o9(G,A)).filter((U)=>U!=="migrations"),E=A==="postgres"?await a9(G):void 0,Y=[];for(let U of H){let z;if(A==="sqlite")z=await KZ(G,U);else if(A==="postgres")z=await PZ(G,U,E);else z=await NZ(G,U);if(z.columns.length>0)Y.push(z)}return{dialect:A,tables:Y}}var NG=a(()=>{f0();m0()});import{existsSync as wH,mkdirSync as kZ,writeFileSync as yZ}from"fs";import{dirname as hU,join as _H}from"path";import AU from"process";function qZ($){let h=$;while(h!==hU(h)){if(wH(_H(h,"package.json")))return h;h=hU(h)}return AU.cwd()}async function xZ($,h={}){let A=qZ(AU.cwd()),G=h.dir||_H(A,"app/Models");if(!wH(G))kZ(G,{recursive:!0}),console.log(`-- Created models directory: ${G}`);let J=$.charAt(0).toUpperCase()+$.slice(1),H=h.table||`${$.toLowerCase()}s`,E=`${J}.ts`,Y=_H(G,E);if(wH(Y))throw console.error(`-- Model already exists: ${Y}`),Error(`Model already exists: ${Y}`);let z=h.timestamps!==!1?` created_at: { validation: { rule: v.date() } },
|
|
293
|
-
updated_at: { validation: { rule: v.date() } },`:"",W=`import { v } from '@stacksjs/ts-validation'
|
|
294
|
-
import { defineModel } from 'bun-query-builder'
|
|
295
|
-
|
|
296
|
-
const model = defineModel({
|
|
297
|
-
name: '${J}',
|
|
298
|
-
table: '${H}',
|
|
299
|
-
primaryKey: 'id',
|
|
300
|
-
attributes: {
|
|
301
|
-
id: { validation: { rule: v.integer() } },
|
|
302
|
-
${z}
|
|
303
|
-
// Add your model attributes here
|
|
304
|
-
// Example:
|
|
305
|
-
// name: { validation: { rule: v.string() } },
|
|
306
|
-
// email: { unique: true, validation: { rule: v.string().email() } },
|
|
307
|
-
// age: { default: 0, validation: { rule: v.number().min(0) } },
|
|
308
|
-
},
|
|
309
|
-
})
|
|
310
|
-
|
|
311
|
-
export default model
|
|
312
|
-
`;yZ(Y,W),console.log(`-- \u2713 Created model: ${Y}`),console.log(`-- Table: ${H}`)}var GU=()=>{};function fZ($){let h=2166136261;for(let A=0;A<$.length;A++)h^=$.charCodeAt(A),h=Math.imul(h,16777619)>>>0;return h.toString(36).padStart(7,"0").slice(-7)}function gZ($,h=63){if($.length<=h)return $;let A=`_${fZ($)}`;return $.slice(0,h-A.length)+A}function K$($,h){let A=`${$}_`,G=h.startsWith(A)?h:`${A}${h}`;return gZ(G)}class d0{quoteIdentifier($){return`\`${$.replace(/`/g,"``")}\``}getColumnType($){switch($.type){case"string":return`varchar(${$.maxLength??255})`;case"text":return"text";case"boolean":return"tinyint(1)";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"datetime";case"timestamptz":return"datetime";case"json":return"json";case"enum":if($.enumValues&&$.enumValues.length>0)return`ENUM(${$.enumValues.map((A)=>`'${A.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 h=$.defaultValue;if(typeof h==="string"){let A=h.toUpperCase();if(A==="UTC_TIMESTAMP")return"default (UTC_TIMESTAMP)";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(A))return`default ${A}`;let J=`'${h.replace(/'/g,"''")}'`;if($.type==="text"||$.type==="json"||$.type==="enum"&&!$.enumValues?.length)return`default (${J})`;return`default ${J}`}else if(typeof h==="number"||typeof h==="bigint")return`default ${h}`;else if(typeof h==="boolean")return`default ${h?1:0}`;else if(h instanceof Date)return`default '${h.toISOString()}'`;return""}createEnumType($,h){return""}foreignKeyClauses($){return $.columns.filter((h)=>h.references).map((h)=>{let A=h.references,G=`${$.table}_${h.name}_fk`,J=`CONSTRAINT ${this.quoteIdentifier(G)} FOREIGN KEY (${this.quoteIdentifier(h.name)}) REFERENCES ${this.quoteIdentifier(A.table)}(${this.quoteIdentifier(A.column)})`;if(A.onDelete)J+=` ON DELETE ${A.onDelete.toUpperCase()}`;if(A.onUpdate)J+=` ON UPDATE ${A.onUpdate.toUpperCase()}`;return J})}createTable($){let h=[...$.columns.map((A)=>this.renderColumn(A)),...this.foreignKeyClauses($)];return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
313
|
-
${h.join(`,
|
|
314
|
-
`)}
|
|
315
|
-
) DEFAULT CHARSET=utf8mb4;`}static KEY_PREFIX_CHARACTERS=255;static MAX_KEY_BYTES=3072;static BYTES_PER_CHARACTER=4;keyPartWidth($){let h=this.getColumnType($).toLowerCase();if(h.includes("text")||h.includes("blob")||h==="json")return{bytes:Number.POSITIVE_INFINITY,indexableWhole:!1};let A=h.match(/^(?:var)?char\((\d+)\)$/)?.[1];if(A!==void 0)return{bytes:Number(A)*d0.BYTES_PER_CHARACTER,indexableWhole:!0};return{bytes:8,indexableWhole:!0}}keyParts($,h,A){let G=h.columns.map((H)=>{let E=A?.find((z)=>z.name===H),Y=E?this.keyPartWidth(E):{bytes:0,indexableWhole:!0},U=!Y.indexableWhole;return{name:H,prefixed:U,bytes:U?d0.KEY_PREFIX_CHARACTERS*d0.BYTES_PER_CHARACTER:Y.bytes,narrowable:!Y.indexableWhole||Y.bytes>d0.KEY_PREFIX_CHARACTERS*d0.BYTES_PER_CHARACTER}}),J=()=>G.reduce((H,E)=>H+E.bytes,0);while(J()>d0.MAX_KEY_BYTES){let H=G.filter((E)=>E.narrowable&&!E.prefixed).sort((E,Y)=>Y.bytes-E.bytes)[0];if(!H)throw Error(`[migrations] Index '${h.name}' on table '${$}' needs ${J()} bytes of key, over MySQL's ${d0.MAX_KEY_BYTES}. Every column in it is already at its ${d0.KEY_PREFIX_CHARACTERS}-character prefix, so shorten a column or drop one from the index.`);H.prefixed=!0,H.bytes=d0.KEY_PREFIX_CHARACTERS*d0.BYTES_PER_CHARACTER}return G.map((H)=>H.prefixed?`${this.quoteIdentifier(H.name)}(${d0.KEY_PREFIX_CHARACTERS})`:this.quoteIdentifier(H.name))}createIndex($,h,A){if(h.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on MySQL. Index '${h.name}' on table '${$}' uses WHERE clause: ${h.where}`);let G=h.type==="unique"?"UNIQUE ":"",J=K$($,h.name),H=this.keyParts($,h,A).join(", ");return`CREATE ${G}INDEX ${this.quoteIdentifier(J)} ON ${this.quoteIdentifier($)} (${H});`}addForeignKey($,h,A,G,J,H,E=[]){let Y=`${$}_${h}_fk`,U=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(Y)} FOREIGN KEY (${this.quoteIdentifier(h)}) REFERENCES ${this.quoteIdentifier(A)}(${this.quoteIdentifier(G)})`;if(J)U+=` ON DELETE ${J.toUpperCase()}`;if(H)U+=` ON UPDATE ${H.toUpperCase()}`;let z=[...new Set(E)].map((W)=>`ALTER TABLE ${this.quoteIdentifier($)} DROP FOREIGN KEY ${this.quoteIdentifier(W)};`).join(`
|
|
316
|
-
`);return z?`${z}
|
|
317
|
-
${U};`:`${U};`}addColumn($,h){let A=this.getColumnType(h),G=[this.quoteIdentifier(h.name),A];if(!h.isNullable&&!h.isPrimaryKey)G.push("not null");let J=this.getDefaultValue(h);if(J)G.push(J);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${G.join(" ")};`}modifyColumn($,h){let A=this.getColumnType(h),G=[this.quoteIdentifier(h.name),A];if(!h.isNullable&&!h.isPrimaryKey)G.push("not null");let J=this.getDefaultValue(h);if(J)G.push(J);return`ALTER TABLE ${this.quoteIdentifier($)} MODIFY COLUMN ${G.join(" ")};`}renameColumn($,h,A){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME COLUMN ${this.quoteIdentifier(h)} TO ${this.quoteIdentifier(A)};`}renameTable($,h){return`RENAME TABLE ${this.quoteIdentifier($)} TO ${this.quoteIdentifier(h)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; MySQL uses in-place ALTER.")}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,h){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(h)};`}dropIndex($,h){let A=K$($,h);return`DROP INDEX ${this.quoteIdentifier(A)} ON ${this.quoteIdentifier($)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
318
|
-
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
319
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
320
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
321
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract($,h){return`JSON_UNQUOTE(JSON_EXTRACT(${$}, CONCAT('$.', ${h})))`}dateBucket($,h,A=0){let G=A===0?$:`DATE_ADD(${$}, INTERVAL ${A} HOUR)`;switch(h){case"hour":return`DATE_FORMAT(${G}, '%Y-%m-%dT%H:00:00.000Z')`;case"week":return`DATE_FORMAT(DATE_SUB(${G}, INTERVAL WEEKDAY(${G}) DAY), '%Y-%m-%dT00:00:00.000Z')`;case"month":return`DATE_FORMAT(${G}, '%Y-%m-01T00:00:00.000Z')`;case"year":return`DATE_FORMAT(${G}, '%Y-01-01T00:00:00.000Z')`;case"day":default:return`DATE_FORMAT(${G}, '%Y-%m-%dT00:00:00.000Z')`}}booleanLiteral($){return $?"TRUE":"FALSE"}renderColumn($){let h=this.getColumnType($),A=[this.quoteIdentifier($.name),h];if($.isPrimaryKey){A.push("PRIMARY KEY");let J=this.getAutoIncrementClause($);if(J)A.push(J)}if(!$.isNullable&&!$.isPrimaryKey)A.push("not null");let G=this.getDefaultValue($);if(G)A.push(G);return A.join(" ")}}var ah=()=>{};class TG{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){switch($.type){case"string":return`varchar(${$.maxLength??255})`;case"text":return"text";case"boolean":return"boolean";case"integer":return"integer";case"bigint":return"bigint";case"float":return"real";case"double":return"double precision";case"decimal":return"decimal(10,2)";case"date":return"date";case"datetime":return"timestamp";case"timestamptz":return"timestamptz";case"json":return"jsonb";case"enum":if($.enumValues&&$.enumValues.length>0)return $.enumTypeName?this.quoteIdentifier($.enumTypeName):"text";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 h=$.defaultValue;if(typeof h==="string"){let A=h.toUpperCase();if(A==="UTC_TIMESTAMP")return"default (now() AT TIME ZONE 'utc')";if(["CURRENT_TIMESTAMP","NOW()","NULL","CURRENT_DATE","CURRENT_TIME"].includes(A))return`default ${A}`;return`default '${h.replace(/'/g,"''")}'`}else if(typeof h==="number"||typeof h==="bigint")return`default ${h}`;else if(typeof h==="boolean")return`default ${h?"true":"false"}`;else if(h instanceof Date)return`default '${h.toISOString()}'`;return""}createEnumType($,h){let A=h.map((G)=>`'${G.replace(/'/g,"''")}'`).join(", ");return`CREATE TYPE ${this.quoteIdentifier($)} AS ENUM (${A});`}createTable($){let h=$.columns.map((A)=>this.renderColumn(A)).join(`,
|
|
322
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
323
|
-
${h}
|
|
324
|
-
);`}createIndex($,h){let A=h.type==="unique"?"UNIQUE ":"",G=K$($,h.name),J=h.columns.map((E)=>this.quoteIdentifier(E)).join(", "),H=h.where?` WHERE ${h.where}`:"";return`CREATE ${A}INDEX IF NOT EXISTS ${this.quoteIdentifier(G)} ON ${this.quoteIdentifier($)} (${J})${H};`}addForeignKey($,h,A,G,J,H,E=[]){let Y=`${$}_${h}_fk`,U=`ALTER TABLE ${this.quoteIdentifier($)} ADD CONSTRAINT ${this.quoteIdentifier(Y)} FOREIGN KEY (${this.quoteIdentifier(h)}) REFERENCES ${this.quoteIdentifier(A)}(${this.quoteIdentifier(G)})`;if(J)U+=` ON DELETE ${J.toUpperCase()}`;if(H)U+=` ON UPDATE ${H.toUpperCase()}`;let z=[...new Set(E)].map((W)=>`ALTER TABLE ${this.quoteIdentifier($)} DROP CONSTRAINT ${this.quoteIdentifier(W)};`).join(`
|
|
325
|
-
`);return z?`${z}
|
|
326
|
-
${U};`:`${U};`}addColumn($,h){let A=this.getColumnType(h),G=[this.quoteIdentifier(h.name),A];if(!h.isNullable&&!h.isPrimaryKey)G.push("not null");let J=this.getDefaultValue(h);if(J)G.push(J);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${G.join(" ")};`}modifyColumn($,h){let A=this.getColumnType(h),G=this.quoteIdentifier($),J=this.quoteIdentifier(h.name),H=[`ALTER TABLE ${G} ALTER COLUMN ${J} DROP DEFAULT;`,`ALTER TABLE ${G} ALTER COLUMN ${J} TYPE ${A} USING ${J}::${A};`];if(!h.isPrimaryKey)H.push(`ALTER TABLE ${G} ALTER COLUMN ${J} ${h.isNullable?"DROP NOT NULL":"SET NOT NULL"};`);let E=this.getDefaultValue(h);if(E)H.push(`ALTER TABLE ${G} ALTER COLUMN ${J} SET ${E};`);return H.join(`
|
|
327
|
-
`)}renameColumn($,h,A){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME COLUMN ${this.quoteIdentifier(h)} TO ${this.quoteIdentifier(A)};`}renameTable($,h){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME TO ${this.quoteIdentifier(h)};`}rebuildTable(){throw Error("[migrations] rebuildTable is only implemented for SQLite; Postgres uses in-place ALTER.")}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}dropColumn($,h){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(h)};`}dropIndex($,h){let A=K$($,h);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(A)};`}dropEnumType($){return`DROP TYPE IF EXISTS ${this.quoteIdentifier($)} CASCADE`}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
328
|
-
id SERIAL PRIMARY KEY,
|
|
329
|
-
migration VARCHAR(255) NOT NULL UNIQUE,
|
|
330
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
331
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES ($1)"}jsonExtract($,h){return`(${$}::jsonb ->> ${h})`}dateBucket($,h,A=0){let G=A===0?`${$}::timestamp`:`(${$}::timestamp ${A>=0?"+":"-"} interval '${Math.abs(A)} hours')`,J=h==="week"?`date_trunc('week', ${G})`:G;switch(h){case"hour":return`to_char(${J}, 'YYYY-MM-DD"T"HH24:00:00.000"Z"')`;case"month":return`to_char(${J}, 'YYYY-MM-01"T"00:00:00.000"Z"')`;case"year":return`to_char(${J}, 'YYYY-01-01"T"00:00:00.000"Z"')`;case"week":case"day":default:return`to_char(${J}, 'YYYY-MM-DD"T"00:00:00.000"Z"')`}}booleanLiteral($){return $?"TRUE":"FALSE"}renderColumn($){let h=$.isPrimaryKey?this.getPrimaryKeyType($):this.getColumnType($),A=[this.quoteIdentifier($.name),h];if($.isPrimaryKey)A.push("PRIMARY KEY");if(!$.isNullable&&!$.isPrimaryKey)A.push("not null");let G=this.getDefaultValue($);if(G)A.push(G);if($.references){let J=`REFERENCES ${this.quoteIdentifier($.references.table)}(${this.quoteIdentifier($.references.column)})`;if($.references.onDelete)J+=` ON DELETE ${$.references.onDelete.toUpperCase()}`;if($.references.onUpdate)J+=` ON UPDATE ${$.references.onUpdate.toUpperCase()}`;A.push(J)}return A.join(" ")}}var OH=()=>{};var kG;var DH=a(()=>{ah();kG=class kG extends d0{createTable($){let h=$.columns.map((H)=>this.renderColumn(H)).join(`,
|
|
332
|
-
`),A=[];if($.tableKind!=="reference"){let H=$.shardKey?.length?$.shardKey:$.columns.filter((E)=>E.isPrimaryKey).map((E)=>E.name);if(H&&H.length>0)A.push(`SHARD KEY (${H.map((E)=>this.quoteIdentifier(E)).join(", ")})`)}if($.tableKind!=="rowstore"&&$.tableKind!=="reference"){let H=$.sortKey?.length?$.sortKey:void 0;A.push(`SORT KEY (${(H??[]).map((E)=>this.quoteIdentifier(E)).join(", ")})`)}let G=[h,...A].join(`,
|
|
333
|
-
`);return`CREATE${this.tableKindSuffix($.tableKind)} TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
334
|
-
${G}
|
|
335
|
-
);`}tableKindSuffix($){switch($){case"rowstore":return" ROWSTORE";case"reference":return" REFERENCE";default:return""}}addForeignKey(){return""}createIndex($,h,A){if(h.where)throw Error(`[migrations] Partial indexes (CompositeIndex.where) are not supported on SingleStore. Index '${h.name}' on table '${$}' uses WHERE clause: ${h.where}`);return super.createIndex($,h,A)}}});var yG;var VH=a(()=>{ah();yG=class yG extends d0{sharded;constructor($=!0){super();this.sharded=$}getAutoIncrementClause($){return this.sharded?"":super.getAutoIncrementClause($)}renderColumn($){if(!this.sharded||!$.references)return super.renderColumn($);let{references:h,...A}=$;return super.renderColumn(A)}foreignKeyClauses($){return this.sharded?[]:super.foreignKeyClauses($)}createTable($){return super.createTable($)}addForeignKey(...$){return this.sharded?"":super.addForeignKey(...$)}createMigrationsTable(){if(!this.sharded)return super.createMigrationsTable();return`CREATE TABLE IF NOT EXISTS migrations (
|
|
336
|
-
migration VARCHAR(255) NOT NULL PRIMARY KEY,
|
|
337
|
-
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
338
|
-
)`}}});function t1($){return $==="integer"||$==="bigint"||$==="float"||$==="double"||$==="decimal"}function JU($){if(typeof $!=="string")return;switch($.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function qG($){switch($){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}class xG{quoteIdentifier($){return`"${$.replace(/"/g,'""')}"`}getColumnType($){if($.name.endsWith("_id")&&t1($.type))return"INTEGER";if($.type==="enum"){if($.enumValues&&$.enumValues.length>0){let h=$.enumValues.map((A)=>`'${A.replace(/'/g,"''")}'`).join(", ");return`TEXT CHECK (${this.quoteIdentifier($.name)} IN (${h}))`}return"TEXT"}return qG($.type)}getPrimaryKeyType($){return this.getColumnType($)}getAutoIncrementClause($){if($.isPrimaryKey&&($.type==="integer"||$.type==="bigint"))return"AUTOINCREMENT";return""}getDefaultValue($){if(!$.hasDefault||$.defaultValue===void 0)return"";let h=$.defaultValue;if(typeof h==="string"){if(h.toUpperCase()==="UTC_TIMESTAMP")return"default CURRENT_TIMESTAMP";if(["CURRENT_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","NOW()","NULL","TRUE","FALSE"].includes(h.toUpperCase()))return`default ${h.toUpperCase()}`;return`default '${h.replace(/'/g,"''")}'`}else if(typeof h==="number"||typeof h==="bigint")return`default ${h}`;else if(typeof h==="boolean")return`default ${h?1:0}`;else if(h instanceof Date)return`default '${h.toISOString()}'`;return""}createEnumType($,h){return""}createTable($){let h=$.columns.map((A)=>this.renderColumn(A)).join(`,
|
|
339
|
-
`);return`CREATE TABLE IF NOT EXISTS ${this.quoteIdentifier($.table)} (
|
|
340
|
-
${h}
|
|
341
|
-
);`}createIndex($,h){let A=h.type==="unique"?"UNIQUE ":"",G=K$($,h.name),J=h.columns.map((E)=>this.quoteIdentifier(E)).join(", "),H=h.where?` WHERE ${h.where}`:"";return`CREATE ${A}INDEX IF NOT EXISTS ${this.quoteIdentifier(G)} ON ${this.quoteIdentifier($)} (${J})${H};`}addForeignKey($,h,A,G,J,H){return""}addColumn($,h){let A=this.getColumnType(h),G=[this.quoteIdentifier(h.name),A];if(!h.isNullable&&!h.isPrimaryKey)G.push("not null");let J=this.getDefaultValue(h);if(J)G.push(J);return`ALTER TABLE ${this.quoteIdentifier($)} ADD COLUMN ${G.join(" ")};`}modifyColumn($,h){return`-- SQLite does not support ALTER COLUMN; a table rebuild is required to change ${this.quoteIdentifier($)}.${this.quoteIdentifier(h.name)}`}renameColumn($,h,A){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME COLUMN ${this.quoteIdentifier(h)} TO ${this.quoteIdentifier(A)};`}renameTable($,h){return`ALTER TABLE ${this.quoteIdentifier($)} RENAME TO ${this.quoteIdentifier(h)};`}rebuildTable($){let{target:h,tempName:A,columnSource:G}=$,J=(z)=>this.quoteIdentifier(z),H=h.columns.map((z)=>this.renderColumn(z)).join(`,
|
|
342
|
-
`),E=`CREATE TABLE ${J(A)} (
|
|
343
|
-
${H}
|
|
344
|
-
);`,Y=h.columns.map((z)=>z.name).filter((z)=>G[z]!==void 0),U=["PRAGMA foreign_keys=OFF;","BEGIN;",E];if(Y.length>0){let z=Y.map(J).join(", "),W=Y.map((Z)=>J(G[Z])).join(", ");U.push(`INSERT INTO ${J(A)} (${z}) SELECT ${W} FROM ${J(h.table)};`)}U.push(`DROP TABLE ${J(h.table)};`),U.push(`ALTER TABLE ${J(A)} RENAME TO ${J(h.table)};`);for(let z of h.indexes)U.push(this.createIndex(h.table,z));return U.push("PRAGMA foreign_key_check;"),U.push("COMMIT;"),U.push("PRAGMA foreign_keys=ON;"),U.join(`
|
|
345
|
-
`)}dropTable($){return`DROP TABLE IF EXISTS ${this.quoteIdentifier($)}`}dropColumn($,h){return`ALTER TABLE ${this.quoteIdentifier($)} DROP COLUMN ${this.quoteIdentifier(h)};`}dropIndex($,h){let A=K$($,h);return`DROP INDEX IF EXISTS ${this.quoteIdentifier(A)};`}dropEnumType($){return""}createMigrationsTable(){return`CREATE TABLE IF NOT EXISTS migrations (
|
|
346
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
347
|
-
migration TEXT NOT NULL UNIQUE,
|
|
348
|
-
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
349
|
-
)`}getExecutedMigrationsQuery(){return"SELECT migration, executed_at FROM migrations ORDER BY executed_at"}recordMigrationQuery(){return"INSERT INTO migrations (migration) VALUES (?)"}jsonExtract($,h){return`json_extract(${$}, '$.' || ${h})`}dateBucket($,h,A=0){let G=A===0?$:`datetime(${$}, '${A>=0?"+":"-"}${Math.abs(A)} hours')`;switch(h){case"hour":return`strftime('%Y-%m-%dT%H:00:00.000Z', ${G})`;case"week":return`strftime('%Y-%m-%dT00:00:00.000Z', ${G}, '-6 days', 'weekday 1')`;case"month":return`strftime('%Y-%m-01T00:00:00.000Z', ${G})`;case"year":return`strftime('%Y-01-01T00:00:00.000Z', ${G})`;case"day":default:return`strftime('%Y-%m-%dT00:00:00.000Z', ${G})`}}booleanLiteral($){return $?"TRUE":"FALSE"}renderColumn($){let h=this.getColumnType($),A=[this.quoteIdentifier($.name),h];if($.isPrimaryKey){A.push("PRIMARY KEY");let J=this.getAutoIncrementClause($);if(J)A.push(J)}if(!$.isNullable&&!$.isPrimaryKey)A.push("not null");let G=this.getDefaultValue($);if(G)A.push(G);if($.references){if(A.push(`REFERENCES ${this.quoteIdentifier($.references.table)}(${this.quoteIdentifier($.references.column)})`),$.references.onDelete)A.push(`ON DELETE ${$.references.onDelete.toUpperCase()}`);if($.references.onUpdate)A.push(`ON UPDATE ${$.references.onUpdate.toUpperCase()}`)}return A.join(" ")}}var fG=()=>{};function y$($,h={}){switch($){case"postgres":return new TG;case"mysql":return new d0;case"singlestore":return new kG;case"vitess":return new yG(h.vitessSharded??v.vitess?.sharded??!0);case"sqlite":return new xG;default:throw Error(`Unsupported dialect: ${$}`)}}var eh=a(()=>{f0();ah();OH();DH();VH();fG();ah();OH();DH();fG();VH()});import{existsSync as vZ}from"fs";import{dirname as HU,isAbsolute as bZ,join as UU}from"path";import EU from"process";function MH($=EU.cwd()){let h=$;while(h!==HU(h)){if(vZ(UU(h,"package.json")))return h;h=HU(h)}return EU.cwd()}function u$($,h="database/migrations"){let A=h||"database/migrations";return bZ(A)?A:UU($??MH(),A)}var $A=()=>{};var QU={};jJ(QU,{saveMigrationSnapshot:()=>wU,resetDatabase:()=>DU,generateMigration:()=>vG,executeMigration:()=>OU,deleteMigrationFiles:()=>VU,copyModelsToGenerated:()=>rZ,clearGeneratedDirectory:()=>MU});import{existsSync as i$,mkdirSync as WU,mkdtempSync as cZ,readdirSync as ZU,readFileSync as hA,rmSync as XU,unlinkSync as SH,writeFileSync as jU}from"fs";import{tmpdir as mZ}from"os";import{join as Z$}from"path";import QH from"process";async function dZ($,h,A){if(A.length===0)return;let G=_U(B1());try{await SU($,h);for(let J of A)await gG($,J,h),A0(`-- \u2713 Recorded applied migration: ${J}`)}catch(J){A0(`-- Could not record applied migrations (the schema change itself succeeded): ${J instanceof Error?J.message:String(J)}`)}}function LU($,h){try{return KU(hA(Z$($,h),"utf8"))}catch{return!1}}function pZ($){let h=$ instanceof Error?$.message:String($);return/duplicate column name/i.test(h)||/duplicate key name/i.test(h)||/\balready exists\b/i.test(h)}function A0($){if(v.verbose)console.log($)}function FU($){return Z$($,v.snapshotDir||".qb")}function CH($,h){return Z$(FU($),`model-snapshot.${h}.json`)}function nZ($,h){let A=CH($,h);if(!i$(A))return;try{let G=hA(A,"utf8"),J=JSON.parse(G);if(J?.plan&&Array.isArray(J.plan.tables)&&J.plan.dialect)return J.plan;if(Array.isArray(J?.tables)&&J?.dialect)return J;A0("-- Invalid snapshot format, treating as no previous state");return}catch(G){A0(`-- Could not load snapshot, treating as no previous state: ${G instanceof Error?G.message:String(G)}`);return}}function RU($,h,A){let G=CH($,h),J=FU($),H=BU(A);if(i$(G))try{let Y=JSON.parse(hA(G,"utf8"));if(Y?.hash===H&&Y?.dialect===h&&Y?.plan){A0("-- Model snapshot unchanged");return}}catch{}if(!i$(J))WU(J,{recursive:!0}),A0(`-- Created snapshot directory: ${J}`);let E={plan:A,hash:H,dialect:h,updatedAt:new Date().toISOString()};jU(G,JSON.stringify(E,null,2)),A0(`-- Model snapshot saved to ${G}`)}function wU($,h={}){let A=h.dialect??$.dialect;RU(h.workspaceRoot??B1(),A,$)}function B1(){return MH()}function _U($){let h=u$($,v.migrationDir);if(!i$(h))WU(h,{recursive:!0}),A0(`-- Created SQL directory: ${h}`);return h}async function vG($,h={}){if(await DG(),!$)$=Z$(QH.cwd(),"app/Models");let A=h.dialect||v.dialect||"postgres",G=B1(),J=await C$({modelsDir:$}),H=AA(J,{dialect:A,vitessSharded:h.vitessSharded}),E,Y=!1;if(!h.full)if(E=nZ(G,A),E)A0("-- Comparing with stored model snapshot");else{let w=Z$($,`.qb-migrations.${A}.json`),B=String(h.state||w);if(i$(B))try{let j=hA(B,"utf8"),O=JSON.parse(j);if(E=O?.plan&&O.plan.tables?O.plan:O?.tables?O:void 0,E)A0("-- Comparing with legacy state file (will migrate to new snapshot format)")}catch{}if(!E||h.fromDb)try{let j=await $U(A),O=new Set(H.tables.map((R)=>R.table)),_=j.tables.filter((R)=>O.has(R.table));if(_.length>0)E={dialect:j.dialect,tables:_},Y=!0,A0(`-- No snapshot; reconciling against live database (${_.length} matching table${_.length===1?"":"s"})`)}catch(j){A0(`-- Could not introspect live database, treating as no previous state: ${j instanceof Error?j.message:String(j)}`)}if(!E)A0("-- No previous snapshot found, generating full migration")}else A0("-- Full migration requested, ignoring any previous state");let U=h.full?{statements:cG(H,{dryRun:h.dryRun}),operations:H.tables.map((w)=>({kind:"create_table",table:w.table,destructive:!1,sql:""}))}:KH(E,H,{applyRenames:h.applyRenames,dryRun:h.dryRun,preserveUnknownColumns:Y}),z=U.statements,W=U.operations,Z=z.join(`
|
|
350
|
-
`),F=z.some((w)=>/\b(?:CREATE|ALTER|DROP)\b/i.test(w));if(h.apply){let w=cZ(Z$(mZ(),"qb-migrate-")),B=Z$(w,"migration.sql");try{if(F){jU(B,Z);let j=J0();await j.file(B),A0("-- Migration applied"),await dZ(j,A,CU())}else A0("-- No changes; nothing to apply")}catch(j){throw console.error("-- Migration failed:",j),j}finally{XU(w,{recursive:!0,force:!0})}}if(!h.dryRun)RU(G,A,H);return{sql:Z,sqlStatements:z,hasChanges:F,plan:H,operations:W}}function zU($){return $==="postgres"||$==="sqlite"}async function iZ($,h){if($==="sqlite")return await h();let A=J0(),G;try{G=await A.reserve()}catch{return await h()}let J=!1;try{return await G.advisoryLock(YU),J=!0,await h()}finally{try{if(J)await G.advisoryUnlock(YU)}finally{G.release?.()}}}async function OU($){await DG();let h=B1(),A=_U(h),G=v.dialect||"postgres",H=ZU(A).filter((E)=>E.endsWith(".sql")).sort();if(H.length===0)return A0("-- No migration files found to execute"),!0;A0(`-- Found ${H.length} script files to execute`);try{let E=J0();return await iZ(G,async()=>{await SU(E,G);let Y=await lZ(E,G),U=H.filter((z)=>!Y.includes(z));if(U.length===0)return A0("-- No pending migrations to execute"),!0;A0(`-- Executing ${U.length} migration${U.length===1?"":"s"}`);for(let z of U){let W=Z$(A,z);A0(`-- Executing: ${z}`);try{if(zU(G)&&!uZ.test(hA(W,"utf-8")))await E.transaction(async(F)=>{await F.file(W),await gG(F,z,G)});else if(await E.file(W),await gG(E,z,G),!zU(G))A0(`-- (${G} commits DDL implicitly, so ${z} was not applied atomically)`);else A0(`-- (${z} contains a statement that cannot run in a transaction, so it was not applied atomically)`);A0(`-- \u2713 Migration ${z} executed and recorded`)}catch(Z){if(LU(A,z)&&pZ(Z)){await gG(E,z,G),A0(`-- \u2713 Migration ${z} was already applied; recorded it (${Z instanceof Error?Z.message:String(Z)})`);continue}throw console.error(`-- \u2717 Migration ${z} failed:`,Z),Z}}return A0("-- All migrations executed successfully"),!0})}catch(E){throw console.error("-- Migration execution failed:",E),E}return!0}async function DU($,h={}){if(await DG(),!$)$=Z$(QH.cwd(),"app/Models");let A=h.dialect||v.dialect||"postgres",G=y$(A),J=B1(),H=async(E)=>{let Y=G.dropTable(E);await WH(async(U)=>{if(A==="sqlite")await U.unsafe("PRAGMA foreign_keys = OFF").execute();if(A==="mysql"||A==="vitess")await U.unsafe("SET FOREIGN_KEY_CHECKS = 0").execute();try{await U.unsafe(Y).execute()}finally{if(A==="sqlite")await U.unsafe("PRAGMA foreign_keys = ON").execute();if(A==="mysql"||A==="vitess")await U.unsafe("SET FOREIGN_KEY_CHECKS = 1").execute()}})};try{try{await H("migrations"),A0("-- Dropped migrations table")}catch(U){console.error(U)}let E=[],Y=[];try{let U=await C$({modelsDir:$}),z=AA(U,{dialect:A});E=z.tables.map((Z)=>Z.table);let W=new Set;for(let Z of z.tables)for(let F of Z.columns)if(F.type==="enum"&&F.enumValues&&F.enumValues.length>0){let w=`${Z.table}_${F.name}_type`;W.add(w)}Y=Array.from(W)}catch(U){console.error(U),E=[],Y=[]}if(E.length===0)A0("-- No tables found to drop");else{A0(`-- Dropping ${E.length} tables: ${E.join(", ")}`);for(let U of E.reverse())try{await H(U),A0(`-- Dropped table: ${U}`)}catch(z){console.error(z),A0(`-- Table ${U} may not exist, skipping drop`)}}if(Y.length>0){A0(`-- Dropping ${Y.length} enum types: ${Y.join(", ")}`);for(let U of Y)try{let z=G.dropEnumType(U);if(z)await WH(async(W)=>{await W.unsafe(z).execute(),A0(`-- Dropped enum type: ${U}`)})}catch(z){console.error(z),A0(`-- Enum type ${U} may not exist, skipping drop`)}}else A0("-- No enum types found to drop");if(E.length>0&&!h.preserveMigrationState)try{await VU($,J,h)}catch(U){console.error(U),A0("-- Could not clean up migration files")}else if(E.length===0)A0("-- No models directory found; keeping committed migration files in place");else A0("-- Preserving migration files and model snapshot for fresh replay");if(!h.preserveMigrationState)try{await MU(J)}catch(U){console.error(U),A0("-- Could not clear generated directory")}return A0("-- Database reset completed successfully"),!0}catch(E){return console.error("-- Database reset failed:",E),!1}}async function VU($,h,A={}){if(!$)$=Z$(QH.cwd(),"app/Models");if(!h)h=B1();let G=String(A.dialect||v.dialect||"postgres"),J=CH(h,G);if(i$(J))SH(J),A0(`-- Removed model snapshot file: ${J}`);let H=Z$($,`.qb-migrations.${G}.json`),E=String(A.state||H);if(i$(E))SH(E),A0(`-- Removed legacy migration state file: ${E}`);sZ(u$(h,v.migrationDir))}function sZ($){if(!i$($))return;let h=0,A=[];for(let G of ZU($).filter((J)=>J.endsWith(".sql"))){if(!LU($,G)){A.push(G);continue}SH(Z$($,G)),A0(`-- Removed generated migration file: ${G}`),h+=1}if(A0(`-- Cleaned up ${h} generated migration file${h===1?"":"s"} from migrations directory`),A.length>0)A0(`-- Kept ${A.length} hand-written migration${A.length===1?"":"s"}: ${A.slice(0,5).join(", ")}${A.length>5?`, +${A.length-5} more`:""}`)}async function rZ($,h){}async function MU($){if(!$)$=B1();let h=Z$($,"generated");if(i$(h))try{XU(h,{recursive:!0,force:!0}),A0("-- Cleared generated directory")}catch(A){console.error("-- Failed to clear generated directory:",A)}}async function SU($,h){let G=y$(h).createMigrationsTable();try{await $.unsafe(G).execute(),A0("-- Migrations table ready")}catch(J){throw console.error("-- Failed to create migrations table:",J),J}}async function lZ($,h){let A=y$(h);try{return(await $.unsafe(A.getExecutedMigrationsQuery()).execute()).map((J)=>J.migration)}catch(G){return console.error("-- Failed to get executed migrations:",G),[]}}async function gG($,h,A){let G=y$(A);try{A0(`-- Recording migration: ${h}`),await $.unsafe(G.recordMigrationQuery(),[h]).execute(),A0(`-- Successfully recorded migration: ${h}`)}catch(J){throw console.error(`-- Failed to record migration ${h}:`,J),J}}var YU="bun-query-builder:migrate",uZ;var bG=a(()=>{f0();U1();eh();m0();NG();$A();uZ=/\bCONCURRENTLY\b|^\s*VACUUM\b|^\s*BEGIN\s*(?:;|TRANSACTION\b)|^\s*PRAGMA\s+foreign_keys\b/im});async function oZ($,h={}){return vG($,h)}var IU=a(()=>{bG()});import{existsSync as PU,readFileSync as tZ,unlinkSync as aZ}from"fs";import{join as eZ}from"path";function $7($){let h=[],A="",G=null;for(let J=0;J<$.length;J++){let H=$[J];if(G){if(A+=H,H===G)if($[J+1]===G)A+=$[J+1],J++;else G=null;continue}if(H==="'"||H==='"'||H==="`"){G=H,A+=H;continue}if(H==="-"&&$[J+1]==="-"){let E=$.indexOf(`
|
|
351
|
-
`,J);J=E===-1?$.length:E;continue}if(H==="/"&&$[J+1]==="*"){let E=$.indexOf("*/",J+2);J=E===-1?$.length:E+1;continue}if(H===";"){if(A.trim())h.push(A.trim());A="";continue}A+=H}if(A.trim())h.push(A.trim());return h}function h7($,h=v.dialect){let A=(H)=>G0(h)?`\`${H}\``:`"${H}"`,G=[],J=[];for(let H of $7($)){let E;if(E=/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?/i.exec(H))G.push(`DROP TABLE IF EXISTS ${A(E[1])}`);else if(E=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+CONSTRAINT\s+["`']?(\w+)["`']?([\s\S]*)$/i.exec(H))if(h==="sqlite")J.push(H);else if(G0(h)&&/\bFOREIGN\s+KEY\b/i.test(E[3]??""))G.push(`ALTER TABLE ${A(E[1])} DROP FOREIGN KEY ${A(E[2])}`);else G.push(`ALTER TABLE ${A(E[1])} DROP CONSTRAINT ${A(E[2])}`);else if(E=/^ALTER\s+TABLE\s+["`']?(\w+)["`']?\s+ADD\s+(?:COLUMN\s+["`']?(\w+)["`']?|["`'](\w+)["`']|(\w+))/i.exec(H)){let Y=E[2]??E[3]??E[4];if(E[4]&&/^(?:PRIMARY|UNIQUE|INDEX|KEY|FOREIGN|CHECK|FULLTEXT|SPATIAL)$/i.test(E[4]))J.push(H);else G.push(`ALTER TABLE ${A(E[1])} DROP COLUMN ${A(Y)}`)}else if(E=/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?["`']?(\w+)["`']?(?:\s+ON\s+["`']?(\w+)["`']?)?/i.exec(H))G.push(G0(h)&&E[2]?`DROP INDEX ${A(E[1])} ON ${A(E[2])}`:`DROP INDEX IF EXISTS ${A(E[1])}`);else J.push(H)}return{down:G.reverse(),skipped:J}}async function A7($={}){let h=$.steps||1,A=$.reverseSchema!==!1;console.log("-- Rolling back migrations"),console.log(`-- Steps: ${h}`),console.log();try{let G=J0(),J=[];try{J=await G.unsafe(`
|
|
352
|
-
SELECT migration, executed_at
|
|
353
|
-
FROM migrations
|
|
354
|
-
ORDER BY executed_at DESC, migration DESC
|
|
355
|
-
`)}catch(U){console.log("-- Migrations table not found. Nothing to rollback.",U);return}if(J.length===0){console.log("-- No migrations to rollback");return}let H=J.slice(0,h);console.log(`-- Found ${J.length} executed migrations`),console.log(`-- Rolling back ${H.length} migration(s):`),console.log();for(let U of H)console.log(` - ${U.migration}`);console.log();let E=u$(void 0,v.migrationDir),Y=!1;for(let U of H)try{let z=eZ(E,U.migration);if(A&&PU(z)){let Z=tZ(z,"utf8"),{down:F,skipped:w}=h7(Z);for(let B of F)await G.unsafe(B),console.log(`-- \u21A9 ${B}`),Y=!0;if(w.length>0)console.log(`-- \u26A0\uFE0F ${w.length} statement(s) in ${U.migration} could not be auto-reversed (data/complex DDL) \u2014 reverse manually.`)}let W=`DELETE FROM migrations WHERE migration = ${r(1)}`;if(await G.unsafe(W,[U.migration]),console.log(`-- \u2713 Removed migration record: ${U.migration}`),$.deleteFiles&&PU(z))aZ(z),console.log(`-- \uD83D\uDDD1\uFE0F Deleted migration file: ${U.migration}`)}catch(z){throw console.error(`-- \u2717 Failed to rollback migration ${U.migration}:`,z),z}if(console.log(),A)console.log(Y?"-- \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(G){throw console.error("-- Rollback failed:",G),G}}var NU=a(()=>{f0();m0();$A()});import{existsSync as G7,readdirSync as J7}from"fs";async function TU(){let $=v.dialect||"postgres",h=y$($),A=u$(void 0,v.migrationDir);if(console.log("-- Migration Status"),console.log(`-- Dialect: ${$}`),console.log(`-- SQL directory: ${A}`),console.log(),!G7(A))return console.log("-- No SQL directory found. No migrations have been created yet."),[];let J=J7(A).filter((H)=>H.endsWith(".sql")).sort();if(J.length===0)return console.log("-- No migration files found"),[];try{let H=J0(),E=[];try{E=await H.unsafe(h.getExecutedMigrationsQuery())}catch(Z){console.log("-- Migrations table not found. All migrations are pending.",Z),console.log()}let Y=new Map(E.map((Z)=>[Z.migration,Z.executed_at])),U=J.map((Z)=>({file:Z,status:Y.has(Z)?"executed":"pending",executedAt:Y.get(Z)})),z=U.filter((Z)=>Z.status==="executed"),W=U.filter((Z)=>Z.status==="pending");if(console.log(`-- Total migrations: ${J.length}`),console.log(`-- Executed: ${z.length}`),console.log(`-- Pending: ${W.length}`),console.log(),z.length>0){console.log("\u2713 Executed Migrations:");for(let Z of z)console.log(` - ${Z.file} ${Z.executedAt?`(${new Date(Z.executedAt).toLocaleString()})`:""}`);console.log()}if(W.length>0){console.log("\u25CB Pending Migrations:");for(let Z of W)console.log(` - ${Z.file}`);console.log()}return U}catch(H){throw console.error("-- Failed to get migration status:",H),H}}async function H7(){return TU()}var kU=a(()=>{f0();eh();m0();$A()});import{readdirSync as E7}from"fs";import{extname as BH,join as yU}from"path";import U7 from"process";async function qU($,h={}){let A=h.dir||yU(U7.cwd(),"app/Models");try{let G=E7(A),J=G.find((W)=>{return W.replace(BH(W),"").toLowerCase()===$.toLowerCase()});if(!J){console.error(`Model "${$}" not found in ${A}`),console.log(`Available models: ${G.filter((W)=>[".ts",".js"].includes(BH(W))).map((W)=>W.replace(BH(W),"")).join(", ")}`);return}let E=await import(yU(A,J)),Y=E.default||E[Object.keys(E)[0]];if(!Y||!Y.name){console.error(`Invalid model file: ${J}`);return}let U={name:Y.name,table:Y.table||`${Y.name.toLowerCase()}s`,primaryKey:Y.primaryKey||"id",attributes:Y.attributes||{},relations:Y.relations,scopes:Y.scopes,indexes:Y.indexes,timestamps:Y.timestamps!==!1,softDeletes:Y.softDeletes===!0},z=[];if(Y.beforeCreate)z.push("beforeCreate");if(Y.afterCreate)z.push("afterCreate");if(Y.beforeUpdate)z.push("beforeUpdate");if(Y.afterUpdate)z.push("afterUpdate");if(Y.beforeDelete)z.push("beforeDelete");if(Y.afterDelete)z.push("afterDelete");if(z.length>0)U.hooks=z;if(h.json)return console.log(JSON.stringify(U,null,2)),U;console.log(`
|
|
356
|
-
\uD83D\uDCE6 Model: ${U.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: ${U.table}`),console.log(`Primary Key: ${U.primaryKey}`),console.log(`Timestamps: ${U.timestamps?"\u2713":"\u2717"}`),console.log(`Soft Deletes: ${U.softDeletes?"\u2713":"\u2717"}`),console.log(`
|
|
357
|
-
\uD83D\uDCCB Attributes (${Object.keys(U.attributes).length}):`);for(let[W,Z]of Object.entries(U.attributes)){let F=Z.type||"string",w=Z.required?"(required)":"",B=Z.unique?"(unique)":"",j=Z.default!==void 0?`= ${JSON.stringify(Z.default)}`:"";console.log(` \u2022 ${W}: ${F} ${w} ${B} ${j}`.trim())}if(U.relations&&Object.keys(U.relations).length>0){console.log(`
|
|
358
|
-
\uD83D\uDD17 Relations (${Object.keys(U.relations).length}):`);for(let[W,Z]of Object.entries(U.relations)){let F=Z.type||"unknown",w=Z.model||Z.table||"unknown";console.log(` \u2022 ${W}: ${F} \u2192 ${w}`)}}if(U.scopes&&Object.keys(U.scopes).length>0){console.log(`
|
|
359
|
-
\uD83D\uDD0D Scopes (${Object.keys(U.scopes).length}):`);for(let W of Object.keys(U.scopes))console.log(` \u2022 ${W}()`)}if(U.hooks&&U.hooks.length>0){console.log(`
|
|
360
|
-
\uD83E\uDE9D Hooks (${U.hooks.length}):`);for(let W of U.hooks)console.log(` \u2022 ${W}`)}if(U.indexes&&U.indexes.length>0){console.log(`
|
|
361
|
-
\uD83D\uDCC7 Indexes (${U.indexes.length}):`);for(let W of U.indexes){let Z=Array.isArray(W.columns)?W.columns.join(", "):W.columns,F=W.unique?"(unique)":"";console.log(` \u2022 ${W.name||"unnamed"}: [${Z}] ${F}`.trim())}}return console.log(),U}catch(G){throw console.error(`Error loading model "${$}":`,G.message),G}}var xU=()=>{};async function Y7(){let h=await J0().ping();return console.log(h?"OK":"NOT READY"),h}var fU=a(()=>{m0()});import{readdirSync as z7,readFileSync as gU,statSync as W7}from"fs";import{extname as vU,join as Z7}from"path";async function bU($,h={}){let A=[];try{let G=W7($),J=[];if(G.isDirectory())J=z7($).filter((U)=>vU(U)===".sql").map((U)=>Z7($,U));else if(G.isFile()&&vU($)===".sql")J=[$];else return console.error("Path must be a .sql file or directory containing .sql files"),A;if(J.length===0)return console.log("No .sql files found"),A;if(h.verbose)console.log(`Analyzing ${J.length} SQL file(s)...
|
|
362
|
-
`);for(let Y of J)try{let U=gU(Y,"utf8").trim();if(!U){if(h.verbose)console.log(`\u2298 ${Y}: empty file`);continue}if(h.verbose)console.log(`\uD83D\uDCC4 ${Y}`),console.log(` Query: ${U.substring(0,60)}${U.length>60?"...":""}`);let z=await $0`EXPLAIN ${$0.unsafe(U)}`;if(A.push({file:Y,query:U,plan:Array.isArray(z)?z:[z]}),h.verbose&&!h.json){if(console.log(" Plan:"),Array.isArray(z))for(let W of z)if(typeof W==="string")console.log(` ${W}`);else if(W["QUERY PLAN"])console.log(` ${W["QUERY PLAN"]}`);else if(W.plan)console.log(` ${JSON.stringify(W.plan)}`);else console.log(` ${JSON.stringify(W)}`);console.log()}}catch(U){if(A.push({file:Y,query:gU(Y,"utf8").trim(),plan:[],error:U.message}),h.verbose)console.log(` \u2717 Error: ${U.message}
|
|
363
|
-
`)}let H=A.filter((Y)=>!Y.error).length,E=A.filter((Y)=>Y.error).length;if(h.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: ${H} successful, ${E} failed`);if(h.json)console.log(JSON.stringify(A,null,2));return A}catch(G){throw console.error("Error explaining queries:",G.message),G}}var cU=a(()=>{U1()});import{writeFileSync as X7}from"fs";import{join as j7}from"path";import L7 from"process";async function mU($={}){let h=$.dir||j7(L7.cwd(),"app/Models"),A=$.format||"mermaid";try{let G=await C$({modelsDir:h});if(!G||Object.keys(G).length===0)return console.error("No models found"),"";let J="";if(A==="mermaid")J=F7(G);else if(A==="dot")J=R7(G);else return console.error(`Unsupported format: ${A}`),"";if($.output)X7($.output,J,"utf8"),console.log(`\u2713 Diagram written to: ${$.output}`);else console.log(J);return J}catch(G){throw console.error("Error generating diagram:",G.message),G}}function F7($){let h=["erDiagram"];for(let[A,G]of Object.entries($)){let J=G.table||`${A.toLowerCase()}s`,H=G.attributes||{};h.push(` ${J} {`);for(let[E,Y]of Object.entries(H)){let U=Y.type||"string",z=G.primaryKey===E?"PK":"",W=Y.unique?"UK":"",Z=[z,W].filter(Boolean).join(","),F=Z?` "${Z}"`:"";h.push(` ${U} ${E}${F}`)}h.push(" }")}for(let[A,G]of Object.entries($)){let J=G.table||`${A.toLowerCase()}s`,H=G.relations||{};for(let[E,Y]of Object.entries(H)){let{type:U,model:z}=Y,W=$[z]?.table||`${z?.toLowerCase()}s`||"unknown",Z="";if(U==="hasOne")Z="||--||";else if(U==="hasMany")Z="||--o{";else if(U==="belongsTo")Z="}o--||";else if(U==="belongsToMany"||U==="manyToMany")Z="}o--o{";else Z="||--||";h.push(` ${J} ${Z} ${W} : "${E}"`)}}return h.join(`
|
|
364
|
-
`)}function R7($){let h=["digraph schema {"," rankdir=LR;"," node [shape=record];",""];for(let[A,G]of Object.entries($)){let J=G.table||`${A.toLowerCase()}s`,H=G.attributes||{},E=[];for(let[U,z]of Object.entries(H)){let W=z.type||"string",Z=G.primaryKey===U?" (PK)":"",F=z.unique?" (UK)":"";E.push(`${U}: ${W}${Z}${F}`)}let Y=`${E.join("\\l")}\\l`;h.push(` ${J} [label="{${J}|${Y}}"];`)}h.push("");for(let[A,G]of Object.entries($)){let J=G.table||`${A.toLowerCase()}s`,H=G.relations||{};for(let[E,Y]of Object.entries(H)){let{type:U,model:z}=Y,W=$[z]?.table||`${z?.toLowerCase()}s`||"unknown",Z="";if(U==="hasOne")Z="arrowhead=none, arrowtail=normal";else if(U==="hasMany")Z="arrowhead=crow, arrowtail=none";else if(U==="belongsTo")Z="arrowhead=normal, arrowtail=none";else if(U==="belongsToMany"||U==="manyToMany")Z="arrowhead=crow, arrowtail=crow";h.push(` ${J} -> ${W} [label="${E}", ${Z}];`)}}return h.push("}"),h.join(`
|
|
365
|
-
`)}var dU=a(()=>{m0()});import{existsSync as mG,mkdirSync as w7,readdirSync as _7,writeFileSync as O7}from"fs";import{dirname as pU,join as W1}from"path";import GA from"process";function dG($){let h=$;while(h!==pU(h)){if(mG(W1(h,"package.json")))return h;h=pU(h)}return GA.cwd()}async function nU($){if(!mG($))return console.log(`-- Seeders directory not found: ${$}`),[];let A=_7($).sort((J,H)=>J.localeCompare(H)).filter((J)=>(J.endsWith(".ts")||J.endsWith(".js"))&&J!=="index.ts"&&J!=="index.js"),G=[];for(let J of A){let H=W1($,J);try{let E=await import(H),Y=E.default||E[Object.keys(E)[0]];if(Y&&typeof Y==="function"){let U=new Y;if(U&&typeof U.run==="function")G.push({name:J.replace(/\.(ts|js)$/,""),className:String(Y.name||""),instance:U})}}catch(E){console.error(`-- Failed to load seeder ${J}:`,E)}}return G.sort((J,H)=>J.instance.order-H.instance.order),G}async function uU($={}){let h=dG(GA.cwd()),A=$.seedersDir||W1(h,"database/seeders"),G=$.verbose??!0;if(G)console.log("-- Running seeders..."),console.log(`-- Seeders directory: ${A}`);let J=await nU(A);if(J.length===0){console.log("-- No seeders found");return}if(G)console.log(`-- Found ${J.length} seeder(s)`);let H=J0();for(let{name:E,instance:Y}of J)try{if(G)console.log(`-- Seeding: ${E}`);if(await Y.run(H),G)console.log(`-- \u2713 Seeded: ${E}`)}catch(U){throw console.error(`-- \u2717 Failed to seed ${E}:`,U),U}if(G)console.log("-- All seeders completed successfully")}async function D7($,h={}){let A=dG(GA.cwd()),G=W1(A,"database/seeders"),J=h.verbose??!0;if(J)console.log(`-- Running seeder: ${$}`);let H=await nU(G),E=H.find((U)=>U.className===$)??H.find((U)=>U.name===$);if(!E){let U=H.map((z)=>z.className||z.name).join(", ")||"none";throw console.error(`-- Seeder not found: ${$}. Available: ${U}`),Error(`Seeder not found: ${$}. Available: ${U}`)}let Y=J0();try{if(await E.instance.run(Y),J)console.log(`-- \u2713 Seeder completed: ${$}`)}catch(U){throw console.error(`-- \u2717 Seeder failed: ${$}`,U),U}}async function V7($){let h=dG(GA.cwd()),A=W1(h,"database/seeders");if(!mG(A))w7(A,{recursive:!0}),console.log(`-- Created seeders directory: ${A}`);let J=`${$.replace(/Seeder$/i,"")}Seeder`,H=`${J}.ts`,E=W1(A,H);if(mG(E))throw console.error(`-- Seeder already exists: ${E}`),Error(`Seeder already exists: ${E}`);let Y=`import type { QueryBuilder } from 'bun-query-builder'
|
|
366
|
-
import { Seeder } from 'bun-query-builder'
|
|
367
|
-
import { faker } from '@stacksjs/ts-faker'
|
|
368
|
-
|
|
369
|
-
export default class ${J} extends Seeder {
|
|
370
|
-
/**
|
|
371
|
-
* Run the database seeds.
|
|
372
|
-
*/
|
|
373
|
-
async run(qb: QueryBuilder): Promise<void> {
|
|
374
|
-
console.log('Seeding: ${J}')
|
|
375
|
-
|
|
376
|
-
// Example: Create 10 records with faker
|
|
377
|
-
const records = Array.from({ length: 10 }, () => ({
|
|
378
|
-
name: faker.person.fullName(),
|
|
379
|
-
email: faker.internet.email().toLowerCase(),
|
|
380
|
-
age: faker.number.int({ min: 18, max: 80 }),
|
|
381
|
-
created_at: faker.date.past(),
|
|
382
|
-
updated_at: new Date(),
|
|
383
|
-
}))
|
|
384
|
-
|
|
385
|
-
// Option 1: Kysely-style API
|
|
386
|
-
await qb.insertInto('table_name').values(records).execute()
|
|
387
|
-
|
|
388
|
-
// Option 2: Laravel-style API (equivalent)
|
|
389
|
-
// await qb.table('table_name').insert(records).execute()
|
|
390
|
-
|
|
391
|
-
console.log(\`\u2713 Seeded \${records.length} records\`)
|
|
392
|
-
|
|
393
|
-
// For large datasets, use batch inserts:
|
|
394
|
-
// const batchSize = 100
|
|
395
|
-
// for (let i = 0; i < records.length; i += batchSize) {
|
|
396
|
-
// const batch = records.slice(i, i + batchSize)
|
|
397
|
-
// await qb.insertInto('table_name').values(batch).execute()
|
|
398
|
-
// // Or: await qb.table('table_name').insert(batch).execute()
|
|
399
|
-
// }
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Specify the order in which this seeder should run.
|
|
404
|
-
* Lower numbers run first. Default is 100.
|
|
405
|
-
*/
|
|
406
|
-
get order(): number {
|
|
407
|
-
return 100
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
`;O7(E,Y),console.log(`-- \u2713 Created seeder: ${E}`)}async function M7($={}){let h=dG(GA.cwd()),A=$.modelsDir||W1(h,"app/Models"),G=$.seedersDir||W1(h,"database/seeders"),J=$.verbose??!0;try{let{resetDatabase:H,generateMigration:E,executeMigration:Y}=await Promise.resolve().then(() => (bG(),QU));if(J)console.log("-- Refreshing database...");if(await H(A),J)console.log("-- Running migrations...");if(await E(A,{full:!0}),await Y(),J)console.log("-- Running seeders...");if(await uU({seedersDir:G,verbose:J}),J)console.log("-- \u2713 Database refreshed successfully")}catch(H){throw console.error("-- \u2717 Database refresh failed:",H),H}}var iU=a(()=>{m0()});function S7($,h,A={}){let G=C$({modelsDir:$}),J=PG(G);if(v.debug)v.debug.captureText=!0;let H=J0({schema:J}),E=H.selectFrom(h).limit(Number(A.limit||10)).toText?.()??"";return console.log(E||"[query]"),{sql:E,qb:H,schema:J}}var sU=a(()=>{f0();m0()});async function Q7($,h={}){let A=J0(),G=h.params?JSON.parse(h.params):void 0,J=await A.unsafe($,G);return console.log(JSON.stringify(J)),J}var rU=a(()=>{m0()});import{existsSync as C7}from"fs";import{dirname as lU,join as oU}from"path";import tU from"process";function K7($){let h=$;while(h!==lU(h)){if(C7(oU(h,"package.json")))return h;h=lU(h)}return tU.cwd()}async function aU($){if(!$)$=oU(K7(tU.cwd()),"app/Models");let h=v.dialect||"postgres";console.log("-- Validating Schema"),console.log(`-- Models directory: ${$}`),console.log(`-- Dialect: ${h}`),console.log();let A=[];try{let G=await C$({modelsDir:$}),J=AA(G,{dialect:h}),H=J0(),E=[];if(h==="sqlite")E=(await H.unsafe(`
|
|
411
|
-
SELECT name FROM sqlite_master
|
|
412
|
-
WHERE type = 'table'
|
|
413
|
-
AND name NOT LIKE 'sqlite_%'
|
|
414
|
-
AND name != 'migrations'
|
|
415
|
-
`)).map((W)=>W.name);else if(h==="postgres")E=(await H.unsafe(`
|
|
416
|
-
SELECT table_name
|
|
417
|
-
FROM information_schema.tables
|
|
418
|
-
WHERE table_schema = 'public'
|
|
419
|
-
AND table_type = 'BASE TABLE'
|
|
420
|
-
AND table_name != 'migrations'
|
|
421
|
-
`)).map((W)=>W.table_name);else if(G0(h))E=(await H.unsafe(`
|
|
422
|
-
SELECT table_name
|
|
423
|
-
FROM information_schema.tables
|
|
424
|
-
WHERE table_schema = DATABASE()
|
|
425
|
-
AND table_type = 'BASE TABLE'
|
|
426
|
-
AND table_name != 'migrations'
|
|
427
|
-
`)).map((W)=>W.table_name);let Y=J.tables.map((z)=>z.table);for(let z of Y)if(!E.includes(z))A.push({type:"missing_table",severity:"error",table:z,message:`Table '${z}' defined in models but not found in database`});for(let z of E)if(!Y.includes(z))A.push({type:"extra_table",severity:"warning",table:z,message:`Table '${z}' exists in database but not defined in models`});for(let z of J.tables){if(!E.includes(z.table))continue;let W=[];if(h==="sqlite")W=(await H.unsafe(`PRAGMA table_info(${z.table})`)).map((B)=>({name:B.name,type:B.type.toLowerCase()}));else if(h==="postgres")W=(await H.unsafe(`
|
|
428
|
-
SELECT column_name, data_type
|
|
429
|
-
FROM information_schema.columns
|
|
430
|
-
WHERE table_name = $1
|
|
431
|
-
`,[z.table])).map((B)=>({name:B.column_name,type:B.data_type.toLowerCase()}));else if(G0(h))W=(await H.unsafe(`
|
|
432
|
-
SELECT column_name, data_type
|
|
433
|
-
FROM information_schema.columns
|
|
434
|
-
WHERE table_name = ?
|
|
435
|
-
AND table_schema = DATABASE()
|
|
436
|
-
`,[z.table])).map((B)=>({name:B.column_name,type:B.data_type.toLowerCase()}));let Z=W.map((w)=>w.name),F=z.columns.map((w)=>w.name);for(let w of z.columns)if(!Z.includes(w.name))A.push({type:"missing_column",severity:"error",table:z.table,column:w.name,expected:w.type,message:`Column '${z.table}.${w.name}' defined in model but not found in database`});for(let w of W)if(!F.includes(w.name))A.push({type:"extra_column",severity:"warning",table:z.table,column:w.name,actual:w.type,message:`Column '${z.table}.${w.name}' exists in database but not defined in model`});for(let w of z.columns){let B=W.find((j)=>j.name===w.name);if(B){let j=(R)=>{return R.toLowerCase().replace(/\(.*\)/,"").replace("integer","int").replace("varchar","text").replace("character varying","text").trim()},O=j(w.type),_=j(B.type);if(O!==_)A.push({type:"type_mismatch",severity:"warning",table:z.table,column:w.name,expected:w.type,actual:B.type,message:`Column '${z.table}.${w.name}' type mismatch: expected '${w.type}', found '${B.type}'`})}}}let U=A.filter((z)=>z.severity==="error").length===0;if(U&&A.length===0)console.log("\u2713 Schema is valid - no issues found"),console.log();else{console.log(`-- Found ${A.length} issue(s)`),console.log();let z=A.filter((Z)=>Z.severity==="error"),W=A.filter((Z)=>Z.severity==="warning");if(z.length>0){console.log(`\u2717 Errors (${z.length}):`);for(let Z of z)console.log(` - ${Z.message}`);console.log()}if(W.length>0){console.log(`\u26A0 Warnings (${W.length}):`);for(let Z of W)console.log(` - ${Z.message}`);console.log()}if(!U)console.log("-- Recommendation: Run migrations to sync the database schema"),console.log("-- qb migrate ./app/Models --apply")}return{valid:U,issues:A}}catch(G){throw console.error("-- Schema validation failed:",G),G}}async function B7($){return aU($)}var eU=a(()=>{f0();oh();m0()});async function I7($={}){let h=Number($.attempts||10),A=Number($.delay||100),G=J0();try{return await G.waitForReady({attempts:h,delayMs:A}),console.log("READY"),!0}catch{throw console.error("NOT READY"),Error("Database not ready")}}var $Y=a(()=>{m0()});var hY=a(()=>{C9();q9();f9();g9();b9();m9();p9();n9();u9();s9();r9();NG();GU();bG();IU();NU();kU();xU();fU();cU();dU();iU();sU();rU();eU();$Y()});function a1($){if(typeof $==="number")return{length:$};return $}function IH($){if(typeof $==="number")return{max:$};return $}function P7($){return typeof $==="function"}function N7($){return $.replace(/[A-Z]/g,(h)=>h.toLowerCase())}function AY($,h){if(!h||typeof h.fractionDigits!=="number")return $;return Number($.toFixed(h.fractionDigits))}function Z1($,h={}){if(!$)return h;return new Proxy($,{get(A,G){if(G in h)return h[G];let J=A[G];if(J!==void 0)return J;let H=A[N7(G)];if(P7(H))return H.bind(A);return}})}function GY($){let h=(W)=>{let Z=Array.isArray(W)?W:[],F=Math.floor(Math.random()*Z.length);return Z[F]},A=()=>$.string,G=()=>$.number,J=()=>$.random,H=Z1($.string,{alpha:(W)=>A()?.alpha?.(a1(W)),alphanumeric:(W)=>A()?.alphanumeric?.(a1(W)),numeric:(W)=>A()?.numeric?.(a1(W)),sample:(W)=>A()?.sample?.(a1(W)),hexadecimal:(W)=>A()?.hexadecimal?.(a1(W))}),E=Z1($.number,{int:(W)=>G()?.int?.(IH(W)),float:(W)=>{let Z=IH(W);return AY(Number(G()?.float?.(Z)??0),Z)}}),Y=Z1($.helpers,{arrayElement:h,arrayElements:(W,Z)=>{let F=[...Array.isArray(W)?W:[]],w=typeof Z==="number"?Z:Math.max(1,Math.floor(Math.random()*F.length));for(let B=F.length-1;B>0;B-=1){let j=Math.floor(Math.random()*(B+1));[F[B],F[j]]=[F[j],F[B]]}return F.slice(0,Math.min(w,F.length))},shuffle:(W)=>{let Z=[...Array.isArray(W)?W:[]];for(let F=Z.length-1;F>0;F-=1){let w=Math.floor(Math.random()*(F+1));[Z[F],Z[w]]=[Z[w],Z[F]]}return Z},maybe:(W,Z)=>{let F=typeof Z?.probability==="number"?Z.probability:0.5;return Math.random()<F?W():void 0},slugify:(W)=>String(W??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),z={string:H,number:E,helpers:Y,datatype:{boolean:(W)=>{let Z=typeof W==="number"?W:W?.probability;if(typeof Z==="number")return Math.random()<Z;return Boolean(J()?.boolean?.())},number:(W)=>Number(G()?.int?.(IH(W))??0),float:(W)=>AY(Number(G()?.float?.(W)??0),W),uuid:()=>crypto.randomUUID(),string:(W)=>String(A()?.alphanumeric?.({length:W??10})??""),hexadecimal:(W)=>String(A()?.hexadecimal?.(a1(W))??""),array:(W)=>Array.from({length:W??3},()=>A()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:A()?.alphanumeric?.({length:8})})},location:Z1($.address),address:Z1($.address),vehicle:Z1($.vehicle,{vrm:()=>$.vehicle?.registration?.()}),company:Z1($.company,{catchPhrase:()=>$.company?.catchphrase?.(),buzzPhrase:()=>$.company?.bs?.()??$.company?.buzzword?.()})};return new Proxy($,{get(W,Z){if(Z in z)return z[Z];let F=W[Z];if(F&&typeof F==="object")return Z1(F);return F}})}function pG($){if(typeof $==="string")return{model:$};if($&&typeof $==="object"&&typeof $.model==="string"){let h=$;return{model:h.model,foreignKey:h.foreignKey,onDelete:h.onDelete}}return null}function e1($){if(!$)return[];return(Array.isArray($)?$:typeof $==="object"?Object.values($):[]).map(pG).filter((A)=>A!==null)}import{existsSync as T7}from"fs";import{join as k7}from"path";import y7 from"process";import{existsSync as JY,statSync as HY}from"fs";import{join as q7,relative as x7,resolve as EY}from"path";import tG from"process";import{Buffer as s$}from"buffer";import{createCipheriv as f7,createDecipheriv as g7,randomBytes as PH}from"crypto";import{closeSync as NH,createReadStream as UY,createWriteStream as v7,existsSync as nG,fsyncSync as YY,openSync as zY,writeFileSync as b7}from"fs";import{access as c7,constants as WY,mkdir as m7,readdir as uG,rename as ZY,stat as $h,unlink as iG,writeFile as TH}from"fs/promises";import{isAbsolute as d7,join as hh,resolve as p7}from"path";import D0 from"process";import{pipeline as n7}from"stream/promises";import{createGzip as XY}from"zlib";import Ah from"process";import r$ from"process";import sG from"process";import{existsSync as rG}from"fs";import{resolve as kH}from"path";import{existsSync as u7}from"fs";import{existsSync as vH,mkdirSync as i7,readdirSync as s7,readFileSync as r7,writeFileSync as l7}from"fs";import{homedir as Gh}from"os";import{dirname as jY,resolve as G$}from"path";import P1 from"process";import{existsSync as o7,readdirSync as t7}from"fs";import{extname as yH,resolve as LY}from"path";import a7 from"process";import{spawnSync as p6}from"child_process";import{existsSync as Jh,readFileSync as n6}from"fs";import{join as Hh}from"path";import mY from"process";function h6($,h){this[$]=$6.bind(null,h)}class iH{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,h){let A=h?`:${h}`:"";return`${this.options.keyPrefix}${$}${A}`}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(([,A],[,G])=>A.timestamp.getTime()-G.timestamp.getTime()),h=$.length-this.options.maxSize+1;for(let A=0;A<h;A++)this.cache.delete($[A][0])}set($,h,A,G){if(!this.options.enabled)return;let J=this.generateKey($,A),H=G??this.options.ttl,E=this.estimateSize(h);this.cache.set(J,{value:h,timestamp:new Date,ttl:H,hits:0,size:E}),this.evictIfNeeded()}get($,h){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,h),G=this.cache.get(A);if(!G){this.totalMisses++;return}if(this.isExpired(G)){this.cache.delete(A),this.totalMisses++;return}return G.hits++,this.totalHits++,G.value}isFileModified($,h){try{if(!JY($))return!0;return HY($).mtime>h}catch{return!0}}getWithFileCheck($,h){let A=this.get($,h);if(!A)return;if(this.isFileModified(h,A.fileTimestamp)){this.delete($,h);return}return A.value}setWithFileCheck($,h,A,G){try{let J=JY(A)?HY(A):null,H=J?J.mtime:new Date;this.set($,{value:h,fileTimestamp:H},A,G)}catch{this.set($,h,A,G)}}delete($,h){let A=this.generateKey($,h);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[h,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(h),$++;return $}getStats(){let $=Array.from(this.cache.values()),h=$.reduce((G,J)=>G+J.size,0),A=$.map((G)=>G.timestamp).sort();return{size:h,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[h,A]of this.cache.entries())$[h]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[h,A]of Object.entries($))if(typeof A==="object"&&A!==null){let G=A;this.cache.set(h,{value:G.value,timestamp:new Date(G.timestamp),ttl:G.ttl,hits:G.hits,size:G.size})}}}class sH{metrics=[];maxMetrics=1000;async track($,h,A={}){let G=performance.now(),J=new Date;try{let H=await h(),E=performance.now()-G;return this.recordMetric({operation:$,duration:E,timestamp:J,...A}),H}catch(H){let E=performance.now()-G;throw this.recordMetric({operation:`${$}:error`,duration:E,timestamp:J,...A}),H}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let h=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(h.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=h.map((J)=>J.duration),G=A.reduce((J,H)=>J+H,0);return{count:h.length,averageDuration:G/h.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:G,recentMetrics:h.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((h)=>h.duration>$)}}function J6($,h={}){let A=Object.keys(h).sort().map((G)=>`${G}:${h[G]}`).join("|");return A?`${$}:${A}`:$}function H6($,h){try{return JSON.stringify($)===JSON.stringify(h)}catch{return $===h}}function E6($){return $.getStats().size*2}function U6($,h={}){let A=tG.cwd();while(A.includes("storage"))A=EY(A,"..");let G=EY(A,$||"");if(h?.relative)return x7(tG.cwd(),G);return G}function p0(){if(r$.env.NODE_ENV==="test"||r$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Y6(){if(r$.env.NODE_ENV==="test"||r$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof r$<"u"){let $=r$.type;if($==="renderer"||$==="worker")return!1;return!!(r$.versions&&(r$.versions.node||r$.versions.bun))}return!1}class SY{async format($){let h=await Y6(),A=await this.getMetadata(h);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:h}=await import("os");return{pid:Ah.pid,hostname:h(),environment:Ah.env.NODE_ENV||"development",platform:Ah.platform,version:Ah.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ah.env.NODE_ENV||Ah.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $J{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($,h={}){this.name=$,this.config={...EA},this.options=this.normalizeOptions(h),this.formatter=this.options.formatter||new SY,this.enabled=h.enabled??!0,this.fancy=h.fancy??!0,this.tagFormat=h.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=h.timestampPosition??"right",this.environment=h.environment??D0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(h);let A={...h},G=h.timestamp!==void 0;if(G)delete A.timestamp;if(this.config={...this.config,...A,timestamp:G||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),H=this.generateKey();this.currentKeyId=J,this.keys.set(J,H),this.encryptionKeys.set(J,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let h={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return h[$]>=h[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...oG,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...oG};return{...oG,...$.fingersCrossed}}normalizeOptions($){let h={format:"json",level:"info",logDirectory:EA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...h,...Object.fromEntries(Object.entries($).filter(([,G])=>G!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=h.level;return A}shouldWriteToFile(){return!p0()&&this.config.writeToFile===!0}async writeToFile($){let h=(async()=>{let G,J=0,H=3,E=1000;while(J<H)try{try{try{await c7(this.config.logDirectory,WY.F_OK|WY.W_OK)}catch(U){if(U instanceof Error&&"code"in U)if(U.code==="ENOENT")await m7(this.config.logDirectory,{recursive:!0,mode:493});else if(U.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw U;else throw U}}catch(U){throw console.error("Debug: [writeToFile] Failed to create log directory:",U),U}let Y=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:s$.from($);try{if(!nG(this.currentLogFile))await TH(this.currentLogFile,"",{mode:420});if(G=zY(this.currentLogFile,"a",420),b7(G,Y,{flag:"a"}),YY(G),G!==void 0)NH(G),G=void 0;if((await $h(this.currentLogFile)).size===0){if(await TH(this.currentLogFile,Y,{flag:"w",mode:420}),(await $h(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(U){let z=U;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<H-1){let W=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${H}:`,W);let Z=E*2**J;await new Promise((F)=>setTimeout(F,Z)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(G!==void 0)try{NH(G)}catch(U){console.error("Debug: [writeToFile] Error closing file descriptor:",U)}}}catch(Y){if(J===H-1){let z=Y,W=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Y}J++;let U=E*2**(J-1);await new Promise((z)=>setTimeout(z,U))}})();this.pendingOperations.push(h);let A=this.pendingOperations.length-1;try{await h}catch(G){throw console.error("Debug: [writeToFile] Error in operation:",G),G}finally{this.pendingOperations.splice(A,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 hh(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 hh(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return hh(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(p0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,h;switch($.frequency){case"daily":h=86400000;break;case"weekly":h=604800000;break;case"monthly":h=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},h)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let h=typeof $.interval==="number"?$.interval:60,A=Math.max(h,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((G)=>{console.error("Error rotating keys:",G)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,h=this.generateKeyId(),A=this.generateKey();this.currentKeyId=h,this.keys.set(h,A),this.encryptionKeys.set(h,{key:A,createdAt:new Date});let G=Array.from(this.encryptionKeys.entries()).sort(([,E],[,Y])=>Y.createdAt.getTime()-E.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,H=Math.max(1,J);if(G.length>H)for(let[E]of G.slice(H))this.encryptionKeys.delete(E),this.keys.delete(E)}generateKeyId(){return PH(16).toString("hex")}generateKey(){return PH(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:h}=this.getCurrentKey(),A=PH(16),G=f7("aes-256-gcm",h,A),J=s$.isBuffer($)?$:s$.from($,"utf8"),H=G.update(J),E=G.final(),Y=H.length+E.length,U=G.getAuthTag(),z=s$.allocUnsafe(16+Y+16);return A.copy(z,0),H.copy(z,16),E.copy(z,16+H.length),U.copy(z,16+Y),{encrypted:z,iv:A}}async compressData($){return new Promise((h,A)=>{let G=XY(),J=[];G.on("data",(H)=>J.push(H)),G.on("end",()=>h(s$.from(s$.concat(J)))),G.on("error",A),G.write($),G.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 h=this.config.rotation.encrypt;return{...$,...h}}return $}async rotateLog(){if(p0())return;if(!this.shouldWriteToFile())return;let $=await $h(this.currentLogFile).catch(()=>null);if(!$)return;let h=this.config.rotation;if(typeof h==="boolean")return;if(h.maxSize&&$.size>=h.maxSize){let A=this.currentLogFile,G=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await uG(this.config.logDirectory),H=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let W=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),E=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Y=`${A}.${E}`;if(await $h(A).catch(()=>null))try{if(await ZY(A,Y),h.compress)try{let U=`${Y}.gz`;await this.compressLogFile(Y,U),await iG(Y)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${A}.1`;await TH(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),H=A.replace(/\.log$/,`-${J}.log`);if(await $h(A).catch(()=>null))await ZY(A,H)}if(this.currentLogFile=G,h.maxFiles){let J=(await uG(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,E)=>E.localeCompare(H));for(let H of J.slice(h.maxFiles))await iG(hh(this.config.logDirectory,H))}}}async compressLogFile($,h){let A=UY($),G=v7(h),J=XY();await n7(A,J,G)}async handleFingersCrossedBuffer($,h){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let G=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(G);console.log(G)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(h);console.log(h)}}shouldLog($){if(!this.enabled)return!1;let h={debug:0,info:1,success:2,warning:3,error:4};return h[$]>=h[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((h)=>{console.error("Error in pending write operation:",h)});return Promise.resolve()})),nG(this.currentLogFile))try{let $=zY(this.currentLogFile,"r+");YY($),NH($)}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(!p0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await uG(this.config.logDirectory)).filter((h)=>(h.includes("temp")||h.includes(".tmp"))&&h.includes(this.name));for(let h of $)try{await iG(hh(this.config.logDirectory,h))}catch(A){console.error(`Failed to delete temp file ${h}:`,A)}}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()?w0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p0())return!1;let $=typeof D0.env.NO_COLOR<"u",h=D0.env.FORCE_COLOR==="0";if($||h)return!1;return!!(typeof D0.stderr<"u"&&D0.stderr.isTTY||typeof D0.stdout<"u"&&D0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:h,icon:A="",tag:G="",message:J,level:H,showTimestamp:E=!0}=$,Y=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(E)w.push(h);if(H==="warning")w.push("WARN");else if(H==="error")w.push("ERROR");else if(A)w.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(G)w.push(G.replace(/[[\]]/g,""));return w.push(J),w.join(" ")}let U=D0.stdout.columns||120,z="";if(H==="warning"||H==="error")z=`${A} ${J}`;else if(H==="info"||H==="success")z=`${A} ${G} ${J}`;else z=`${A} ${G} ${w0.cyan(J)}`;if(!E)return z.trim();let W=Y(z).trim().length,Z=Y(h).length,F=Math.max(1,U-2-W-Z);return`${z.trim()}${" ".repeat(F)}${h}`}formatMessage($,h){if(h.length===1&&Array.isArray(h[0]))return $.replace(/\{(\d+)\}/g,(H,E)=>{let Y=Number.parseInt(E,10);return Y<h[0].length?String(h[0][Y]):H});let A=/%([sdijfo%])/g,G=0,J=$.replace(A,(H,E)=>{if(E==="%")return"%";if(G>=h.length)return H;let Y=h[G++];switch(E){case"s":return String(Y);case"d":case"i":return Number(Y).toString();case"j":case"o":return JSON.stringify(Y,null,2);default:return H}});if(G<h.length)J+=` ${h.slice(G).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let h=$;return h=h.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,G,J)=>{let H=w0.underline(w0.blue(G)),E=this.toAbsoluteFilePath(J);if(E&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Y=`file://${encodeURI(E)}`,U="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${Y}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),h=h.replace(/`([^`]+)`/g,(A,G)=>w0.bgGray(G)),h=h.replace(/\*\*([^*]+)\*\*/g,(A,G)=>w0.bold(G)),h=h.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,G)=>w0.italic(G)),h=h.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,G)=>w0.italic(G)),h=h.replace(/~([^~]+)~/g,(A,G)=>w0.strikethrough(G)),h}supportsHyperlinks(){if(p0())return!1;let $=D0.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 h=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(h)&&h>=5000)return!0;return!1}toAbsoluteFilePath($){try{let h=$;if(h.startsWith("file://"))h=h.replace(/^file:\/\//,"");if(h.startsWith("~")){let A=D0.env.HOME||"";if(A)h=h.replace(/^~(?=$|\/)/,A)}if(d7(h)||h.startsWith("./")||h.startsWith("../"))h=p7(h);else return null;return nG(h)?h:null}catch{return null}}buildOutputTexts($){let h=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:h,fileText:A}}async log($,h,...A){if(!this.shouldLog($))return;let G=new Date,J=this.formatConsoleTimestamp(G),H=this.formatFileTimestamp(G),E,Y;if(h instanceof Error)E=h.message,Y=h.stack;else E=this.formatMessage(h,A);let{consoleText:U,fileText:z}=this.buildOutputTexts(E);if(this.shouldStyleConsole()){let Z=this.options.showIcons===!1?"":QY[$],F=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",w;switch($){case"debug":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:w0.gray(U),level:$}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:w0.green(U),level:$}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:J,icon:Z,tag:F,message:U,level:$}),console.error(w),Y){let B=Y.split(`
|
|
437
|
-
`);for(let j of B)if(j.trim()&&!j.includes(E))console.error(this.formatConsoleMessage({timestamp:J,message:w0.gray(` ${j}`),level:$,showTimestamp:!1}))}break}}else if(!p0()){if(console.error(`${H} ${this.environment}.${$.toUpperCase()}: ${E}`),Y)console.error(Y)}let W=`${H} ${this.environment}.${$.toUpperCase()}: ${z}
|
|
438
|
-
`;if(Y)W+=`${Y}
|
|
439
|
-
`;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,h=""){let A={update:(J,H)=>{},finish:(J)=>{},interrupt:(J,H)=>{}};if(!this.enabled)return A;let G=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:h||"",barLength:G,lastRenderedLine:""},this.shouldStyleConsole()&&!p0()&&D0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(J,H)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,J),this.activeProgressBar.total),H!==void 0)this.activeProgressBar.message=H;if(this.shouldStyleConsole()&&!p0()&&D0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(J)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,J)},interrupt:(J,H="info")=>{if(!p0()&&D0.stdout.isTTY)D0.stdout.write(`
|
|
440
|
-
`);if(this[H==="warning"?"warn":H](J),this.activeProgressBar&&this.shouldStyleConsole()&&!p0()&&D0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let h=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",G=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":w0.blue("\u25D0"),tag:A,message:`${w0.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let G=performance.now(),J=Math.round(G-h),H=`${$} completed in ${J}ms`,E=new Date,Y=this.formatConsoleTimestamp(E),U=`${this.formatFileTimestamp(E)} ${this.environment}.INFO: ${H}`;if(A)U+=` ${JSON.stringify(A)}`;if(U+=`
|
|
441
|
-
`,U=U.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":w0.green("\u2713"),tag:z,message:`${H}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!p0())console.error(U.trim());if(this.shouldWriteToFile())await this.writeToFile(U)}}async debug($,...h){await this.log("debug",$,...h)}async info($,...h){await this.log("info",$,...h)}async success($,...h){await this.log("success",$,...h)}async warn($,...h){await this.log("warning",$,...h)}async error($,...h){await this.log("error",$,...h)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:h}=$;return!!h}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let h=`${this.name}:${$}`,A=new $J(h,{...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(A),A}createReadStream(){if(p0())throw Error("createReadStream is not supported in browser environments");if(!nG(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return UY(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let h=this.config.rotation;if(!h.encrypt||typeof h.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let G=s$.isBuffer($)?$:s$.from($,"base64"),J=G.subarray(0,16),H=G.subarray(G.length-16),E=G.subarray(16,G.length-16),Y=g7("aes-256-gcm",A,J);Y.setAuthTag(H);let U=Y.update(E),z=Y.final(),W=U.length+z.length,Z=s$.allocUnsafe(W);return U.copy(Z,0),z.copy(Z,U.length),Z.toString("utf8")}catch(G){throw Error(`Decryption failed: ${G instanceof Error?G.message:String(G)}`)}}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($,h){this.currentKeyId=$,this.keys.set($,h)}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 h=new Date,A=this.formatConsoleTimestamp(h),G=this.formatFileTimestamp(h),{consoleText:J,fileText:H}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Y=J.split(`
|
|
442
|
-
`),U=Math.max(...Y.map((F)=>F.length))+2,z=`\u250C${"\u2500".repeat(U)}\u2510`,W=`\u2514${"\u2500".repeat(U)}\u2518`,Z=Y.map((F)=>{return this.formatConsoleMessage({timestamp:A,message:w0.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:w0.cyan(z),showTimestamp:!1})),Z.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:A,message:w0.cyan(W),showTimestamp:!1}))}else if(!p0())console.error(`${G} ${this.environment}.INFO: [BOX] ${H}`);let E=`${G} ${this.environment}.INFO: [BOX] ${H}
|
|
443
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(E)}async prompt($){if(p0())return Promise.resolve(!0);return new Promise((h)=>{console.error(`${w0.cyan("?")} ${$} (y/n) `);let A=(G)=>{let J=G.toString().trim().toLowerCase();D0.stdin.removeListener("data",A);try{if(typeof D0.stdin.setRawMode==="function")D0.stdin.setRawMode(!1)}catch{}D0.stdin.pause(),console.error(""),h(J==="y"||J==="yes")};try{if(typeof D0.stdin.setRawMode==="function")D0.stdin.setRawMode(!0)}catch{}D0.stdin.resume(),D0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...h){if(!this.enabled)return;let A=$;if(h&&h.length>0){let E=/%([sdijfo%])/g,Y=0;if(A=$.replace(E,(U,z)=>{if(z==="%")return"%";if(Y>=h.length)return U;let W=h[Y++];switch(z){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return U}}),Y<h.length)A+=` ${h.slice(Y).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}let{consoleText:G,fileText:J}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",Y=this.options.showIcons===!1?"":`${w0.blue("\u25D0")} `;console.error(`${Y}${E} ${w0.cyan(G)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${J}
|
|
444
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar($,h=!1){if(!this.enabled||!this.shouldStyleConsole()||!D0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),G=Math.round($.barLength*A/100),J=$.barLength-G,H=w0.green("\u2501".repeat(G)),E=w0.gray("\u2501".repeat(J)),Y=`[${H}${E}]`,U=`${A}%`.padStart(4),z=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":h||A===100?w0.green("\u2713"):w0.blue("\u25B6"),Z=this.options.showTags!==!1&&this.name?` ${w0.gray(this.formatTag(this.name))}`:"",F=`\r${W}${Z} ${Y} ${U}${z}`,w=D0.stdout.columns||80,B=" ".repeat(Math.max(0,w-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${B}`,D0.stdout.write($.lastRenderedLine),h)D0.stdout.write(`
|
|
445
|
-
`)}finishProgressBar($,h){if(!this.enabled||!this.fancy||p0()||!D0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(h)$.message=h;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(p0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let h=await uG(this.config.logDirectory),A=[];for(let G of h){if(!($.name?new RegExp($.name.replace("*",".*")).test(G):G.startsWith(this.name))||!G.endsWith(".log"))continue;let J=hh(this.config.logDirectory,G);if($.before)try{if((await $h(J)).mtime>=$.before)continue}catch(H){console.error(`Failed to get stats for file ${J}:`,H);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let G of A)try{await iG(G),console.warn(`Deleted log file: ${G}`)}catch(J){console.error(`Failed to delete log file ${G}:`,J)}console.warn("Log clearing process finished.")}catch(h){console.error("Error during log clearing process:",h)}}}async function CY($,h={}){let{maxRetries:A=3,retryDelay:G=1000,isRetryable:J=()=>!0,fallback:H}=h,E=Error("Unknown error occurred");for(let Y=0;Y<=A;Y++)try{return await $()}catch(U){if(E=U instanceof Error?U:Error(String(U)),Y===A||!J(E))break;if(G>0)await new Promise((z)=>setTimeout(z,G))}if(H!==void 0)return H;throw E instanceof Error?E:Error(`Unknown error: ${String(E)}`)}function KY($){return $ instanceof X$}function C6($){return $ instanceof aG}function K6($){if(KY($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((h)=>$.message.toLowerCase().includes(h.toLowerCase()))}class hJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,h)=>h==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let h=$.toLowerCase();return["true","1","yes"].includes(h)}},{name:"number",canParse:($,h)=>h==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let h=Number($);if(Number.isNaN(h))throw TypeError(`Cannot parse "${$}" as number`);return h}},{name:"array",canParse:($,h)=>h==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let h=JSON.parse($);if(Array.isArray(h))return h}catch{}return $.split(",").map((h)=>h.trim())}},{name:"json",canParse:($,h)=>h==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(h){throw Error(`Cannot parse "${$}" as JSON: ${h}`)}}}]}async applyEnvironmentVariables($,h,A={}){let{prefix:G,useCamelCase:J=!0,useBackwardCompatibility:H=!0,customParsers:E={},verbose:Y=!1,trackPerformance:U=!0}=A,z=async()=>{if(!$)return{config:h,source:{type:"environment",priority:50,timestamp:new Date}};let W=G||this.generateEnvPrefix($),Z={...h};return this.processObject(Z,[],W,{useCamelCase:J,useBackwardCompatibility:H,customParsers:E,verbose:Y,configName:$}),{config:Z,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return OA.track("applyEnvironmentVariables",z,{configName:$});return z()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,h){if(!h)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,h,A,G){for(let[J,H]of Object.entries($)){let E=[...h,J],Y=E.map((W)=>this.formatEnvKey(W,G.useCamelCase)),U=`${A}_${Y.join("_")}`,z=G.useBackwardCompatibility?`${A}_${E.map((W)=>W.toUpperCase()).join("_")}`:null;if(G.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,E,A,G);else{let W=sG.env[U]||(z?sG.env[z]:void 0);if(W!==void 0){if(G.verbose){let Z=sG.env[U]?U:z}try{$[J]=this.parseEnvironmentValue(W,typeof H,U,G.customParsers,G.configName)}catch(Z){if(Z instanceof eG)throw Z;throw X1.envVar(U,W,typeof H,G.configName)}}}}}parseEnvironmentValue($,h,A,G,J){for(let[H,E]of Object.entries(G))try{return E($)}catch{continue}for(let H of this.defaultParsers)if(H.canParse($,h))try{return H.parse($)}catch{throw X1.envVar(A,$,`${h} (via ${H.name} parser)`,J)}return $}getEnvironmentVariables($){let h={},A=$.toUpperCase();for(let[G,J]of Object.entries(sG.env))if(G.startsWith(A)&&J!==void 0)h[G]=J;return h}validateEnvironmentVariable($,h,A){let G=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))G.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,h,A,{})}catch(J){G.push(`Cannot parse value "${h}" as ${A}: ${J}`)}return{isValid:G.length===0,errors:G}}generateEnvVarDocs($,h,A={}){let{prefix:G,format:J="text"}=A,H=G||this.generateEnvPrefix($),E=[];switch(this.extractEnvVarInfo(h,[],H,E),J){case"markdown":return this.formatAsMarkdown(E,$);case"json":return JSON.stringify(E,null,2);default:return this.formatAsText(E,$)}}extractEnvVarInfo($,h,A,G){for(let[J,H]of Object.entries($)){let E=[...h,J],Y=`${A}_${E.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,E,A,G);else G.push({key:Y,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${E.join(".")}`,example:this.generateExample(H)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,h){let A=`Environment Variables for ${h}:
|
|
446
|
-
|
|
447
|
-
`;for(let G of $)A+=`${G.key}
|
|
448
|
-
`,A+=` Type: ${G.type}
|
|
449
|
-
`,A+=` Description: ${G.description}
|
|
450
|
-
`,A+=` Example: ${G.example}
|
|
451
|
-
|
|
452
|
-
`;return A}formatAsMarkdown($,h){let A=`# Environment Variables for ${h}
|
|
453
|
-
|
|
454
|
-
`;A+=`| Variable | Type | Description | Example |
|
|
455
|
-
`,A+=`|----------|------|-------------|----------|
|
|
456
|
-
`;for(let G of $)A+=`| \`${G.key}\` | ${G.type} | ${G.description} | \`${G.example}\` |
|
|
457
|
-
`;return A}}function B6($,h){let A=G6("process");if(typeof A>"u"||!A.env)return h;let G=A.env[$];return G!==void 0?G:h}function IY($,h,A={}){return PY($,h,A,new WeakMap)}function PY($,h,A,G){let{arrayMergeMode:J="replace",skipNullish:H=!1,customMerger:E}=A;if(h===null||h===void 0)return H?$:h;if(E){let Y=E($,h);if(Y!==void 0)return Y}if(Array.isArray(h)||Array.isArray($))return NY($,h,J,G);if(!D$(h)||!D$($))return h;return T6($,h,A,G)}function NY($,h,A,G){if(Array.isArray(h)&&!Array.isArray($))return h;if(Array.isArray($)&&!Array.isArray(h))return h;if(Array.isArray(h)&&Array.isArray($))switch(A){case"replace":return h;case"concat":return I6($,h);case"smart":return P6($,h,G);default:return h}return h}function I6($,h){let A=[...h];for(let G of $)if(!A.some((J)=>uH(J,G)))A.push(G);return A}function P6($,h,A){if(h.length===0)return $;if($.length===0)return h;if(D$(h[0])&&D$($[0]))return N6($,h,A);if(h.every((G)=>typeof G==="string")&&$.every((G)=>typeof G==="string")){let G=[...h];for(let J of $)if(!G.includes(J))G.push(J);return G}return h}function N6($,h,A){let G=[...h];for(let J of $){if(!D$(J)){G.push(J);continue}let H=["id","name","key","path","type"],E=!1;for(let Y of H)if(Y in J){if(G.find((U)=>D$(U)&&(Y in U)&&U[Y]===J[Y])){E=!0;break}}if(!E)G.push(J)}return G}function T6($,h,A,G){let J=h;if(D$(J)&&G.has(J))return G.get(J);let H={...$};if(D$(J))G.set(J,H);for(let E in J){if(!Object.prototype.hasOwnProperty.call(J,E))continue;let Y=J[E],U=H[E];if(A.skipNullish&&(Y===null||Y===void 0))continue;if(Y===null||Y===void 0){H[E]=Y;continue}if(D$(Y)&&D$(U))H[E]=PY(U,Y,A,G);else if(Array.isArray(Y)||Array.isArray(U))H[E]=NY(U,Y,A.arrayMergeMode||"smart",G);else H[E]=Y}return H}function rH($,h,A="replace"){return IY($,h,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function uH($,h){if($===h)return!0;if(Array.isArray($)&&Array.isArray(h)){if($.length!==h.length)return!1;for(let A=0;A<$.length;A++)if(!uH($[A],h[A]))return!1;return!0}if(D$($)&&D$(h)){let A=Object.keys($),G=Object.keys(h);if(A.length!==G.length)return!1;for(let J of A){if(!Object.prototype.hasOwnProperty.call(h,J))return!1;if(!uH($[J],h[J]))return!1}return!0}return!1}function D$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class AJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,h,A={}){let{arrayStrategy:G="replace",useCache:J=!0,cacheTtl:H,trackPerformance:E=!0,verbose:Y=!1}=A;if(J){let z=Qh.getWithFileCheck("file",$);if(z){if(Y)console.log(`Configuration loaded from cache: ${$}`);return z}}let U=async()=>{if(!rG($))return null;try{let z=`?t=${Date.now()}`,W=await import($+z),Z=W.default||W,F="default"in W,w=Object.keys(W).length>0;if(!F&&!w)throw new UA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof Z!=="object"||Z===null||Array.isArray(Z))throw new UA($,Error("Configuration must export a valid object"),"unknown");let B={config:rH(h,Z,G),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)Qh.setWithFileCheck("file",B,$,H);return B}catch(z){throw z instanceof Error?X1.configLoad($,z):X1.configLoad($,Error(String(z)))}};if(E)return OA.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,h,A={}){for(let G of $)try{let J=await this.loadFromPath(G,h,A);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(A.verbose)console.warn(`Failed to load config from ${G}:`,J)}return null}generateConfigPaths($,h,A){let G=this.generateNamePatterns($,A),J=[];for(let H of G)for(let E of this.extensions)J.push(kH(h,`${H}${E}`));return J}generateNamePatterns($,h){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let G=h===void 0?[]:Array.isArray(h)?h:[h];for(let H of G){if(!H)continue;if(A.push(H,`.${H}.config`,`${H}.config`,`.${H}`),$)A.push(`${$}.${H}.config`,`.${$}.${H}.config`)}let J=new Set;return A.filter((H)=>{if(!H||J.has(H))return!1;return J.add(H),!0})}checkFileAccess($){return CY(async()=>{return rG($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,h,A){let G=[];if(!rG($))return G;if(h||A){let J=this.generateNamePatterns(h||"",A);for(let H of J)for(let E of this.extensions){let Y=kH($,`${H}${E}`);if(await this.checkFileAccess(Y))G.push(Y)}}else try{let{readdirSync:J}=await import("fs"),H=J($);for(let E of H)if(this.looksLikeConfigFile(E)){let Y=kH($,E);if(await this.checkFileAccess(Y))G.push(Y)}}catch{return[]}return G}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((h)=>h.test($))}async validateConfigFile($){let h=[];try{if(!rG($))return h.push("Configuration file does not exist"),h;let A=await import($),G=A.default||A;if(G===void 0)h.push("Configuration file must export a default value or named exports");else if(typeof G!=="object"||G===null)h.push("Configuration must be an object");else if(Array.isArray(G))h.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),H=J($,"utf8");JSON.parse(H)}catch(J){h.push(`Invalid JSON syntax: ${J}`)}}catch(A){h.push(`Failed to load configuration file: ${A}`)}return h}async getFileModificationTime($){try{let{statSync:h}=await import("fs");return h($).mtime}catch{return null}}async preloadConfigurations($,h={}){let A=new Map;return await Promise.allSettled($.map(async(G)=>{try{let J=await this.loadFromPath(G,{},h);if(J)A.set(G,J.config)}catch(J){if(h.verbose)console.warn(`Failed to preload ${G}:`,J)}})),A}}class oH{async validateConfiguration($,h,A={}){let{stopOnFirstError:G=!1,validateRequired:J=!0,validateTypes:H=!0,customRules:E=[],trackPerformance:Y=!0,verbose:U=!1}=A,z=async()=>{let W=[],Z=[],F={stopOnFirstError:G,validateRequired:J,validateTypes:H,customRules:E,trackPerformance:Y,verbose:U};try{if(typeof h==="string")return await this.validateWithSchemaFile($,h,F);else if(Array.isArray(h))return this.validateWithRules($,[...h,...E],F);else return this.validateWithJSONSchema($,h,F)}catch(w){return W.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:W,warnings:Z}}};if(Y)return await OA.track("validateConfiguration",z);return z()}async validateWithSchemaFile($,h,A){try{if(!u7(h))throw new YA(h,[{path:"",message:"Schema file does not exist"}]);let G=await import(h),J=G.default||G;if(Array.isArray(J))return this.validateWithRules($,J,A);else return this.validateWithJSONSchema($,J,A)}catch(G){throw new YA(h,[{path:"",message:`Failed to load schema: ${G}`}])}}validateWithJSONSchema($,h,A){let G=[],J=[];return this.validateObjectAgainstSchema($,h,"",G,J,A),{isValid:G.length===0,errors:G,warnings:J}}validateObjectAgainstSchema($,h,A,G,J,H){if(H.validateTypes&&h.type){let E=Array.isArray($)?"array":typeof $,Y=Array.isArray(h.type)?h.type:[h.type];if(!Y.includes(E)){if(G.push({path:A,message:`Expected type ${Y.join(" or ")}, got ${E}`,expected:Y.join(" or "),actual:E,rule:"type"}),H.stopOnFirstError)return}}if(h.enum&&!h.enum.includes($)){if(G.push({path:A,message:`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:$,rule:"enum"}),H.stopOnFirstError)return}if(typeof $==="string"){if(h.minLength!==void 0&&$.length<h.minLength)G.push({path:A,message:`String length must be at least ${h.minLength}`,expected:`>= ${h.minLength}`,actual:$.length,rule:"minLength"});if(h.maxLength!==void 0&&$.length>h.maxLength)G.push({path:A,message:`String length must not exceed ${h.maxLength}`,expected:`<= ${h.maxLength}`,actual:$.length,rule:"maxLength"});if(h.pattern){if(!new RegExp(h.pattern).test($))G.push({path:A,message:`String does not match pattern ${h.pattern}`,expected:h.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(h.minimum!==void 0&&$<h.minimum)G.push({path:A,message:`Value must be at least ${h.minimum}`,expected:`>= ${h.minimum}`,actual:$,rule:"minimum"});if(h.maximum!==void 0&&$>h.maximum)G.push({path:A,message:`Value must not exceed ${h.maximum}`,expected:`<= ${h.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&h.items)for(let E=0;E<$.length;E++){let Y=A?`${A}[${E}]`:`[${E}]`;if(this.validateObjectAgainstSchema($[E],h.items,Y,G,J,H),H.stopOnFirstError&&G.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let E=$;if(H.validateRequired&&h.required){for(let Y of h.required)if(!(Y in E)){if(G.push({path:A?`${A}.${Y}`:Y,message:`Missing required property '${Y}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(h.properties){for(let[Y,U]of Object.entries(h.properties))if(Y in E){let z=A?`${A}.${Y}`:Y;if(this.validateObjectAgainstSchema(E[Y],U,z,G,J,H),H.stopOnFirstError&&G.length>0)return}}if(h.additionalProperties===!1){let Y=new Set(Object.keys(h.properties||{}));for(let U of Object.keys(E))if(!Y.has(U))J.push({path:A?`${A}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,h,A){let G=[],J=[];for(let H of h)try{let E=this.getValueByPath($,H.path),Y=this.validateWithRule(E,H,H.path);if(G.push(...Y),A.stopOnFirstError&&G.length>0)break}catch(E){G.push({path:H.path,message:`Rule validation failed: ${E}`,rule:"system"})}return{isValid:G.length===0,errors:G,warnings:J}}validateWithRule($,h,A){let G=[];if(h.required&&($===void 0||$===null))return G.push({path:A,message:h.message||`Property '${A}' is required`,expected:"required",rule:"required"}),G;if($===void 0||$===null)return G;if(h.type){let J=Array.isArray($)?"array":typeof $;if(J!==h.type)G.push({path:A,message:h.message||`Expected type ${h.type}, got ${J}`,expected:h.type,actual:J,rule:"type"})}if(h.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<h.min)G.push({path:A,message:h.message||`Value must be at least ${h.min}`,expected:`>= ${h.min}`,actual:J,rule:"min"})}if(h.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>h.max)G.push({path:A,message:h.message||`Value must not exceed ${h.max}`,expected:`<= ${h.max}`,actual:J,rule:"max"})}if(h.pattern&&typeof $==="string"){if(!h.pattern.test($))G.push({path:A,message:h.message||`Value does not match pattern ${h.pattern}`,expected:h.pattern.toString(),actual:$,rule:"pattern"})}if(h.enum&&!h.enum.includes($))G.push({path:A,message:h.message||`Value must be one of: ${h.enum.join(", ")}`,expected:h.enum.join(", "),actual:$,rule:"enum"});if(h.validator){let J=h.validator($);if(J)G.push({path:A,message:h.message||J,rule:"custom"})}return G}getValueByPath($,h){if(!h)return $;let A=h.split("."),G=$;for(let J of A)if(G&&typeof G==="object"&&J in G)G=G[J];else return;return G}generateRulesFromInterface($){let h=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let G of A){let[,J,H,E]=G;h.push({path:J,required:!H,type:this.mapTypeScriptType(E)})}return h}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:yY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function k6($){if(!$)return"";let h=Array.isArray($)?$.filter(Boolean):[$];if(h.length===0)return"";if(h.length===1)return` or alias "${h[0]}"`;return` or aliases ${h.map((A)=>`"${A}"`).join(", ")}`}class tH{fileLoader=new AJ;envProcessor=new hJ;validator=new oH;async loadConfig($){let h=Date.now(),{cache:A,performance:G,schema:J,validate:H,...E}=$;try{if(A?.enabled){let U=this.checkCache(E.name||"",E);if(U)return U}let Y;try{Y=await this.loadConfigurationStrategies(E,!0,A)}catch(U){let z=E.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(z)throw U;Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`No configuration file found for "${E.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let W=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),Z=!W&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),F=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(z&&(F||W))throw U;if(Z&&(!z||!F))Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else Y={...await this.applyEnvironmentVariables(E.name||"",E.defaultConfig,E.checkEnv!==!1,E.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(J||H)await this.validateConfiguration(Y.config,J,H,E.name);if(A?.enabled&&Y)this.cacheResult(E.name||"",Y,A,E);if(G?.enabled){let U={operation:"loadConfig",duration:Date.now()-h,configName:E.name,timestamp:new Date};if(G.onMetrics)G.onMetrics(U);if(G.slowThreshold&&U.duration>G.slowThreshold)O$.warn(`Slow configuration loading detected: ${U.duration}ms for ${E.name}`);Y.metrics=U}return Y}catch(Y){let U=Date.now()-h;throw O$.error(`Configuration loading failed after ${U}ms:`,[Y instanceof Error?Y:Error(String(Y))]),Y}}async loadConfigurationStrategies($,h=!1,A){let{name:G="",alias:J,cwd:H,configDir:E,defaultConfig:Y,checkEnv:U=!0,arrayStrategy:z="replace",verbose:W=!1}=$,Z=H||P1.cwd(),F=[],w=await this.loadLocalConfiguration(G,J,Z,E,Y,z,W,U,A);if(w)return F.push(...this.getLocalSearchPaths(G,J,Z,E)),this.finalizeResult(w,F,U,G,W);let B=await this.loadHomeConfiguration(G,J,Y,z,W,U);if(B)return F.push(...this.getHomeSearchPaths(G,J)),this.finalizeResult(B,F,U,G,W);let j=await this.loadPackageJsonConfiguration(G,J,Z,Y,z,W,U);if(j)return F.push(G$(Z,"package.json")),this.finalizeResult(j,F,U,G,W);if(F.push(...this.getAllSearchPaths(G,J,Z,E)),h)throw X1.configNotFound(G,F,J);return{...await this.applyEnvironmentVariables(G,Y,U,W),warnings:[`No configuration file found for "${G}"${k6(J)}, using defaults with environment variables`]}}async loadLocalConfiguration($,h,A,G,J,H,E,Y,U){let z=Y?HA($,J,E):J,W=this.getLocalDirectories(A,G);for(let Z of W){if(E)O$.info(`Searching for configuration in: ${Z}`);let F=this.fileLoader.generateConfigPaths($,Z,h),w=await this.fileLoader.tryLoadFromPaths(F,z,{arrayStrategy:H,verbose:E,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(w){if(E)O$.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration($,h,A,G,J,H){if(!$)return null;let E=H?HA($,A,J):A,Y=[G$(Gh(),".config",$),G$(Gh(),".config"),Gh()];for(let U of Y){if(J)O$.info(`Checking home directory: ${U}`);let z=this.fileLoader.generateConfigPaths($,U,h),W=await this.fileLoader.tryLoadFromPaths(z,E,{arrayStrategy:G,verbose:J});if(W){if(J)O$.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,h,A,G,J,H,E){let Y=E?HA($,G,H):G;try{let U=G$(A,"package.json");if(!vH(U))return null;let z={};try{z=JSON.parse(r7(U,"utf8"))}catch(F){if(H)O$.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let W=z[$],Z=$;if(!W&&h){let F=Array.isArray(h)?h:[h];for(let w of F){if(!w)continue;if(z[w]){W=z[w],Z=w;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(H)O$.success(`Configuration loaded from package.json: ${Z}`);return{config:rH(Y,W,J),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(H)O$.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,h,A,G){if(!A||!$||typeof h!=="object"||h===null||Array.isArray(h))return{config:h,source:{type:"default",priority:10,timestamp:new Date}};return{config:HA($,h,G),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,h,A,G,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,h,A,G){let J=[];if(A){let H=A($);if(H)J.push(...H)}if(h){let H=await this.validator.validateConfiguration($,h);if(!H.isValid)J.push(...H.errors.map((E)=>E.path?`${E.path}: ${E.message}`:E.message))}if(J.length>0)throw X1.configValidation(G||"unknown",J,G)}checkCache($,h){let A=this.generateCacheKey($,h);return Qh.get(A)||null}cacheResult($,h,A,G){let J=this.generateCacheKey($,G);Qh.set(J,h,void 0,A.ttl)}generateCacheKey($,h){let A=[$];if(h.alias){let G=Array.isArray(h.alias)?h.alias.join(","):h.alias;A.push(`alias:${G}`)}if(h.cwd)A.push(`cwd:${h.cwd}`);if(h.configDir)A.push(`configDir:${h.configDir}`);if("checkEnv"in h)A.push(`checkEnv:${h.checkEnv}`);return A.join("|")}getLocalDirectories($,h){return Array.from(new Set([$,G$($,"config"),G$($,".config"),h?G$($,h):void 0].filter(Boolean)))}getAllSearchPaths($,h,A,G){let J=[];return J.push(...this.getLocalSearchPaths($,h,A,G)),J.push(...this.getHomeSearchPaths($,h)),J.push(G$(A,"package.json")),J}getLocalSearchPaths($,h,A,G){let J=this.getLocalDirectories(A,G),H=[];for(let E of J)H.push(...this.fileLoader.generateConfigPaths($,E,h));return H}getHomeSearchPaths($,h){if(!$)return[];let A=[G$(Gh(),".config",$),G$(Gh(),".config"),Gh()],G=[];for(let J of A)G.push(...this.fileLoader.generateConfigPaths($,J,h));return G}async loadConfigWithResult($){return this.loadConfig($)}}function DY($){let h=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return h||A}async function y6($){return l$.loadConfig({...$,__strictErrorHandling:!0})}async function aH($){let h="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let G;if(A)G=await l$.loadConfig($);else G=await l$.loadConfig({...$,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}});return G?.config??h}catch(G){let J=G instanceof Error?G.name:"UnknownError",H=G instanceof Error?G.message:String(G);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||H.includes("config"))&&$.verbose)O$.warn("Unexpected error loading config, using defaults:",[G instanceof Error?G:Error(String(G))]);let E=A?{...$,defaultConfig:h}:{...$,defaultConfig:h,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await l$.applyEnvironmentVariables(E.name||"",h,!0,E.verbose||!1))?.config??h;return h}}async function q6($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:h}=await import("process");try{return(await l$.loadConfig({name:$,cwd:h(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&DY(A)))return(await l$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await l$.loadConfig({...$,cwd:$.cwd||P1.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(h){if(h instanceof Error&&(h.name==="ConfigNotFoundError"||h.name==="ConfigLoadError"&&DY(h)))return(await l$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw h}}async function x6($,h,A="replace"){let G=new AJ;try{let J=await G.loadFromPath($,h,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function HA($,h,A=!1){let G=new hJ,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(E,Y=[]){let U={...E};for(let[z,W]of Object.entries(E)){let Z=[...Y,z],F=[`${J}_${Z.join("_").toUpperCase()}`,`${J}_${Z.map((j)=>j.toUpperCase()).join("")}`,`${J}_${Z.map((j)=>j.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,B;for(let j of F)if(w=P1.env[j],w!==void 0){B=j;break}if(w!==void 0&&B)if(typeof W==="boolean")U[z]=["true","1","yes"].includes(w.toLowerCase());else if(typeof W==="number"){let j=Number(w);if(!Number.isNaN(j))U[z]=j}else if(Array.isArray(W))try{U[z]=JSON.parse(w)}catch{U[z]=w.split(",").map((j)=>j.trim())}else U[z]=w;else if(W&&typeof W==="object"&&!Array.isArray(W))U[z]=H(W,Z)}return U}return H(h)}function f6($){let h=G$(P1.cwd(),$.configDir),A=G$(P1.cwd(),$.generatedDir),G=G$(A,"config-types.ts");if(!vH(jY(G)))i7(jY(G),{recursive:!0,mode:511});let J=vH(h)?s7(h).map((E)=>E.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${S6}
|
|
458
|
-
export type ConfigNames = ${J.length?`'${J.join("' | '")}'`:"string"}
|
|
459
|
-
`;l7(G,H,{mode:438})}function g6($){let h=null,A=null,G=()=>{if(!A)A=aH($).then((H)=>{return h=H,H},(H)=>{let E="defaultConfig"in $?$.defaultConfig:{};if(h=E,"verbose"in $&&$.verbose)O$.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return E});return A},J="defaultConfig"in $?$.defaultConfig:{};return h=J,G(),new Proxy({},{get(H,E){if(h)return h[E];let Y=J[E];return G(),Y},has(H,E){return E in(h||J)},ownKeys(){return Object.keys(h||J)},getOwnPropertyDescriptor(H,E){return Object.getOwnPropertyDescriptor(h||J,E)},set(H,E,Y){if(!h)h={...J};return h[E]=Y,!0}})}function b6($){let h=LY(a7.cwd(),$?.configDir||"./config");function A(){if(!o7(h))return[];let J=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],E=t7(h).filter((U)=>J.has(yH(U))).map((U)=>({base:U.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:U})),Y=new Map;for(let{base:U,file:z}of E){let W=yH(z).toLowerCase(),Z=Y.get(U);if(!Z){Y.set(U,z);continue}let F=yH(Z).toLowerCase();if(H.indexOf(W)<H.indexOf(F))Y.set(U,z)}return Array.from(Y.entries()).map(([U,z])=>({base:U,file:z})).sort((U,z)=>U.base.localeCompare(z.base))}function G(){let J=A(),H=J.map((U)=>U.base),E=H.length?H.map((U)=>`'${U}'`).join(" | "):"string",Y=J.length?`{
|
|
460
|
-
${J.map((U)=>{let z=LY(h,U.file).replace(/\\/g,"/");return` '${U.base}': typeof import('${z}').default`}).join(`,
|
|
461
|
-
`)}
|
|
462
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${E}
|
|
463
|
-
export type ConfigByName = ${Y}
|
|
464
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
465
|
-
export type ConfigOf = Config
|
|
466
|
-
`}return{name:"bunfig-plugin",setup(J){J.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),J.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:G(),loader:"ts"}})}}}async function bY(){if(!gH)gH=await aH({name:"faker",alias:"mock",defaultConfig:GJ});return gH}function Eh($){let h=$.replace(/-/g,"_").split("_"),A=h[0].toLowerCase(),G=h[1]?.toUpperCase(),J=G?`${A}-${G.toLowerCase()}`:A;return{full:$,language:A,region:G,packageName:J,normalized:G?`${A}_${G}`:A}}function m6($){let h=Eh($);if(h.region)return[h.normalized,h.language];return[h.language]}function d6($){return`@mock-locale/${Eh($).packageName}`}function cY($,h){let A={...$};for(let G in h){let J=h[G],H=$[G];if(J===void 0)continue;if(typeof J==="object"&&J!==null&&!Array.isArray(J)&&typeof H==="object"&&H!==null&&!Array.isArray(H))A[G]=cY(H,J);else A[G]=J}return A}function I1(){let $=mY.cwd(),h=Hh($,"package.json");if(!Jh(h))return!1;try{let A=JSON.parse(n6(h,"utf-8"));return!!(A.workspaces||A.workspace)}catch{return!1}}function $E(){let $=mY.cwd();if(Jh(Hh($,"bun.lockb"))||Jh(Hh($,"bun.lock")))return"bun";if(Jh(Hh($,"pnpm-lock.yaml")))return"pnpm";if(Jh(Hh($,"yarn.lock")))return"yarn";if(Jh(Hh($,"package-lock.json")))return"npm";return"bun"}function hE($,h={}){let A=$E(),{silent:G=!1}=h;if(!G)console.log(`
|
|
467
|
-
\uD83D\uDCE6 Installing ${$} using ${A}...`);let J={bun:{cmd:"bun",args:["add",$]},npm:{cmd:"npm",args:["install",$]},yarn:{cmd:"yarn",args:["add",$]},pnpm:{cmd:"pnpm",args:["add",$]}},{cmd:H,args:E}=J[A];try{let Y=p6(H,E,{stdio:"pipe",shell:!0}),U=Y.stdout?.toString()||"",z=Y.stderr?.toString()||"",W=U+z;if(!G){if(U)console.log(U);if(z)console.error(z)}if(Y.status===0){if(!G)console.log(`\u2713 Successfully installed ${$}`);return!0}else{let Z=W;if(Z.toLowerCase().includes("dependency loop")||Z.includes("DependencyLoop")||Z.includes("has a dependency loop")||Z.includes("An internal error occurred (DependencyLoop)")){if(!G){if(console.log(`
|
|
468
|
-
\u26A0\uFE0F Package ${$} is already available in the workspace and cannot be installed separately due to a dependency loop.`),I1())console.log(" This is expected when running in a workspace environment. The package should be available for import.")}return!0}if(!G)console.error(`\u2717 Failed to install ${$}`);return!1}}catch(Y){if(!G)console.error(`\u2717 Error installing ${$}:`,Y);return!1}}function Kh($,h){let A=[];for(let G of h.rules)if(!G.validator($)){let J=G.errorMessage||`Validation failed for value: ${$}`;if(A.push(J),h.strict)throw Error(J)}return{isValid:A.length===0,errors:A}}function Bh($,h){let{items:A}=h;if(A.length===0)throw Error("Cannot select from empty weighted items array");let G=A.reduce((E,Y)=>E+Y.weight,0);if(G<=0)throw Error("Total weight must be greater than 0");let J=$.number()*G,H=0;for(let E of A)if(H+=E.weight,J<=H)return E.item;return A[A.length-1].item}function dY($,h){return $.filter((A)=>{if(h.gender&&A.gender&&A.gender!==h.gender)return!1;if(h.country){let G=Array.isArray(h.country)?h.country:[h.country];if(A.country&&!G.includes(A.country))return!1}if(h.region){let G=Array.isArray(h.region)?h.region:[h.region];if(A.region&&!G.includes(A.region))return!1}if(h.locale&&A.locale&&A.locale!==h.locale)return!1;if(h.ageRange&&A.age){let{min:G,max:J}=h.ageRange;if(A.age<G||A.age>J)return!1}for(let[G,J]of Object.entries(h))if(G!=="gender"&&G!=="country"&&G!=="region"&&G!=="locale"&&G!=="ageRange"&&A[G]!==void 0){if(!(Array.isArray(J)?J:[J]).includes(A[G]))return!1}return!0})}function o$($,h){let A={...$};for(let G of h){let{field:J,dependsOn:H,mapping:E}=G;if(A[H]&&E[A[H]])A[J]=E[A[H]]}return A}function pY($,h={}){let A=$();if(h.relationships)return o$(A,h.relationships);return A}class JJ{providers=new Map;register($){let{category:h,name:A}=$;if(!this.providers.has(h))this.providers.set(h,new Map);this.providers.get(h).set(A,$)}get($,h){return this.providers.get($)?.get(h)}getProvidersInCategory($){let h=this.providers.get($);return h?Array.from(h.values()):[]}getCategories(){return Array.from(this.providers.keys())}remove($,h){let A=this.providers.get($);if(A)return A.delete(h);return!1}clear(){this.providers.clear()}}class Uh{random;locale;constructor($,h){this.random=$,this.locale=h}street(){let $=this.random.arrayElement(this.locale.address.street),h=this.streetSuffix();return`${$} ${h}`}streetSuffix(){return this.random.arrayElement(this.locale.address.streetSuffix??["Street","Avenue","Road","Boulevard","Drive","Lane","Way"])}streetAddress($){let h=this.buildingNumber(),A=this.street();if($?.useFullAddress)return`${h} ${A}, ${this.city()}, ${this.stateAbbr()} ${this.zipCode()}`;return`${h} ${A}`}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 h=$?.min??-90,A=$?.max??90,G=$?.precision??4;return this.random.float(h,A,G)}longitude($){let h=$?.min??-180,A=$?.max??180,G=$?.precision??4;return this.random.float(h,A,G)}address(){return this.streetAddress({useFullAddress:!0})}cityAdvanced($){let h;if($?.constraints?.country){let A=$.constraints.country,G=Array.isArray(A)?A:[A];h=this.city()}else h=this.city();if($?.weighted)h=Bh(this.random,$.weighted);if($?.relationships)h=o$({city:h,country:$?.constraints?.country},$.relationships).city||h;if($?.validation){let A=Kh(h,$.validation);if(!A.isValid){if($.validation.strict)throw Error(`Validation failed: ${A.errors.join(", ")}`);h=this.city()}}return h}countryAdvanced($){let h;if($?.constraints?.country){let A=$.constraints.country,G=Array.isArray(A)?A:[A];h=this.random.arrayElement(G)}else h=this.country();if($?.weighted)h=Bh(this.random,$.weighted);if($?.relationships)h=o$({country:h},$.relationships).country||h;if($?.validation){let A=Kh(h,$.validation);if(!A.isValid){if($.validation.strict)throw Error(`Validation failed: ${A.errors.join(", ")}`);h=this.country()}}return h}addressAdvanced($){let h=this.countryAdvanced($),A=this.cityAdvanced($),G=this.state(),J=this.stateAbbr(),H=this.zipCode(),E=this.street(),Y=this.latitude(),U=this.longitude(),z={street:E,city:A,state:G,stateAbbr:J,country:h,countryCode:this.countryCode(),zipCode:H,latitude:Y,longitude:U};if($?.relationships)return o$(z,$.relationships);return z}neighborhood($){let h=$?.size||this.random.int(3,10),A=this.cityAdvanced($),G=this.state(),J=this.zipCode(),H=[];for(let E=0;E<h;E++)H.push({street:this.street(),city:A,state:G,zipCode:J,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 H}}class Yh{random;locale;constructor($,h){this.random=$,this.locale=h}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 zh{random;locale;constructor($,h){this.random=$,this.locale=h}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 H=Array.from({length:9},()=>this.random.int(0,9)),E=this.random.int(0,10)===10?"X":String(this.random.int(0,9));return`${H.slice(0,1).join("")}-${H.slice(1,4).join("")}-${H.slice(4,9).join("")}-${E}`}let $="978",h=this.random.int(0,9),A=Array.from({length:3},()=>this.random.int(0,9)).join(""),G=Array.from({length:5},()=>this.random.int(0,9)).join(""),J=this.random.int(0,9);return`${$}-${h}-${A}-${G}-${J}`}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 Wh{random;locale;constructor($,h){this.random=$,this.locale=h}hex($){let h=$?.prefix??"#",A=this.random.int(0,16777215).toString(16).padStart(6,"0").toUpperCase();return h+A}rgb($){let h=this.random.int(0,255),A=this.random.int(0,255),G=this.random.int(0,255);if($?.alpha){let J=this.random.float(0,1,2);if($?.format==="array")return[h,A,G,J];return`rgba(${h}, ${A}, ${G}, ${J})`}if($?.format==="array")return[h,A,G];return`rgb(${h}, ${A}, ${G})`}hsl($){let h=this.random.int(0,360),A=this.random.int(0,100),G=this.random.int(0,100);if($?.alpha){let J=this.random.float(0,1,2);if($?.format==="array")return[h,A,G,J];return`hsla(${h}, ${A}%, ${G}%, ${J})`}if($?.format==="array")return[h,A,G];return`hsl(${h}, ${A}%, ${G}%)`}css($){let h=$?.format??this.random.arrayElement(["hex","rgb","hsl"]);if(h==="hex")return this.hex();if(h==="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 Zh{random;locale;constructor($,h){this.random=$,this.locale=h}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"],h=this.locale?.commerce?.productMaterial??["Steel","Wooden","Concrete","Plastic","Cotton","Granite","Rubber","Metal","Soft","Fresh","Frozen","Silk","Leather","Glass","Carbon","Aluminum"],A=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(h)} ${this.random.arrayElement(A)}`}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 h=$?.min??1,A=$?.max??1000,G=$?.dec??2,J=$?.symbol??"",H=this.random.float(h,A,G);return J+H.toFixed(G)}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}."],h=["lifetime warranty","money-back guarantee","premium quality","eco-friendly design","cutting-edge technology","ergonomic design","sleek finish","modern aesthetics"],A=["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(h)).replace("{benefit}",this.random.arrayElement(A))}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"],h=this.random.int(10,99);return`${this.random.arrayElement($)}${h}`}sku(){let $=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3),h=this.random.int(1e4,99999),A=this.random.arrayElement("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")).repeat(3);return`${$}-${h}-${A}`}}class Xh{random;locale;constructor($,h){this.random=$,this.locale=h}name(){let $=this.random.arrayElement(this.locale.company.name??["Company"]),h=this.random.arrayElement(this.locale.company.suffix??["Inc","LLC","Corp"]);return`${$} ${h}`}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"]),h=this.random.arrayElement(this.locale.company.descriptor??["digital"]),A=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${h} ${A}`}buzzword(){return this.random.arrayElement(this.locale.company.buzzwords??["innovation"])}bs(){let $=this.buzzword(),h=this.random.arrayElement(this.locale.company.descriptor??["digital"]),A=this.random.arrayElement(this.locale.company.noun??["solution"]);return`${$} ${h} ${A}`}}class zA{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 h=0;h<24;h++)$+="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 h=$?.engine??this.engine().toLowerCase().replace(/ /g,""),A="user",G="password",J="localhost",H=this.random.int(3000,9999),E=this.table(),Y={mysql:"mysql",postgresql:"postgresql",mongodb:"mongodb",redis:"redis"}[h]||"jdbc";if(h==="mongodb")return`${Y}://user:password@localhost:${H}/${E}`;return`${Y}://user:password@localhost:${H}/${E}`}}class WA{random;constructor($){this.random=$}past($){let h=$?.years??1,A=$?.to??new Date,G=$?.from??new Date(A.getTime()-h*365*24*60*60*1000);return this.between({from:G,to:A})}future($){let h=$?.years??1,A=$?.from??new Date,G=$?.to??new Date(A.getTime()+h*365*24*60*60*1000);return this.between({from:A,to:G})}between($){let h=$.from??new Date(Date.now()-31536000000),A=$.to??new Date,G=h.getTime(),J=A.getTime(),H=this.random.int(G,J);return new Date(H)}recent($){let h=$?.days??1,A=new Date,G=new Date(A.getTime()-h*24*60*60*1000);return this.between({from:G,to:A})}soon($){let h=$?.days??1,A=new Date,G=new Date(A.getTime()+h*24*60*60*1000);return this.between({from:A,to:G})}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($)}birthdate($){let h=$?.mode??"age",A=$?.refDate??new Date;if(h==="year"){let U=$?.min??1900,z=$?.max??A.getUTCFullYear(),W=new Date(Date.UTC(U,0,1)),Z=new Date(Date.UTC(z,11,31,23,59,59,999));return this.between({from:W,to:Z})}let G=Math.max(0,$?.min??18),J=Math.max(G,$?.max??80),H=(U)=>U*365.25*24*60*60*1000,E=new Date(A.getTime()-H(J)),Y=new Date(A.getTime()-H(G));return this.between({from:E,to:Y})}}class ZA{random;constructor($){this.random=$}amount($){let h=$?.min??0,A=$?.max??1e4,G=$?.dec??2,J=$?.symbol??"",H=this.random.float(h,A,G);return J+H.toFixed(G)}account($=8){let h="";for(let A=0;A<$;A++)h+=this.random.int(0,9);return h}accountName(){let $=["Savings","Checking","Money Market","Investment","Credit Card","Personal Loan"];return`${this.random.arrayElement($)} Account`}routingNumber(){return this.account(9)}creditCardNumber($){let h=$?.formatted??!0,A=$?.issuer??this.random.arrayElement(["visa","mastercard","amex","discover"]),G="",J=16;switch(A){case"visa":G="4",J=16;break;case"mastercard":G=`5${this.random.int(1,5)}`,J=16;break;case"amex":G=`3${this.random.arrayElement(["4","7"])}`,J=15;break;case"discover":G="6011",J=16;break}let H=G;while(H.length<J)H+=this.random.int(0,9);if(h){if(A==="amex")return`${H.slice(0,4)}-${H.slice(4,10)}-${H.slice(10)}`;return H.match(/.{1,4}/g)?.join("-")??H}return H}cvv(){return this.account(3)}iban($){let h=$?.countryCode??"GB",A=$?.formatted??!1,G=this.random.int(10,99).toString(),J="WEST",H=this.account(14),E=h+G+"WEST"+H;if(A)return E.match(/.{1,4}/g)?.join(" ")??E;return E}bic(){let $="";for(let h=0;h<4;h++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let h=0;h<2;h++)$+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[this.random.int(0,25)];for(let h=0;h<2;h++)$+=this.random.arrayElement([..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),...Array.from({length:10},(A,G)=>G.toString())]);return $}bitcoin(){let $=this.random.arrayElement(["1","3"]);for(let h=0;h<33;h++)$+="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[this.random.int(0,57)];return $}ethereum(){let $="0x";for(let h=0;h<40;h++)$+="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 jh{random;locale;constructor($,h){this.random=$,this.locale=h}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"],h=["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(h)}`}}class XA{random;constructor($){this.random=$}branch(){let $=["feature","bugfix","hotfix","refactor","chore","docs","test"],h=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],A=["authentication","database","api","ui","tests","documentation","config","validation","error-handling","logging","security","performance","caching"],G=this.random.arrayElement($),J=this.random.arrayElement(h),H=this.random.arrayElement(A);return`${G}/${J}-${H}`}commitMessage(){let $=["feat","fix","docs","style","refactor","test","chore","perf"],h=["api","ui","auth","db","config","deps","core","utils"],A=["add","update","fix","remove","improve","refactor","optimize","enhance","implement"],G=["user authentication","database connection","API endpoint","UI component","test coverage","documentation","configuration","validation logic","error handling","logging system"],J=this.random.arrayElement($),H=this.random.boolean(0.5)?`(${this.random.arrayElement(h)})`:"",E=this.random.arrayElement(A),Y=this.random.arrayElement(G);return`${J}${H}: ${E} ${Y}`}commitSha($){let h=$?.short?7:40,A="0123456789abcdef",G="";for(let J=0;J<h;J++)G+="0123456789abcdef"[this.random.int(0,15)];return G}commitEntry(){let $=this.commitSha({short:!0}),h=this.commitMessage();return`${$} ${h}`}commitAuthor($){let h=["John Doe","Jane Smith","Bob Johnson","Alice Williams","Charlie Brown","Diana Davis","Eve Martinez","Frank Garcia","Grace Wilson","Henry Lee"],A=$?.name??this.random.arrayElement(h),G=$?.email??`${A.toLowerCase().replace(" ",".")}@example.com`;return`${A} <${G}>`}remote($){let h=$?.protocol??this.random.arrayElement(["https","ssh"]),A=$?.platform??this.random.arrayElement(["github","gitlab","bitbucket"]),G=this.random.arrayElement(["acme","techcorp","devteam","opensource","mycompany"]),J=this.random.arrayElement(["webapp","api","mobile-app","backend","frontend","monorepo"]),H={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};if(h==="ssh")return`git@${H[A]}:${G}/${J}.git`;return`https://${H[A]}/${G}/${J}.git`}tag(){let $=this.random.int(0,5),h=this.random.int(0,20),A=this.random.int(0,50),G=this.random.boolean(0.2)?`-${this.random.arrayElement(["alpha","beta","rc"])}.${this.random.int(1,10)}`:"";return`v${$}.${h}.${A}${G}`}}class Lh{random;locale;constructor($,h){this.random=$,this.locale=h}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 jA{random;constructor($){this.random=$}randomElement($){return this.random.arrayElement($)}arrayElement($){return this.random.arrayElement($)}arrayElements($,h){return this.random.arrayElements($,h)}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 h=Object.keys($);return this.random.arrayElement(h)}objectValue($){let h=this.objectKey($);return $[h]}multiple($,h=3){return Array.from({length:h},$)}maybe($,h=0.5){return this.random.boolean(h)?$():void 0}unique($,h=50){let A=new Set,G=0;while(G<h){let J=$();if(!A.has(J))return A.add(J),J;G++}throw Error(`Failed to generate unique value after ${h} retries`)}replaceCreditCardSymbols($="####-####-####-####",h="#"){return this.random.replaceCreditCardSymbols($,h)}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,(h,A)=>{return""})}}class LA{random;constructor($){this.random=$}url($){let h=$?.width??640,A=$?.height??480;return`https://via.placeholder.com/${h}x${A}`}avatar(){return`https://i.pravatar.cc/${this.random.int(100,500)}`}urlLoremFlickr($){let h=$?.width??640,A=$?.height??480,G=$?.category??"";if(G)return`https://loremflickr.com/${h}/${A}/${G}`;return`https://loremflickr.com/${h}/${A}`}urlPicsumPhotos($){let h=$?.width??640,A=$?.height??480,G=`https://picsum.photos/${h}/${A}`;if($?.grayscale)G+="?grayscale";if($?.blur)G+=$?.grayscale?`&blur=${$.blur}`:`?blur=${$.blur}`;return G}dataUri($){let h=$?.width??640,A=$?.height??480,G=$?.color??this.random.int(0,16777215).toString(16).padStart(6,"0"),J=`<svg xmlns="http://www.w3.org/2000/svg" width="${h}" height="${A}"><rect width="${h}" height="${A}" fill="#${G}"/></svg>`;return`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(J)}`}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 Fh{random;locale;domainWordsCache=null;constructor($,h){this.random=$,this.locale=h}getDomainWords(){if(!this.domainWordsCache){let $=this.locale.company.name??["company","tech","digital"];this.domainWordsCache=$.map((h)=>h.toLowerCase().replace(/[^a-z0-9]/g,"")).filter((h)=>h.length>0)}return this.domainWordsCache}email($){let h;if($?.firstName)h=$.firstName.toLowerCase();else{let E=this.locale.person.firstNameMale.length,Y=this.locale.person.firstNameFemale.length,U=this.locale.person.firstNameNeutral?.length||0,z=E+Y+U,W=this.random.int(0,z-1);if(W<E)h=this.locale.person.firstNameMale[W].toLowerCase();else if(W<E+Y)h=this.locale.person.firstNameFemale[W-E].toLowerCase();else h=this.locale.person.firstNameNeutral[W-E-Y].toLowerCase()}let A=$?.lastName??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),G=$?.provider??this.random.arrayElement(this.locale.internet.domainSuffix??["com","net","org"]),J=this.random.arrayElement(u6),H=this.random.arrayElement(this.getDomainWords());return`${h}${J}${A}@${H}.${G}`}safeEmail(){return this.email({provider:this.random.arrayElement(["example.com","example.org","example.net"])})}freeEmail(){let $=this.locale.person.firstNameMale.length,h=this.locale.person.firstNameFemale.length,A=this.locale.person.firstNameNeutral?.length||0,G=$+h+A,J=this.random.int(0,G-1),H;if(J<$)H=this.locale.person.firstNameMale[J].toLowerCase();else if(J<$+h)H=this.locale.person.firstNameFemale[J-$].toLowerCase();else H=this.locale.person.firstNameNeutral[J-$-h].toLowerCase();let E=this.random.arrayElement(this.locale.person.lastName).toLowerCase(),Y=this.random.arrayElement(this.locale.internet.freeEmail??["gmail.com","yahoo.com","hotmail.com"]),U=[".","_",""],z=this.random.arrayElement(U);return`${H}${z}${E}@${Y}`}username($){let h;if($?.firstName)h=$.firstName.toLowerCase();else{let J=this.locale.person.firstNameMale.length,H=this.locale.person.firstNameFemale.length,E=this.locale.person.firstNameNeutral?.length||0,Y=J+H+E,U=this.random.int(0,Y-1);if(U<J)h=this.locale.person.firstNameMale[U].toLowerCase();else if(U<J+H)h=this.locale.person.firstNameFemale[U-J].toLowerCase();else h=this.locale.person.firstNameNeutral[U-J-H].toLowerCase()}let A=$?.lastName?.toLowerCase()??this.random.arrayElement(this.locale.person.lastName).toLowerCase(),G=[`${h}${A}`,`${h}_${A}`,`${h}.${A}`,`${h}${this.random.int(10,999)}`,`${h}_${A}${this.random.int(10,99)}`];return this.random.arrayElement(G)}password($){let h=$?.length??12,A=$?.memorable??!1,G=$?.prefix??"";if(A){let E=[...this.locale.person.firstNameMale,...this.locale.person.firstNameFemale,...this.locale.person.firstNameNeutral||[]],Y=[];for(let U=0;U<3;U++)Y.push(this.random.arrayElement(E));return G+Y.join("-")+this.random.int(10,999)}let J="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*",H=G;for(let E=G.length;E<h;E++)H+=J[this.random.int(0,J.length-1)];return H}url($){let h=$?.protocol??this.random.arrayElement(["http","https"]),A=$?.domain??this.domainName();return`${h}://${A}`}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 h=0;h<8;h++)$.push(this.random.int(0,65535).toString(16).padStart(4,"0"));return $.join(":")}mac($=":"){let h=[];for(let A=0;A<6;A++)h.push(this.random.int(0,255).toString(16).padStart(2,"0").toUpperCase());return h.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 h=[];for(let A=0;A<$;A++)h.push(this.random.arrayElement(this.locale.company.buzzwords??["innovation","technology","solution"]));return h.join("-").toLowerCase()}ip(){return this.ipv4()}}class FA{random;constructor($){this.random=$}word(){return this.random.arrayElement(i6)}words($=3){let h=[];for(let A=0;A<$;A++)h.push(this.word());return h.join(" ")}sentence($){let h=$??this.random.int(3,10),A=this.words(h);return`${A.charAt(0).toUpperCase()+A.slice(1)}.`}sentences($=3,h=" "){let A=[];for(let G=0;G<$;G++)A.push(this.sentence());return A.join(h)}paragraph($){let h=$??this.random.int(3,7);return this.sentences(h)}paragraphs($=3,h=`
|
|
469
|
-
|
|
470
|
-
`){let A=[];for(let G=0;G<$;G++)A.push(this.paragraph());return A.join(h)}text($){let h=$??200,A="";while(A.length<h)A+=`${this.paragraph()} `;return A.trim().slice(0,h)}slug($=3){return this.words($).replace(/ /g,"-")}lines($=3){let h=[];for(let A=0;A<$;A++)h.push(this.sentence());return h.join(`
|
|
471
|
-
`)}}class Rh{random;locale;constructor($,h){this.random=$,this.locale=h}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(),h=this.random.arrayElement(["maj","min","maj7","min7","7","dim","aug","sus4","sus2"]);return`${$}${h}`}tempo(){return this.random.int(60,200)}key(){let $=this.note(),h=this.random.arrayElement(["Major","Minor"]);return`${$} ${h}`}timeSignature(){let $=["4/4","3/4","6/8","5/4","7/8","2/4","9/8","12/8"];return this.random.arrayElement($)}}class RA{random;constructor($){this.random=$}int($){let h=$?.min??0,A=$?.max??100;return this.random.int(h,A)}float($){let h=$?.min??0,A=$?.max??1,G=$?.precision??2;return this.random.float(h,A,G)}bigInt($){let h=$?.min??0n,A=($?.max??1000000n)-h+1n,G=BigInt(Math.floor(this.random.number()*Number(A)));return h+G}binary($){let h=$?.length??8,A="";for(let G=0;G<h;G++)A+=this.random.int(0,1);return A}octal($){let h=$?.length??3,A="";for(let G=0;G<h;G++)A+=this.random.int(0,7);return A}hex($){let h=$?.length??6,A="0123456789ABCDEF",G="";for(let J=0;J<h;J++)G+="0123456789ABCDEF"[this.random.int(0,15)];return G}randomNumber($){return this.int($)}randomDigit(){return this.int({min:0,max:9})}randomDigitNotZero(){return this.int({min:1,max:9})}}class wh{random;locale;constructor($,h){this.random=$,this.locale=h}firstName($){if($?.gender==="male")return this.firstNameMale();if($?.gender==="female")return this.firstNameFemale();if($?.gender==="neutral")return this.firstNameNeutral();let h=this.locale.person.firstNameMale.length,A=this.locale.person.firstNameFemale.length,G=this.locale.person.firstNameNeutral?.length||0,J=h+A+G,H=this.random.int(0,J-1);if(H<h)return this.locale.person.firstNameMale[H];if(H<h+A)return this.locale.person.firstNameFemale[H-h];return this.locale.person.firstNameNeutral[H-h-A]}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 h=this.firstName({gender:$.gender}),A=this.lastName();if($.prefix&&$.suffix)return`${this.prefix()} ${h} ${A} ${this.suffix()}`;if($.prefix)return`${this.prefix()} ${h} ${A}`;if($.suffix)return`${h} ${A} ${this.suffix()}`;return`${h} ${A}`}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 h;if($?.constraints)h=this.firstName({gender:$.constraints.gender});else h=this.firstName({gender:$?.gender});if($?.weighted)h=Bh(this.random,$.weighted);if($?.relationships)h=o$({firstName:h,gender:$?.gender||$?.constraints?.gender},$.relationships).firstName||h;if($?.validation){let A=Kh(h,$.validation);if(!A.isValid){if($.validation.strict)throw Error(`Validation failed: ${A.errors.join(", ")}`);h=this.firstName({gender:$?.gender||$?.constraints?.gender})}}return h}fullNameAdvanced($){let h;if($?.constraints)h=this.fullName({gender:$.constraints.gender,prefix:$.prefix,suffix:$.suffix});else h=this.fullName($);if($?.weighted)h=Bh(this.random,$.weighted);if($?.relationships)h=o$({fullName:h,gender:$?.gender||$?.constraints?.gender},$.relationships).fullName||h;if($?.validation){let A=Kh(h,$.validation);if(!A.isValid){if($.validation.strict)throw Error(`Validation failed: ${A.errors.join(", ")}`);h=this.fullName({gender:$?.gender||$?.constraints?.gender,prefix:$?.prefix,suffix:$?.suffix})}}return h}profile($){let h=$?.constraints?.gender||$?.gender||this.gender(),A=this.firstNameAdvanced({...$,gender:h}),G=this.lastName(),J=`${A} ${G}`,H={firstName:A,lastName:G,fullName:J,gender:h,jobTitle:this.jobTitle(),age:$?.constraints?.ageRange?this.random.int($.constraints.ageRange.min,$.constraints.ageRange.max):this.random.int(18,80)};if($?.relationships)return o$(H,$.relationships);return H}family($){let h=$?.size||this.random.int(2,6),A=this.lastName(),G=["parent","parent","child","child","child","grandparent"],J=[];for(let H=0;H<h;H++){let E=G[H]||"relative",Y=E==="parent"||E==="grandparent"?this.random.weightedBoolean(0.6)?"male":"female":this.random.boolean()?"male":"female",U=this.firstNameAdvanced({...$,gender:Y,constraints:{...$?.constraints,gender:Y}});J.push({firstName:U,lastName:A,fullName:`${U} ${A}`,gender:Y,relationship:E})}return{members:J,lastName:A}}}class _h{random;locale;constructor($,h){this.random=$,this.locale=h}number($){let h=$??this.random.arrayElement(this.locale.phone.formats??["###-###-####"]);return this.random.replaceSymbols(h)}phoneNumber($){return this.number($)}}class Oh{random;locale;constructor($,h){this.random=$,this.locale=h}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 h=["A","T","C","G"],A="";for(let G=0;G<$;G++)A+=this.random.arrayElement(h);return A}rnaSequence($=12){let h=["A","U","C","G"],A="";for(let G=0;G<$;G++)A+=this.random.arrayElement(h);return A}hypothesis(){let $=["temperature increases","pressure decreases","concentration rises","pH changes","light intensity increases","surface area increases","catalyst is added"],h=["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(h)}`}}class Dh{random;locale;constructor($,h){this.random=$,this.locale=h}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 wA{random;constructor($){this.random=$}uuid(){if(!this.random.isSeeded()&&typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();let $="0123456789abcdef",h="";for(let A=0;A<36;A++)if(A===8||A===13||A===18||A===23)h+="-";else if(A===14)h+="4";else if(A===19){let G=this.random.int(0,15);h+=$[G&3|8]}else h+=$[this.random.int(0,15)];return h}nanoid($=21){let h="";for(let A=0;A<$;A++)h+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"[this.random.int(0,63)];return h}alpha($){let h=$?.length??10,A=$?.casing??"mixed",G="abcdefghijklmnopqrstuvwxyz",J="ABCDEFGHIJKLMNOPQRSTUVWXYZ",H="";if(A==="lower")H="abcdefghijklmnopqrstuvwxyz";else if(A==="upper")H="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else H="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let E="";for(let Y=0;Y<h;Y++)E+=H[this.random.int(0,H.length-1)];return E}alphanumeric($){let h=$?.length??10,A=$?.casing??"mixed",G="abcdefghijklmnopqrstuvwxyz",J="ABCDEFGHIJKLMNOPQRSTUVWXYZ",H="0123456789",E="0123456789";if(A==="lower")E+="abcdefghijklmnopqrstuvwxyz";else if(A==="upper")E+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";else E+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let Y="";for(let U=0;U<h;U++)Y+=E[this.random.int(0,E.length-1)];return Y}numeric($=10){if(!this.random.isSeeded()){let A="";for(let G=0;G<$;G++)A+=Math.floor(Math.random()*10);return A}let h="";for(let A=0;A<$;A++)h+=this.random.int(0,9);return h}sample($=10){return this.alphanumeric({length:$})}symbol($=5){let h="";for(let A=0;A<$;A++)h+="!@#$%^&*()_+-=[]{}|;:,.<>?"[this.random.int(0,25)];return h}hexadecimal($){let h=$?.length??6,A=$?.prefix??"",G="0123456789abcdef",J=A;for(let H=0;H<h;H++)J+="0123456789abcdef"[this.random.int(0,15)];return J}}class Vh{random;locale;constructor($,h){this.random=$,this.locale=h}fileName($){let h;if(this.locale?.system?.fileName)h=this.locale.system.fileName;else h=["document","report","presentation","spreadsheet","image","video","audio","backup","archive","data","config","settings","log","cache","temp","index","main","app","script","style","layout","component","module"];let A=this.random.arrayElement(h),G=$?.extension??this.fileExtension();return`${A}.${G}`}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),h=this.random.int(0,20),A=this.random.int(0,50);return`${$}.${h}.${A}`}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),h=this.random.boolean(0.5)?"*":this.random.int(0,23),A=this.random.boolean(0.5)?"*":this.random.int(1,31),G=this.random.boolean(0.5)?"*":this.random.int(1,12),J=this.random.boolean(0.5)?"*":this.random.int(0,6);return`${$} ${h} ${A} ${G} ${J}`}}class Mh{random;locale;constructor($,h){this.random=$,this.locale=h}manufacturer(){if(this.locale?.vehicle?.manufacturer)return this.random.arrayElement(this.locale.vehicle.manufacturer);return this.random.arrayElement(s6)}model(){if(this.locale?.vehicle?.model)return this.random.arrayElement(this.locale.vehicle.model);return this.random.arrayElement(r6)}type(){if(this.locale?.vehicle?.type)return this.random.arrayElement(this.locale.vehicle.type);return this.random.arrayElement(l6)}fuel(){if(this.locale?.vehicle?.fuel)return this.random.arrayElement(this.locale.vehicle.fuel);return this.random.arrayElement(o6)}color(){if(this.locale?.commerce?.color)return this.random.arrayElement(this.locale.commerce.color);return this.random.arrayElement(t6)}vin(){let $="";for(let h=0;h<17;h++)$+="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),h=this.manufacturer(),A=this.model();return`${$} ${h} ${A}`}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 Sh{random;locale;constructor($,h){this.random=$,this.locale=h}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"],h=this.random.arrayElement($);return this[h]()}words($=3){let h=[];for(let A=0;A<$;A++)h.push(this.sample());return h.join(" ")}}class _A{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,h=100){return Math.floor(this.number()*(h-$+1))+$}float($=0,h=1,A=2){let G=this.number()*(h-$)+$;return Number.parseFloat(G.toFixed(A))}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($,h){if($.length===0)return[];let A=h??this.int(1,$.length);return[...$].sort(()=>this.number()-0.5).slice(0,Math.min(A,$.length))}shuffle($){let h=[...$];for(let A=h.length-1;A>0;A--){let G=this.int(0,A);[h[A],h[G]]=[h[G],h[A]]}return h}boolean($=0.5){return this.number()<$}replaceSymbols($){if(this.seed===void 0){let h="";for(let A=0;A<$.length;A++){let G=$[A];if(G==="#")h+="0123456789"[Math.floor(Math.random()*10)];else if(G==="?")h+=VY[Math.floor(Math.random()*26)];else h+=G}return h}return $.replace(/[#?]/g,(h)=>{if(h==="#")return String(this.int(0,9));return this.arrayElement(VY)})}replaceCreditCardSymbols($="####-####-####-####",h="#"){return $.replace(new RegExp(h,"g"),()=>String(this.int(0,9)))}weightedArrayElement($){if($.length===0)throw Error("Cannot pick from empty weighted items array");let h=$.reduce((J,H)=>J+H.weight,0);if(h<=0)throw Error("Total weight must be greater than 0");let A=this.number()*h,G=0;for(let J of $)if(G+=J.weight,A<=G)return J.item;return $[$.length-1].item}weightedArrayElements($,h,A=!1){if($.length===0)return[];let G=h??this.int(1,$.length),J=[],H=[...$];for(let E=0;E<G&&H.length>0;E++){let Y=this.weightedArrayElement(H);if(J.push(Y),!A){let U=H.findIndex((z)=>z.item===Y);if(U!==-1)H.splice(U,1)}}return J}weightedBoolean($=0.5){return this.number()<$}weightedInt($,h,A){let G=h-$+1;if(A){if(A.length!==G)throw Error("Weights array length must match the range size");let J=A.map((H,E)=>({item:$+E,weight:H}));return this.weightedArrayElement(J)}return this.int($,h)}}class VA{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 h=$?.locale??"en",A=$?.seed;if(this._autoInstallLocales=$?.autoInstallLocales??!1,h!=="en"&&!U$.isCached(h))console.warn(`[ts-mocker] Locale '${h}' requires async loading. Use 'await Faker.create({ locale: "${h}" })' for better performance. Falling back to English.`),this._locale=U$.loadSync("en");else this._locale=U$.loadSync(h);this.random=new _A(A),this.person=new wh(this.random,this._locale),this.address=new Uh(this.random,this._locale),this.internet=new Fh(this.random,this._locale),this.phone=new _h(this.random,this._locale),this.company=new Xh(this.random,this._locale),this.lorem=new FA(this.random),this.date=new WA(this.random),this.number=new RA(this.random),this.string=new wA(this.random),this.color=new Wh(this.random,this._locale),this.finance=new ZA(this.random),this.helpers=new jA(this.random),this.image=new LA(this.random),this.git=new XA(this.random),this.science=new Oh(this.random,this._locale),this.music=new Rh(this.random,this._locale),this.database=new zA(this.random),this.food=new jh(this.random,this._locale),this.commerce=new Zh(this.random,this._locale),this.book=new zh(this.random,this._locale),this.animal=new Yh(this.random,this._locale),this.sport=new Dh(this.random,this._locale),this.hacker=new Lh(this.random,this._locale),this.system=new Vh(this.random,this._locale),this.word=new Sh(this.random,this._locale),this.vehicle=new Mh(this.random,this._locale)}static async create($){let h=$?.locale??"en";return await U$.load(h),new VA($)}seed($){return this.random=new _A($),Object.assign(this.person,new wh(this.random,this._locale)),Object.assign(this.address,new Uh(this.random,this._locale)),Object.assign(this.internet,new Fh(this.random,this._locale)),Object.assign(this.phone,new _h(this.random,this._locale)),Object.assign(this.company,new Xh(this.random,this._locale)),Object.assign(this.lorem,new FA(this.random)),Object.assign(this.date,new WA(this.random)),Object.assign(this.number,new RA(this.random)),Object.assign(this.string,new wA(this.random)),Object.assign(this.color,new Wh(this.random,this._locale)),Object.assign(this.finance,new ZA(this.random)),Object.assign(this.helpers,new jA(this.random)),Object.assign(this.image,new LA(this.random)),Object.assign(this.git,new XA(this.random)),Object.assign(this.science,new Oh(this.random,this._locale)),Object.assign(this.music,new Rh(this.random,this._locale)),Object.assign(this.database,new zA(this.random)),Object.assign(this.food,new jh(this.random,this._locale)),Object.assign(this.commerce,new Zh(this.random,this._locale)),Object.assign(this.book,new zh(this.random,this._locale)),Object.assign(this.animal,new Yh(this.random,this._locale)),Object.assign(this.sport,new Dh(this.random,this._locale)),Object.assign(this.hacker,new Lh(this.random,this._locale)),Object.assign(this.system,new Vh(this.random,this._locale)),Object.assign(this.word,new Sh(this.random,this._locale)),Object.assign(this.vehicle,new Mh(this.random,this._locale)),this}async setLocale($){return this._locale=await U$.load($),this.reinitializeLocaleModules(),this}setLocaleSync($){if(!U$.isCached($)&&$!=="en")return console.warn(`[ts-mocker] Locale '${$}' is not loaded. Use 'await faker.setLocale("${$}")' or preload it first.`),this;return this._locale=U$.loadSync($),this.reinitializeLocaleModules(),this}async preloadLocales($){return await U$.preload($),this}reinitializeLocaleModules(){Object.assign(this.person,new wh(this.random,this._locale)),Object.assign(this.address,new Uh(this.random,this._locale)),Object.assign(this.internet,new Fh(this.random,this._locale)),Object.assign(this.phone,new _h(this.random,this._locale)),Object.assign(this.company,new Xh(this.random,this._locale)),Object.assign(this.food,new jh(this.random,this._locale)),Object.assign(this.animal,new Yh(this.random,this._locale)),Object.assign(this.sport,new Dh(this.random,this._locale)),Object.assign(this.music,new Rh(this.random,this._locale)),Object.assign(this.commerce,new Zh(this.random,this._locale)),Object.assign(this.book,new zh(this.random,this._locale)),Object.assign(this.vehicle,new Mh(this.random,this._locale)),Object.assign(this.word,new Sh(this.random,this._locale)),Object.assign(this.hacker,new Lh(this.random,this._locale)),Object.assign(this.system,new Vh(this.random,this._locale)),Object.assign(this.color,new Wh(this.random,this._locale)),Object.assign(this.science,new Oh(this.random,this._locale))}get locale(){return this._locale.title}static get availableLocales(){return U$.getAvailableLocales()}static isLocaleLoaded($){return U$.isCached($)}static async preloadLocales($){await U$.preload($)}name(){return this.person.name()}email(){return this.internet.email()}}var e7,$6=($)=>$,A6=($,h)=>{for(var A in h)e7($,A,{get:h[A],enumerable:!0,configurable:!0,set:h6.bind(h,A)})},t$=($,h)=>()=>($&&(h=$($=0)),h),G6,Qh,OA,MY,DA,FY,qH,EA,z6,n0,w0,W6,RY,Z6,wY,X6,j6,xH,L6,_Y,OY,F6,fH,R6,w6,_6,O6,D6,oG,QY,V6,M6,S6="0.15.9",Q6=()=>{},X$,aG,UA,bH,cH,eG,mH,dH,YA,pH,nH,X1,Ch,BY,TY,lH,kY,yY,qY,O$,l$,xY,fY,v6,c6=()=>{},gY,vY,GJ,gH=null,eH,lG,B$,JA,U$,nY,uY,iY,sY,u6,i6,s6,r6,l6,o6,t6,VY,AE,rY;var lY=a(()=>{e7=Object.defineProperty;G6=import.meta.require;DA=t$(()=>{Qh=new iH,OA=new sH,MY={createKey:J6,isEquivalent:H6,estimateMemoryUsage:E6}});M6=t$(()=>{FY=tG.env.CLARITY_LOG_DIR||q7(U6(),"logs"),qH={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},EA={...qH},z6=(async()=>{try{let{loadConfig:$}=await Promise.resolve().then(()=>(vY(),gY)),h=await $({name:"clarity",alias:"logging",defaultConfig:qH,cwd:tG.cwd()});if(h)Object.assign(EA,h)}catch{}return EA})(),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"},w0=n0,W6=n0.red,RY=n0.green,Z6=n0.yellow,wY=n0.blue,X6=n0.magenta,j6=n0.cyan,xH=n0.white,L6=n0.gray,_Y=n0.bgRed,OY=n0.bgYellow,F6=n0.bgGray,fH=n0.bold,R6=n0.dim,w6=n0.italic,_6=n0.underline,O6=n0.strikethrough,D6=n0.reset,oG={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QY={debug:"\uD83D\uDD0D",info:wY("\u2139"),success:RY("\u2713"),warning:OY(xH(fH(" WARN "))),error:_Y(xH(fH(" ERROR ")))},V6=new $J("stacks")});Ch=t$(()=>{X$=class extends Error{timestamp;context;constructor($,h={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=h,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(([h,A])=>`${h}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},aG=class extends X${code="CONFIG_NOT_FOUND";constructor($,h,A){let G=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],J="";if(G.length===1)J=` or alias "${G[0]}"`;else if(G.length>1)J=` or aliases ${G.map((H)=>`"${H}"`).join(", ")}`;super(`Configuration "${$}"${J} not found`,{configName:$,alias:A,searchPaths:h,searchPathCount:h.length})}},UA=class extends X${code="CONFIG_LOAD_ERROR";constructor($,h,A){super(`Failed to load configuration from "${$}": ${h.message}`,{configPath:$,configName:A,originalError:h.name,originalMessage:h.message});this.cause=h}},bH=class extends X${code="CONFIG_VALIDATION_ERROR";constructor($,h,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:h,errorCount:h.length})}},cH=class extends X${code="CONFIG_MERGE_ERROR";constructor($,h,A,G){super(`Failed to merge configuration from "${$}" with "${h}": ${A.message}`,{sourcePath:$,targetPath:h,configName:G,originalError:A.name,originalMessage:A.message});this.cause=A}},eG=class extends X${code="ENV_VAR_ERROR";constructor($,h,A,G){super(`Failed to parse environment variable "${$}" with value "${h}" as ${A}`,{envKey:$,envValue:h,expectedType:A,configName:G})}},mH=class extends X${code="FILE_SYSTEM_ERROR";constructor($,h,A){super(`File system ${$} failed for "${h}": ${A.message}`,{operation:$,path:h,originalError:A.name,originalMessage:A.message});this.cause=A}},dH=class extends X${code="TYPE_GENERATION_ERROR";constructor($,h,A){super(`Failed to generate types from "${$}" to "${h}": ${A.message}`,{configDir:$,outputPath:h,originalError:A.name,originalMessage:A.message});this.cause=A}},YA=class extends X${code="SCHEMA_VALIDATION_ERROR";constructor($,h,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:h,errorCount:h.length})}},pH=class extends X${code="BROWSER_CONFIG_ERROR";constructor($,h,A,G){super(`Failed to fetch configuration from "${$}": ${h} ${A}`,{endpoint:$,status:h,statusText:A,configName:G})}},nH=class extends X${code="PLUGIN_ERROR";constructor($,h,A){super(`Plugin "${$}" failed during ${h}: ${A.message}`,{pluginName:$,operation:h,originalError:A.name,originalMessage:A.message});this.cause=A}},X1={configNotFound($,h,A){return new aG($,h,A)},configLoad($,h,A){return new UA($,h,A)},configValidation($,h,A){return new bH($,h,A)},configMerge($,h,A,G){return new cH($,h,A,G)},envVar($,h,A,G){return new eG($,h,A,G)},fileSystem($,h,A){return new mH($,h,A)},typeGeneration($,h,A){return new dH($,h,A)},schemaValidation($,h,A){return new YA($,h,A)},browserConfig($,h,A,G){return new pH($,h,A,G)},plugin($,h,A){return new nH($,h,A)}}});BY=t$(()=>{DA(),Ch()});lH=t$(()=>{TY={replace:"replace",concat:"concat",smart:"smart"}});kY=t$(()=>{DA(),Ch(),lH()});qY=t$(()=>{DA(),Ch(),yY=/^https?:\/\//});v6=t$(()=>{M6(),Q6(),DA(),Ch(),BY(),kY(),qY(),lH(),O$=new $J("bunfig",{showTags:!0}),l$=new tH,xY=G$(P1.cwd(),"config"),fY=G$(P1.cwd(),"src/generated")});gY={};A6(gY,{withErrorRecovery:()=>CY,tryLoadConfig:()=>x6,loadConfigWithResult:()=>y6,loadConfig:()=>aH,isRetryableError:()=>K6,isConfigNotFoundError:()=>C6,isBunfigError:()=>KY,globalPerformanceMonitor:()=>OA,globalCache:()=>Qh,getEnvOrDefault:()=>B6,generateConfigTypes:()=>f6,defaultGeneratedDir:()=>fY,defaultConfigDir:()=>xY,deepMergeWithArrayStrategy:()=>rH,deepMerge:()=>IY,createLibraryConfig:()=>g6,config:()=>q6,bunfigPlugin:()=>b6,applyEnvVarsToConfig:()=>HA,TypeGenerationError:()=>dH,SchemaValidationError:()=>YA,PluginError:()=>nH,PerformanceMonitor:()=>sH,FileSystemError:()=>mH,ErrorFactory:()=>X1,EnvVarError:()=>eG,EnvProcessor:()=>hJ,ConfigValidator:()=>oH,ConfigValidationError:()=>bH,ConfigNotFoundError:()=>aG,ConfigMergeError:()=>cH,ConfigLoader:()=>tH,ConfigLoadError:()=>UA,ConfigFileLoader:()=>AJ,ConfigCache:()=>iH,CacheUtils:()=>MY,BunfigError:()=>X$,BrowserConfigError:()=>pH,ArrayMergeStrategies:()=>TY});vY=t$(()=>{v6(),Ch(),DA(),Ch(),c6(),BY(),kY(),qY(),lH()});vY();GJ={verbose:!1,locale:"en",autoInstallLocales:!1};eH=GJ,lG={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"]}};B$=new Map,JA=new Map;U$=class U${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 h=Eh($).normalized;if(h==="en"){if(!B$.has("en"))B$.set("en",lG);return lG}if(B$.has(h))return B$.get(h);if(JA.has(h))return JA.get(h);let A=this.loadLocaleWithFallback(h);JA.set(h,A);try{let G=await A;return B$.set(h,G),G}finally{JA.delete(h)}}static loadSync($){let h=Eh($).normalized;if(h==="en"){if(!B$.has("en"))B$.set("en",lG);return lG}if(B$.has(h))return B$.get(h);throw Error(`Locale '${$}' is not loaded. Please use async loading with faker.setLocale('${$}') or preload it.`)}static isCached($){let h=Eh($).normalized;return B$.has(h)}static async preload($){await Promise.all($.map((h)=>this.load(h)))}static clearCache(){B$.clear(),JA.clear()}static async loadLocaleWithFallback($){let h=m6($);for(let A=0;A<h.length;A++){let G=h[A],J=A===0&&h.length>1,H=!J;try{if(J){let E=await this.loadLocaleModule(G),Y=h[1];try{let U=await this.loadLocaleModule(Y);return cY(U,E)}catch{return E}}else return await this.loadLocaleModule(G)}catch(E){if(A===h.length-1)throw E;continue}}throw Error(`Failed to load locale '${$}' with fallback chain: ${h.join(" \u2192 ")}`)}static async tryWorkspaceImport($,h){if(!I1())return null;try{let A=await import(`../../${h.packageName}/dist/index.js`);return A[h.normalized]||A[h.language]||A.default}catch{try{let A=y7.cwd(),G=k7(A,"packages",h.packageName,"dist","index.js");if(!T7(G))return null;let J=await import(`file://${G}`);return J[h.normalized]||J[h.language]||J.default}catch{return null}}}static async loadLocaleModule($){let h=d6($),A=Eh($);try{let G=await import(h);return G[A.normalized]||G[A.language]||G.default}catch(G){let J=G instanceof Error?G.message:String(G);if(J.includes("Cannot find")||J.includes("not found")||J.includes("ModuleNotFound")){if(I1()&&h.startsWith("@mock-locale/")){let H=await this.tryWorkspaceImport($,A);if(H)return H}if(eH.autoInstallLocales)if(console.log(`
|
|
472
|
-
\uD83D\uDD0D Locale '${$}' not found. Auto-installing ${h}...`),hE(h)){if(I1()&&h.startsWith("@mock-locale/")){let H=await this.tryWorkspaceImport($,A);if(H)return H}try{let H=await import(h);return H[A.normalized]||H[A.language]||H.default}catch(H){if(I1()&&h.startsWith("@mock-locale/")){let E=await this.tryWorkspaceImport($,A);if(E)return E;throw Error(`Locale '${$}' workspace package is not properly built or linked. Please ensure the package is built with 'bun run build' in the ${h.replace("@mock-locale/","packages/")} directory.`)}throw Error(`Failed to load locale '${$}' after installation: ${H instanceof Error?H.message:String(H)}`)}}else throw Error(`Failed to auto-install locale '${$}'. Please install manually with: bun add ${h}`);throw Error(`Locale '${$}' is not installed. Install it with: bun add ${h}
|
|
473
|
-
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}
|
|
474
|
-
Or enable auto-install in your mock.config.ts: { autoInstallLocales: true }`)}throw Error(`Failed to load locale '${$}': ${J}`)}}};nY=new JJ,uY={email:($)=>{return/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test($)},phone:($)=>{let h=/^\+?[1-9]\d{0,15}$/,A=$.replace(/[\s\-()]/g,"");return A.length>=7&&h.test(A)},name:($)=>{return/^[a-z\s\-']+$/i.test($)&&$.length>=2&&$.length<=50},age:($)=>{return Number.isInteger($)&&$>=0&&$<=150},url:($)=>{try{let h=new URL($);return $.startsWith("http://")||$.startsWith("https://")}catch{return!1}},regex:($)=>(h)=>{return $.test(h)},length:($,h)=>(A)=>{return A.length>=$&&A.length<=h},range:($,h)=>(A)=>{return A>=$&&A<=h}},iY={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"]}}},sY={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}]}};u6=[".","_","-",""];i6=["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"];s6=["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"],r6=["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"],l6=["Sedan","SUV","Truck","Coupe","Convertible","Hatchback","Wagon","Van","Minivan","Crossover","Sports Car","Luxury","Electric","Hybrid","Diesel","Compact"],o6=["Gasoline","Diesel","Electric","Hybrid","Plug-in Hybrid","Hydrogen","Ethanol","Biodiesel","CNG","LPG"],t6=["Black","White","Silver","Gray","Red","Blue","Green","Yellow","Orange","Brown","Gold","Purple","Pink","Beige","Tan","Navy","Maroon","Teal","Burgundy","Charcoal"];VY="abcdefghijklmnopqrstuvwxyz".split("");AE=new VA,rY=AE});var oY={};jJ(oY,{validateData:()=>Kh,selectWeightedItem:()=>Bh,isInWorkspace:()=>I1,installPackage:()=>hE,globalProviderRegistry:()=>nY,getConfig:()=>bY,generateRealisticData:()=>pY,faker:()=>AE,detectPackageManager:()=>$E,defaultConfig:()=>GJ,default:()=>rY,config:()=>eH,applyRelationships:()=>o$,applyConstraints:()=>dY,WordModule:()=>Sh,WeightedSelections:()=>sY,VehicleModule:()=>Mh,ValidationRules:()=>uY,SystemModule:()=>Vh,StringModule:()=>wA,SportModule:()=>Dh,ScienceModule:()=>Oh,Random:()=>_A,PhoneModule:()=>_h,PersonModule:()=>wh,NumberModule:()=>RA,MusicModule:()=>Rh,LoremModule:()=>FA,LocaleLoader:()=>U$,InternetModule:()=>Fh,ImageModule:()=>LA,HelpersModule:()=>jA,HackerModule:()=>Lh,GitModule:()=>XA,FoodModule:()=>jh,FinanceModule:()=>ZA,Faker:()=>VA,DateModule:()=>WA,DatabaseModule:()=>zA,DataRelationships:()=>iY,DataProviderRegistry:()=>JJ,CompanyModule:()=>Xh,CommerceModule:()=>Zh,ColorModule:()=>Wh,BookModule:()=>zh,AnimalModule:()=>Yh,AddressModule:()=>Uh});var tY=a(()=>{lY()});import{Database as UE}from"bun:sqlite";function k1(){let $=new Date().toISOString();return G0(v.dialect)?$.slice(0,19).replace("T"," "):$}function a$($,h){if(typeof $!=="string"||$.length===0)throw TypeError(`[bun-query-builder] ${h}: identifier must be a non-empty string, got ${typeof $}`);if($.length>64)throw TypeError(`[bun-query-builder] ${h}: identifier '${$}' exceeds 64 chars`);if(!H8.test($))throw TypeError(`[bun-query-builder] ${h}: identifier '${$}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function E8($,h){if(typeof $!=="string"||$.length===0)throw TypeError(`[bun-query-builder] ${h}: identifier must be a non-empty string, got ${typeof $}`);let A=$.split(".");if(A.length>2||A.some((G)=>G.length===0||G.length>64||!H8.test(G)))throw TypeError(`[bun-query-builder] ${h}: invalid ORDER BY column '${$}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function a6($,h){zE.set($,h),Ih.clear()}function U8(){zE.clear(),Ih.clear()}function j$($){if(!HJ)try{HJ=(QA(),zz(j8)).getModel}catch{HJ=()=>{return}}return HJ($)??zE.get($)}function aY($){let h=EJ.get($);if(h!==void 0)return h;let A=0,G=$.replace(/\?/g,()=>`$${++A}`);if(EJ.size>=e6)EJ.clear();return EJ.set($,G),G}function eY($){if($==null)return 0;if(typeof $.affectedRows==="number")return $.affectedRows;if(typeof $.count==="number")return $.count;if(Array.isArray($))return $.length;return 0}function $8($){if($==null||typeof $!=="object")return null;if("insertId"in $&&$.insertId!=null)return $.insertId;if("lastInsertRowid"in $&&$.lastInsertRowid!=null)return $.lastInsertRowid;return null}class YE{sqliteDb;dialect="sqlite";constructor($){this.sqliteDb=$}all($,h){return Promise.resolve(this.sqliteDb.query($).all(...h))}get($,h){return Promise.resolve(this.sqliteDb.query($).get(...h)??void 0)}run($,h){let A=this.sqliteDb.run($,h);return Promise.resolve({changes:A.changes,lastInsertId:A.lastInsertRowid})}insert($,h){return this.run($,h)}}class Y8{dialect;constructor($){this.dialect=$}conn(){return E1()}text($){return this.dialect==="postgres"?aY($):$}async all($,h){let A=await this.conn().unsafe(this.text($),h);return Array.isArray(A)?A:[]}async get($,h){let A=await this.conn().unsafe(this.text($),h);if(Array.isArray(A))return A[0]??void 0;return A??void 0}async run($,h){let A=await this.conn().unsafe(this.text($),h);return{changes:eY(A),lastInsertId:$8(A)}}async insert($,h,A){if(this.dialect==="postgres"){let H=await this.conn().unsafe(`${aY($)} RETURNING ${A}`,h),E=Array.isArray(H)?H[0]:H;return{changes:1,lastInsertId:E?E[A]??null:null}}let G=await this.conn().unsafe($,h),J=$8(G);if(J==null){let H=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);J=(Array.isArray(H)?H[0]:H)?.id??null}return{changes:eY(G)||1,lastInsertId:J}}}function K_($){if($.database instanceof UE)T1=$.database;else T1=new UE($.database||":memory:",{create:!0}),uh(T1);e$=null,SA=null}function Q0(){if(T1){if(!e$||SA!==T1)e$=new YE(T1),SA=T1,GE="sqlite",JE=null;return e$}let $=v.dialect,h=v.database?.database??null;if(e$&&SA===null&&GE===$&&JE===h)return e$;if(SA=null,GE=$,JE=h,$==="sqlite"){let A=new UE(h||":memory:",{create:!0});uh(A),e$=new YE(A)}else e$=new Y8($);return e$}function B_(){let $=Q0();if($.sqliteDb)return $.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${$.dialect}'. Use the async model API instead.`)}function Ph($){let h=$.traits;return Boolean(h?.useSoftDeletes||h?.softDeletable)}function y1($){let h=$.traits;return Boolean(h?.useTimestamps||h?.timestampable)}function $X($){let h=h8.get($);if(h)return h;let A=new Set,G=$.belongsToMany;if(G){if(Array.isArray(G)){for(let J of G)if(typeof J==="string")A.add(J.toLowerCase());else if(J&&typeof J==="object"&&J.model)A.add(J.model.toLowerCase())}else if(typeof G==="object")for(let J of Object.keys(G))A.add(J)}return h8.set($,A),A}function z8($){let h={};for(let[A,G]of Object.entries($))h[C0(A)]=G;return h}function hX($){for(let h in $)if(C0(h)!==h)return z8($);return $}function AX($,h){if($[h])return $[h];let A=C0(h);if($[A])return $[A];for(let G of Object.keys($))if(C0(G)===A)return $[G];return}class Y${_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_relations={};constructor($,h={}){this._definition=$,this._attributes=hX({...h}),this._original=null;let A=$X($);if(A.size===0)return;let G=this;return new Proxy(this,{get(J,H,E){if(typeof H==="string"&&A.has(H)&&!(H in J))return()=>{let Y=W8($,H);if(!Y||Y.type!=="belongsToMany")throw Error(`[orm] relation '${H}' did not resolve to a belongsToMany on '${$.name}'`);let U=j$(Y.relatedModelName),z=U?.getDefinition?.()||U?.definition;if(!z)throw Error(`[orm] related model '${Y.relatedModelName}' is not registered`);return new Z8(G,$,Y,z)};return Reflect.get(J,H,E)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get($){let h=this._definition.get?.[$];if(h)try{let A=h(this._attributes);if(A!==void 0)return A}catch{}return this._attributes[C0($)]}getAttribute($){return this._attributes[C0($)]}getAttributes(){return{...this._attributes}}set($,h){if(this._original===null)this._original={...this._attributes};this._attributes[C0($)]=h}only($){let h={};for(let A of $)h[A]=this._attributes[C0(A)];return h}except($){let h=new Set($.map((G)=>C0(G))),A={};for(let G of Object.keys(this._attributes))if(!h.has(G))A[G]=this._attributes[G];return A}getRelation($){return this._relations[$]}setRelation($,h){this._relations[$]=h}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($){let h=C0($);return this._attributes[h]!==this._original[h]}return Object.keys(this._attributes).some((h)=>this._attributes[h]!==this._original[h])}isClean($){return!this.isDirty($)}getOriginal($){return this.getOriginalAttributes()[C0($)]}getChanges(){if(this._original===null)return{};let $={};for(let h of Object.keys(this._attributes))if(this._attributes[h]!==this._original[h])$[h]=this._attributes[h];return $}fill($){let h=this._definition.attributes;for(let[A,G]of Object.entries($)){let J=AX(h,A),H=!J&&C0(A).endsWith("_id");if(J?.fillable&&!J?.guarded||H){if(this._original===null)this._original={...this._attributes};this._attributes[C0(A)]=G}}return this}forceFill($){if(this._original===null)this._original={...this._attributes};let h=z8($);Object.assign(this._attributes,h);for(let A of Object.keys(h))this._forced.add(A);return this}async save(){let $=Q0(),h=this._definition.primaryKey||"id",A=this._definition.hooks,G=this._definition.set||{};for(let[J,H]of Object.entries(G))if(this.isDirty(J))this._attributes[C0(J)]=H(this._attributes);if(this._attributes[h]){await A?.beforeUpdate?.(this,this.getChanges());let J=this.getChanges(),H=Object.keys(J);if(H.length>0){let E=H.map((U)=>`${U} = ?`).join(", "),Y=[...Object.values(J),this._attributes[h]];if(y1(this._definition)){let U=k1();await $.run(`UPDATE ${this._definition.table} SET ${E}, updated_at = ? WHERE ${h} = ?`,[...Object.values(J),U,this._attributes[h]])}else await $.run(`UPDATE ${this._definition.table} SET ${E} WHERE ${h} = ?`,Y)}await A?.afterUpdate?.(this)}else{let J=this._definition.attributes,H={};for(let[z,W]of Object.entries(J)){if(W.guarded&&!this._forced.has(C0(z)))continue;let Z=C0(z);if(this._attributes[Z]!==void 0)H[Z]=this._attributes[Z]}for(let z of Object.keys(this._attributes))if(z.endsWith("_id")&&z!==h&&!(z in H))H[z]=this._attributes[z];if(y1(this._definition)){let z=k1();H.created_at=z,H.updated_at=z}if(this._definition.traits?.useUuid&&!H.uuid)H.uuid=crypto.randomUUID();await A?.beforeCreate?.(H);let E=Object.keys(H),Y=E.map(()=>"?").join(", "),U=await $.insert(`INSERT INTO ${this._definition.table} (${E.join(", ")}) VALUES (${Y})`,Object.values(H),h);for(let[z,W]of Object.entries(H))this._attributes[z]=W;if(U.lastInsertId!=null)this._attributes[h]=U.lastInsertId;await A?.afterCreate?.(this)}return this._original={...this._attributes},this._hasSaved=!0,this}async update($){return this.fill($),this.save()}async fresh(){let $=Q0(),h=this._definition.primaryKey||"id",A=this._attributes[h];if(A==null)return null;let G=await $.get(`SELECT * FROM ${this._definition.table} WHERE ${h} = ?`,[A]);if(!G)return null;return new Y$(this._definition,G)}async delete(){let $=Q0(),h=this._definition.primaryKey||"id",A=this._attributes[h],G=this._definition.hooks;if(!A)throw Error("Cannot delete a model without a primary key");if(await G?.beforeDelete?.(this),Ph(this._definition)){let J=k1();await $.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${h} = ?`,[J,A]),this._attributes[j1]=J}else await $.run(`DELETE FROM ${this._definition.table} WHERE ${h} = ?`,[A]);return await G?.afterDelete?.(this),!0}async restore(){if(!Ph(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let $=this._definition.primaryKey||"id",h=this._attributes[$];if(!h)throw Error("Cannot restore a model without a primary key");return await Q0().run(`UPDATE ${this._definition.table} SET ${j1} = ? WHERE ${$} = ?`,[null,h]),this._attributes[j1]=null,this._original=null,this}trashed(){return this._attributes[j1]!=null}async refresh(){let $=Q0(),h=this._definition.primaryKey||"id",A=this._attributes[h];if(!A)throw Error("Cannot refresh a model without a primary key");let G=await $.get(`SELECT * FROM ${this._definition.table} WHERE ${h} = ?`,[A]);if(!G)return null;return this._attributes=G,this._original=null,this}replicate(){let $=this._definition.primaryKey||"id",h={...this._attributes};return delete h[$],delete h.uuid,delete h.created_at,delete h.updated_at,new Y$(this._definition,h)}toArray(){let $={...this._attributes};for(let[h,A]of Object.entries(this._relations))if(Array.isArray(A))$[h]=A.map((G)=>G.toArray());else if(A)$[h]=A.toArray();else $[h]=null;return $}toJSON(){let $=new Set;for(let[A,G]of Object.entries(this._definition.attributes))if(G.hidden)$.add(A);let h={};for(let[A,G]of Object.entries(this._attributes))if(!$.has(A))h[A]=G;for(let[A,G]of Object.entries(this._relations))if(Array.isArray(G))h[A]=G.map((J)=>J.toJSON());else if(G)h[A]=G.toJSON();else h[A]=null;return h}}function I$($){return C0($)}function C0($){let h=A8.get($);if(h!==void 0)return h;return h=$.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),A8.set($,h),h}function N1($){let h=G8.get($);if(h!==void 0)return h;return h=ZH($),G8.set($,h),h}function J8($,h){let A=$[h];if(!A)return[];if(Array.isArray(A))return A.map((G)=>typeof G==="string"?G:String(G?.model??"")).filter(Boolean);if(typeof A==="object")return Object.keys(A);if(typeof A==="string")return[A];return[]}function HX($,h){let A=$.name??$.table??"model",J=JX.filter((E)=>J8($,E).some((Y)=>Y.toLowerCase()===h.toLowerCase())).filter((E)=>!UJ.includes(E));if(J.length>0)return`[orm] '${A}' declares '${h}' as ${J.join("/")}, which eager loading does not support yet. Supported kinds: ${UJ.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let H=UJ.flatMap((E)=>J8($,E));return H.length>0?`[orm] '${A}' has no relation '${h}'. Available: ${H.join(", ")}.`:`[orm] '${A}' has no relation '${h}' \u2014 it declares no relations at all.`}function W8($,h){let{name:A,table:G}=$,J=$.primaryKey||"id";function H(j){if(!j)return null;if(Array.isArray(j)){for(let O of j){let _=typeof O==="string"?O:O?.model||"";if(_&&_.toLowerCase()===h.toLowerCase())return _}return null}if(typeof j==="object"){for(let[O,_]of Object.entries(j))if(O===h||O.toLowerCase()===h.toLowerCase())return typeof _==="string"?_:_?.model||_?.target||O}return null}function E(){let j=$.belongsTo;if(!j)return null;let O=h.toLowerCase(),_=(R)=>{if(typeof R==="string")return{model:R};if(R&&typeof R==="object"&&typeof R.model==="string")return{model:R.model,foreignKey:R.foreignKey};return null};if(Array.isArray(j)){for(let R of j){let S=_(R);if(S&&S.model.toLowerCase()===O)return S}return null}if(typeof j==="object"){for(let[R,S]of Object.entries(j))if(R===h||R.toLowerCase()===O)return _(S)}return null}function Y(){let j=$.belongsToMany;if(!j)return null;if(Array.isArray(j)){for(let O of j)if(typeof O==="string"){if(O.toLowerCase()===h.toLowerCase())return{entry:O}}else if(O&&typeof O==="object"&&O.model){if(O.model.toLowerCase()===h.toLowerCase())return{entry:O}}return null}if(typeof j==="object"){for(let[O,_]of Object.entries(j))if(O===h||O.toLowerCase()===h.toLowerCase())return{entry:_}}return null}let U=H($.hasMany);if(U){let O=j$(U)?.getTable?.()||N1(U),_=C0(A)+"_id";return{type:"hasMany",relatedModelName:U,relatedTable:O,foreignKey:_,localKey:J}}let z=H($.hasOne);if(z){let O=j$(z)?.getTable?.()||N1(z),_=C0(A)+"_id";return{type:"hasOne",relatedModelName:z,relatedTable:O,foreignKey:_,localKey:J}}let W=E();if(W){let j=W.model,O=j$(j),_=O?.getTable?.()||N1(j),R=O?.getDefinition?.()?.primaryKey||"id",S=W.foreignKey||`${C0(j)}_id`;return{type:"belongsTo",relatedModelName:j,relatedTable:_,foreignKey:S,localKey:R}}let Z=Y();if(Z){let j=typeof Z.entry==="object",O=j?Z.entry.model:Z.entry,R=j$(O)?.getTable?.()||N1(O),S=j?Z.entry:null,D,y;if(S?.table)D=S.table;else if(S?.through){y=S.through;let Q=j$(S.through);if(!Q)throw Error(`[orm] belongsToMany relation '${h}' on '${A}' references unknown through model '${S.through}'. Make sure '${S.through}' is registered.`);D=Q.getTable?.()||Q.getDefinition?.()?.table||N1(S.through)}else{let Q=MA(G),N=MA(R);D=[Q,N].sort().join("_")}let P=S?.foreignKey||`${MA(G)}_id`,T=S?.relatedKey||`${MA(R)}_id`,C=[];if(S?.pivot?.columns)for(let Q of Object.keys(S.pivot.columns))C.push(Q);if(y){let Q=j$(y),N=Q?.getDefinition?.()||Q?.definition,K=N?.attributes??{},x=N?.primaryKey??"id";for(let p of Object.keys(K)){if(p===P||p===T||p===x)continue;if(!C.includes(p))C.push(p)}}return{type:"belongsToMany",relatedModelName:O,relatedTable:R,foreignKey:P,localKey:J,pivotTable:D,pivotFkParent:P,pivotFkRelated:T,pivotColumns:C,pivotModelName:y,pivotTimestamps:Boolean(S?.pivot?.timestamps)}}let F=(j,O)=>{if(!j||typeof j!=="object"||Array.isArray(j))return null;let _=j[h]??j[Object.keys(j).find((N)=>N.toLowerCase()===h.toLowerCase())??""];if(!_||typeof _!=="object")return null;let{through:R,target:S}=_;if(!R||!S)return null;let D=j$(R),y=D?.getDefinition?.()||D?.definition,P=D?.getTable?.()||y?.table||N1(R),T=y?.primaryKey||"id",Q=j$(S)?.getTable?.()||N1(S);return{type:O,relatedModelName:S,relatedTable:Q,foreignKey:`${C0(A)}_id`,localKey:J,throughTable:P,throughForeignKey:`${C0(A)}_id`,throughLocalKey:T,targetForeignKey:`${MA(P)}_id`}},w=F($.hasManyThrough,"hasManyThrough");if(w)return w;let B=F($.hasOneThrough,"hasOneThrough");if(B)return B;return null}function EE($,h){let A=new Set;for(let G of $){let J=G.get(h);if(J!=null)A.add(J)}return[...A]}function MA($){return z1(v.relations?.singularizeStrategy)($)}class Z8{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor($,h,A,G){this._parent=$,this._parentDef=h,this._resolved=A,this._relatedDef=G}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($,h,A){if(A===void 0)this._wheres.push({sql:`${this.relatedTable}.${$} = ?`,params:[h]});else this._wheres.push({sql:`${this.relatedTable}.${$} ${String(h)} ?`,params:[A]});return this}wherePivot($,h,A){if(A===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${$} = ?`,params:[h]});else this._pivotWheres.push({sql:`${this.pivotTable}.${$} ${String(h)} ?`,params:[A]});return this}wherePivotIn($,h){if(!h.length)return this;let A=h.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} IN (${A})`,params:[...h]}),this}wherePivotNotIn($,h){if(!h.length)return this;let A=h.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${$} NOT IN (${A})`,params:[...h]}),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($,h="asc"){if(E8($,"orderBy(column)"),h!=="asc"&&h!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${h}'`);return this._orderBy.push(`${$} ${h.toUpperCase()}`),this}limit($){if(!Number.isFinite($)||$<0||!Number.isInteger($))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${$}`);return this._limit=$,this}offset($){if(!Number.isFinite($)||$<0||!Number.isInteger($))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${$}`);return this._offset=$,this}relatedSelectColumns(){let $=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),h=this._relatedDef.traits;if(h?.useTimestamps||h?.timestampable)$.add("created_at"),$.add("updated_at");if(h?.useSoftDeletes||h?.softDeletable)$.add("deleted_at");if(h?.useUuid)$.add("uuid");return[...$]}buildSelect(){let $=[],A=`SELECT ${this.relatedSelectColumns().map((G)=>`${this.relatedTable}.${G} AS ${HE}${G}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;A+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,A+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,$.push(this.parentId);for(let G of this._pivotWheres)A+=` AND ${G.sql}`,$.push(...G.params);for(let G of this._wheres)A+=` AND ${G.sql}`,$.push(...G.params);if(this._orderBy.length>0)A+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)A+=` LIMIT ${this._limit}`;if(this._offset!==void 0)A+=` OFFSET ${this._offset}`;return{sql:A,params:$}}hydrateRows($){let h=this.fkParent,A=this.fkRelated;return $.map((G)=>{let J={},H={};for(let[Y,U]of Object.entries(G))if(Y.startsWith(HE))J[Y.slice(HE.length)]=U;else if(Y!==h&&Y!==A)H[Y]=U;let E=new Y$(this._relatedDef,J);return E.pivot=H,E})}async get(){let $=Q0(),{sql:h,params:A}=this.buildSelect(),G=await $.all(h,A);return this.hydrateRows(G)}async first(){return this._limit=1,(await this.get())[0]}async count(){let $=Q0(),h=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,A=[this.parentId];for(let J of this._pivotWheres)h+=` AND ${J.sql}`,A.push(...J.params);let G=await $.get(h,A);return Number(G?.count??0)}async exists(){return await this.count()>0}now(){return k1()}async attach($,h={}){let A=Q0(),G=Array.isArray($)?$:[$];if(G.length===0)return 0;let J=this._resolved.pivotTimestamps?this.now():null,H=0;for(let E of G){let Y={[this.fkParent]:this.parentId,[this.fkRelated]:E,...h};if(J){if(Y.created_at===void 0)Y.created_at=J;if(Y.updated_at===void 0)Y.updated_at=J}let U=Object.keys(Y),z=U.map(()=>"?").join(", "),W=`INSERT INTO ${this.pivotTable} (${U.join(", ")}) VALUES (${z})`,Z=U.map((F)=>Y[F]);await A.run(W,Z),H++}return H}async detach($){let h=Q0(),A=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,G=[this.parentId];if($!==void 0&&$!==null){let J=Array.isArray($)?$:[$];if(J.length===0)return 0;let H=J.map(()=>"?").join(", ");A+=` AND ${this.fkRelated} IN (${H})`,G.push(...J)}return(await h.run(A,G)).changes}async updateExistingPivot($,h){let A=Q0(),G={...h};if(this._resolved.pivotTimestamps&&G.updated_at===void 0)G.updated_at=this.now();let J=Object.keys(G);if(J.length===0)return 0;let H=J.map((U)=>`${U} = ?`).join(", "),E=`UPDATE ${this.pivotTable} SET ${H} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,Y=[...J.map((U)=>G[U]),this.parentId,$];return(await A.run(E,Y)).changes}async sync($){let h=Q0(),A=new Map;for(let z of $)if(z!=null&&typeof z==="object"&&"id"in z){let{id:W,...Z}=z;A.set(W,Z)}else A.set(z,{});let G=await h.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),J=new Set(G.map((z)=>z[this.fkRelated])),H=[],E=[],Y=[],U=[...J].filter((z)=>!A.has(z));if(U.length>0)await this.detach(U),E.push(...U);for(let[z,W]of A)if(!J.has(z))await this.attach(z,W),H.push(z);else if(Object.keys(W).length>0)await this.updateExistingPivot(z,W),Y.push(z);return{attached:H,detached:E,updated:Y}}async toggle($){let h=Q0(),A=Array.isArray($)?$:[$];if(A.length===0)return{attached:[],detached:[]};let G=A.map(()=>"?").join(", "),J=await h.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${G})`,[this.parentId,...A]),H=new Set(J.map((U)=>U[this.fkRelated])),E=A.filter((U)=>!H.has(U)),Y=A.filter((U)=>H.has(U));if(E.length>0)await this.attach(E);if(Y.length>0)await this.detach(Y);return{attached:E,detached:Y}}}class z0{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor($){this._definition=$}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where($,h,A){if(A===void 0)this._wheres.push({column:$,operator:"=",value:h,boolean:"and"});else this._wheres.push({column:$,operator:h,value:A,boolean:"and"});return this}orWhere($,h,A){if(A===void 0)this._wheres.push({column:$,operator:"=",value:h,boolean:"or"});else this._wheres.push({column:$,operator:h,value:A,boolean:"or"});return this}whereIn($,h){return this._wheres.push({column:$,operator:"in",value:h,boolean:"and"}),this}orWhereIn($,h){return this._wheres.push({column:$,operator:"in",value:h,boolean:"or"}),this}whereNotIn($,h){return this._wheres.push({column:$,operator:"not in",value:h,boolean:"and"}),this}orWhereNotIn($,h){return this._wheres.push({column:$,operator:"not in",value:h,boolean:"or"}),this}whereNull($){return a$($,"whereNull(column)"),this._wheres.push({column:$,operator:"=",value:null,boolean:"and"}),this}orWhereNull($){return a$($,"orWhereNull(column)"),this._wheres.push({column:$,operator:"=",value:null,boolean:"or"}),this}whereNotNull($){return a$($,"whereNotNull(column)"),this._wheres.push({column:$,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull($){return a$($,"orWhereNotNull(column)"),this._wheres.push({column:$,operator:"!=",value:null,boolean:"or"}),this}whereLike($,h){return this._wheres.push({column:$,operator:"like",value:h,boolean:"and"}),this}orWhereLike($,h){return this._wheres.push({column:$,operator:"like",value:h,boolean:"or"}),this}whereNotLike($,h){return this._wheres.push({column:$,operator:"not like",value:h,boolean:"and"}),this}orWhereNotLike($,h){return this._wheres.push({column:$,operator:"not like",value:h,boolean:"or"}),this}whereRaw($,...h){return this._wheres.push({raw:$,rawParams:h,boolean:"and"}),this}orWhereRaw($,...h){return this._wheres.push({raw:$,rawParams:h,boolean:"or"}),this}whereGroup($){return this._addGroup("and",$)}orWhereGroup($){return this._addGroup("or",$)}_addGroup($,h){let A=new z0(this._definition);if(h(A),A._wheres.length===0)return this;let G=[],J=A.buildWhereClauses(G);if(!J)return this;return this._wheres.push({raw:`(${J})`,rawParams:G,boolean:$}),this}whereBetween($,h){return a$($,"whereBetween(column)"),this._wheres.push({column:$,operator:">=",value:h[0],boolean:"and"}),this._wheres.push({column:$,operator:"<=",value:h[1],boolean:"and"}),this}whereNotBetween($,h){a$($,"whereNotBetween(column)");let A=I$($);return this._wheres.push({raw:`(${A} < ? OR ${A} > ?)`,rawParams:[h[0],h[1]],boolean:"and"}),this}when($,h){if($)return h(this);return this}orderBy($,h="asc"){if(E8($,"orderBy(column)"),h!=="asc"&&h!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${h}'`);return this._orderBy.push({column:$,direction:h}),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(...$){for(let h of $)if(!this._withRelations.includes(h))this._withRelations.push(h);return this}getWithRelations(){return this._withRelations}buildWhereClauses($){let h=[];for(let A of this._wheres){let G;if(A.raw){if(G=A.raw,A.rawParams&&A.rawParams.length>0)$.push(...A.rawParams)}else if(A.value===null){let J=I$(A.column);G=A.operator==="="?`${J} IS NULL`:`${J} IS NOT NULL`}else if(A.operator==="in"||A.operator==="not in"){let J=A.value;G=W$(I$(A.column),J,A.operator==="not in",J.map(()=>"?").join(", ")),$.push(...J)}else G=`${I$(A.column)} ${A.operator} ?`,$.push(A.value);h.push({conn:A.boolean==="or"?"OR":"AND",sql:G})}return C1(h)}softDeleteClause(){if(this._trashed==="include"||!Ph(this._definition))return"";return this._trashed==="only"?`${j1} IS NOT NULL`:`${j1} IS NULL`}assertNoUnappliedClauses($){let h=[];if(this._limit!==void 0)h.push("limit()");if(this._offset!==void 0)h.push("offset()");if(this._orderBy.length>0)h.push("orderBy()");if(h.length>0)throw TypeError(`[orm] ${$}() cannot apply ${h.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere($){let h=this._wheres.length>0?this.buildWhereClauses($):"",A=this.softDeleteClause();if(h&&A)return`(${h}) AND ${A}`;return h||A}buildQuery(){let $=[],A=`SELECT ${this._select.map((J)=>J==="*"?J:I$(J)).join(", ")} FROM ${this._definition.table}`,G=this.composeWhere($);if(G)A+=` WHERE ${G}`;if(this._orderBy.length>0)A+=` ORDER BY ${this._orderBy.map((J)=>`${I$(J.column)} ${J.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)A+=` LIMIT ${this._limit}`;if(this._offset!==void 0)A+=` OFFSET ${this._offset}`;return{sql:A,params:$}}toSql(){return this.buildQuery()}async eagerLoadRelations($){if($.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((h)=>this.eagerLoadRelation(h,$)))}async eagerLoadRelation($,h){let A=Q0(),G=this._definition.primaryKey||"id",J=`${this._definition.name}:${$}`,H=Ih.get(J);if(H===void 0){if(H=W8(this._definition,$),Ih.size>=GX)Ih.clear();Ih.set(J,H)}if(!H)throw Error(HX(this._definition,$));if(H.type==="hasMany"||H.type==="hasOne"){let E=EE(h,G);if(E.length===0)return;let Y=E.map(()=>"?").join(", "),U=await A.all(`SELECT * FROM ${H.relatedTable} WHERE ${H.foreignKey} IN (${Y})`,E),z=j$(H.relatedModelName),W=z?.getDefinition?.()||z?.definition||this._definition;if(H.type==="hasMany"){let Z=new Map;for(let F of U){let w=F[H.foreignKey];if(!Z.has(w))Z.set(w,[]);Z.get(w).push(F)}for(let F of h){let w=Z.get(F.get(G))||[];F.setRelation($,w.map((B)=>new Y$(W,B)))}}else{let Z=new Map;for(let F of U){let w=F[H.foreignKey];if(!Z.has(w))Z.set(w,F)}for(let F of h){let w=Z.get(F.get(G));F.setRelation($,w?new Y$(W,w):null)}}}if(H.type==="belongsTo"){let E=new Set;for(let w of h){let B=w._attributes[H.foreignKey];if(B!=null)E.add(B)}let Y=[...E];if(Y.length===0)return;let U=Y.map(()=>"?").join(", "),z=await A.all(`SELECT * FROM ${H.relatedTable} WHERE ${H.localKey} IN (${U})`,Y),W=j$(H.relatedModelName),Z=W?.getDefinition?.()||W?.definition||this._definition,F=new Map;for(let w of z)F.set(w[H.localKey],w);for(let w of h){let B=w._attributes[H.foreignKey],j=F.get(B);w.setRelation($,j?new Y$(Z,j):null)}}if(H.type==="belongsToMany"){let E=EE(h,G);if(E.length===0)return;if(!H.pivotTable||!H.pivotFkParent||!H.pivotFkRelated)return;let Y=E.map(()=>"?").join(", "),U=await A.all(`SELECT * FROM ${H.pivotTable} WHERE ${H.pivotFkParent} IN (${Y})`,E);if(U.length===0){for(let R of h)R.setRelation($,[]);return}let z=new Set;for(let R of U){let S=R[H.pivotFkRelated];if(S!=null)z.add(S)}let W=[...z],Z=j$(H.relatedModelName),F=Z?.getDefinition?.()||Z?.definition||this._definition,w=F?.primaryKey||"id",B=[];if(W.length>0){let R=W.map(()=>"?").join(", ");B=await A.all(`SELECT * FROM ${H.relatedTable} WHERE ${w} IN (${R})`,W)}let j=new Map;for(let R of B)j.set(R[w],R);let O=new Map;for(let R of U){let S=R[H.pivotFkParent];if(!O.has(S))O.set(S,[]);O.get(S).push(R)}let _=new Set([H.pivotFkParent,H.pivotFkRelated]);for(let R of h){let S=R.get(G),y=(O.get(S)||[]).map((P)=>{let T=j.get(P[H.pivotFkRelated]);if(!T)return null;let C=new Y$(F,T),Q={};for(let[N,K]of Object.entries(P))if(!_.has(N))Q[N]=K;return C.pivot=Q,C}).filter((P)=>P!==null);R.setRelation($,y)}}if(H.type==="hasManyThrough"||H.type==="hasOneThrough"){let E=EE(h,G);if(E.length===0)return;let Y=H.throughLocalKey||"id",U=E.map(()=>"?").join(", "),z=await A.all(`SELECT ${Y}, ${H.throughForeignKey} FROM ${H.throughTable} WHERE ${H.throughForeignKey} IN (${U})`,E);if(z.length===0){for(let _ of h)_.setRelation($,H.type==="hasManyThrough"?[]:null);return}let W=new Map;for(let _ of z)W.set(_[Y],_[H.throughForeignKey]);let Z=[...new Set(z.map((_)=>_[Y]))],F=Z.map(()=>"?").join(", "),w=await A.all(`SELECT * FROM ${H.relatedTable} WHERE ${H.targetForeignKey} IN (${F})`,Z),B=j$(H.relatedModelName),j=B?.getDefinition?.()||B?.definition||this._definition,O=new Map;for(let _ of w){let R=W.get(_[H.targetForeignKey]);if(R==null)continue;if(!O.has(R))O.set(R,[]);O.get(R).push(new Y$(j,_))}for(let _ of h){let R=O.get(_.get(G))||[];_.setRelation($,H.type==="hasManyThrough"?R:R[0]??null)}}}async get(){let $=Q0(),{sql:h,params:A}=this.buildQuery(),J=(await $.all(h,A)).map((H)=>new Y$(this._definition,H));if(this._withRelations.length>0)await this.eagerLoadRelations(J);return J}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let $=await this.first();if(!$)throw Error(`No ${this._definition.name} found`);return $}async last(){let $=this._definition.primaryKey||"id";return this._orderBy=[{column:$,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let $=Q0(),h=[],A=`SELECT COUNT(*) as count FROM ${this._definition.table}`,G=this.composeWhere(h);if(G)A+=` WHERE ${G}`;let J=await $.get(A,h);return Number(J?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let $=await 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]}async increment($,h=1){a$($,"increment(column)"),this.assertNoUnappliedClauses("increment");let A=Q0(),G=[h],J=I$($),H=`UPDATE ${this._definition.table} SET ${J} = ${J} + ?`;if(y1(this._definition))H+=", updated_at = ?",G.push(k1());let E=this.composeWhere(G);if(E)H+=` WHERE ${E}`;return(await A.run(H,G)).changes}decrement($,h=1){return this.increment($,-h)}async chunk($,h){let A=0;while(!0){let G=new z0(this._definition);G._wheres=[...this._wheres],G._orderBy=[...this._orderBy],G._select=[...this._select],G._withRelations=[...this._withRelations],G._trashed=this._trashed,G._limit=$,G._offset=A*$;let J=await G.get();if(J.length===0)break;if(await h(J)===!1)break;if(J.length<$)break;A++}}async paginate($=1,h=15){let A=await this.count(),G=Math.ceil(A/h);this._limit=h,this._offset=($-1)*h;let J=await this.get();return{data:J,total:A,page:$,perPage:h,lastPage:G,hasMorePages:$<G,isEmpty:J.length===0,from:J.length>0?($-1)*h+1:null,to:J.length>0?($-1)*h+J.length:null}}async pluck($){a$($,"pluck(column)");let h=Q0(),A=[],G=I$($),J=`SELECT ${G} FROM ${this._definition.table}`,H=this.composeWhere(A);if(H)J+=` WHERE ${H}`;if(this._orderBy.length>0)J+=` ORDER BY ${this._orderBy.map((Y)=>`${I$(Y.column)} ${Y.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)J+=` LIMIT ${this._limit}`;if(this._offset!==void 0)J+=` OFFSET ${this._offset}`;return(await h.all(J,A)).map((Y)=>Y[G])}async aggregate($,h){a$(h,`${$}(column)`);let A=Q0(),G=[],J=`SELECT ${$}(${I$(h)}) as v FROM ${this._definition.table}`,H=this.composeWhere(G);if(H)J+=` WHERE ${H}`;let Y=(await A.get(J,G))?.v;if(Y==null)return null;if(typeof Y==="string"){let U=Number(Y);return Y.trim()!==""&&!Number.isNaN(U)?U:Y}return Y}max($){return this.aggregate("MAX",$)}min($){return this.aggregate("MIN",$)}async avg($){return Number(await this.aggregate("AVG",$)??0)||0}async sum($){return Number(await this.aggregate("SUM",$)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let $=Q0(),h=[],A=`DELETE FROM ${this._definition.table}`,G=this.composeWhere(h);if(G)A+=` WHERE ${G}`;return(await $.run(A,h)).changes}async update($){this.assertNoUnappliedClauses("update");let h=Q0(),A=Object.entries($),G=A.map(([Y])=>`${I$(Y)} = ?`).join(", "),J=A.map(([,Y])=>Y);if(y1(this._definition))J.push(k1());let H=`UPDATE ${this._definition.table} SET ${G}${y1(this._definition)?", updated_at = ?":""}`,E=this.composeWhere(J);if(E)H+=` WHERE ${E}`;return(await h.run(H,J)).changes}}function EX($){let h={query:()=>new z0($),where(A,G,J){return new z0($).where(A,G,J)},orWhere(A,G,J){return new z0($).orWhere(A,G,J)},whereIn(A,G){return new z0($).whereIn(A,G)},whereNotIn(A,G){return new z0($).whereNotIn(A,G)},whereNull(A){return new z0($).whereNull(A)},whereNotNull(A){return new z0($).whereNotNull(A)},whereLike(A,G){return new z0($).whereLike(A,G)},orderBy(A,G="asc"){return new z0($).orderBy(A,G)},orderByDesc(A){return new z0($).orderByDesc(A)},select(...A){return new z0($).select(...A)},with(...A){return new z0($).with(...A)},limit:(A)=>new z0($).limit(A),take:(A)=>new z0($).take(A),skip:(A)=>new z0($).skip(A),withTrashed:()=>new z0($).withTrashed(),onlyTrashed:()=>new z0($).onlyTrashed(),async find(A){let G=Q0(),J=$.primaryKey||"id",H=Ph($)?` AND ${j1} IS NULL`:"",E=await G.get(`SELECT * FROM ${$.table} WHERE ${J} = ?${H}`,[A]);return E?new Y$($,E):void 0},async findOrFail(A){let G=await h.find(A);if(!G)throw Error(`${$.name} with id ${A} not found`);return G},async findMany(A){let G=Q0(),J=$.primaryKey||"id",H=Ph($)?` AND ${j1} IS NULL`:"";return(await G.all(`SELECT * FROM ${$.table} WHERE ${J} IN (${A.map(()=>"?").join(", ")})${H}`,A)).map((Y)=>new Y$($,Y))},all:()=>new z0($).get(),first:()=>new z0($).first(),firstOrFail:()=>new z0($).firstOrFail(),last:()=>new z0($).last(),count:()=>new z0($).count(),exists:()=>new z0($).exists(),doesntExist:()=>new z0($).doesntExist(),paginate:(A,G)=>new z0($).paginate(A,G),whereBetween(A,G){return new z0($).whereBetween(A,G)},whereNotBetween(A,G){return new z0($).whereNotBetween(A,G)},async create(A){let G=new Y$($,A);return await G.save(),G},async createMany(A){let G=[];for(let J of A)G.push(await this.create(J));return G},async updateOrCreate(A,G){let J=new z0($);for(let[E,Y]of Object.entries(A))J=J.where(E,Y);let H=await J.first();if(H)return await H.update(G),H;return this.create({...A,...G})},async firstOrCreate(A,G){let J=new z0($);for(let[E,Y]of Object.entries(A))J=J.where(E,Y);return await J.first()||this.create({...A,...G})},async destroy(A){let G=Q0(),J=$.primaryKey||"id";return(await G.run(`DELETE FROM ${$.table} WHERE ${J} = ?`,[A])).changes>0},remove(A){return this.destroy(A)},async truncate(){await Q0().run(`DELETE FROM ${$.table}`,[])},getDefinition:()=>$,getTable:()=>$.table,make(A={}){return new Y$($,A)},latest:(A="created_at")=>new z0($).orderByDesc(A),oldest:(A="created_at")=>new z0($).orderBy(A,"asc"),max:(A)=>new z0($).max(A),min:(A)=>new z0($).min(A),avg:(A)=>new z0($).avg(A),sum:(A)=>new z0($).sum(A),pluck(A){return new z0($).pluck(A)}};return new Proxy(h,{get(A,G){if(typeof G==="string"&&G.startsWith("where")&&G.length>5){let J=G.slice(5),H=J.charAt(0).toLowerCase()+J.slice(1);if(H in $.attributes||H==="id"||H===$.primaryKey)return(E)=>new z0($).where(H,E)}return Reflect.get(A,G)}})}function X8($){let h=EX($);if($?.name)a6($.name,h);return h}async function I_($){let h=Q0(),A=C0($.primaryKey||"id"),G=[],J=new Set([A]);if(G.push($.autoIncrement!==!1?`${A} INTEGER PRIMARY KEY AUTOINCREMENT`:`${A} INTEGER PRIMARY KEY`),$.traits?.useUuid)G.push("uuid TEXT UNIQUE"),J.add("uuid");for(let[H,E]of Object.entries($.attributes)){let Y=C0(H);if(J.has(Y))continue;J.add(Y);let U=JU(E.type),z=qG(U);if(Y.endsWith("_id")&&(U===void 0||t1(U)))z="INTEGER";let W=`${Y} ${z}`;if(E.unique)W+=" UNIQUE";if(typeof E.foreignKey==="object"&&E.foreignKey!==null){let Z=E.foreignKey;if(W+=` REFERENCES ${Z.table}(${Z.column??"id"})`,Z.onDelete)W+=` ON DELETE ${Z.onDelete.toUpperCase()}`;if(Z.onUpdate)W+=` ON UPDATE ${Z.onUpdate.toUpperCase()}`}G.push(W)}for(let H of e1($.belongsTo)){let E=H.foreignKey??`${C0(H.model)}_id`;if(J.has(E))continue;J.add(E),G.push(`${E} INTEGER`)}if(y1($))for(let H of["created_at","updated_at"]){if(J.has(H))continue;J.add(H),G.push(`${H} TEXT`)}if(Ph($)&&!J.has("deleted_at"))J.add("deleted_at"),G.push("deleted_at TEXT");await h.run(`CREATE TABLE IF NOT EXISTS ${$.table} (${G.join(", ")})`,[])}async function P_($,h,A){let G=Q0(),J=$.traits?.useSeeder,H=h??(typeof J==="object"&&J?J.count:10);if(!A)try{let E=await Promise.resolve().then(() => (tY(),oY));A=GY(E.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let E=0;E<H;E++){let Y={};for(let[z,W]of Object.entries($.attributes))if(W.factory)Y[C0(z)]=W.factory(A);if(y1($)){let z=k1();Y.created_at=z,Y.updated_at=z}if($.traits?.useUuid)Y.uuid=crypto.randomUUID();let U=Object.keys(Y);await G.run(`INSERT INTO ${$.table} (${U.join(", ")}) VALUES (${U.map(()=>"?").join(", ")})`,Object.values(Y))}}var H8,HJ=null,zE,EJ,e6=500,T1=null,e$=null,SA=null,GE=null,JE=null,j1="deleted_at",HE="__btm_rel__",h8,A8,G8,Ih,GX=1000,UJ,JX;var WE=a(()=>{f0();U1();VG();H8=/^[A-Z_][A-Z0-9_]*$/i;zE=new Map;EJ=new Map;h8=new WeakMap;A8=new Map,G8=new Map,Ih=new Map;UJ=["hasMany","hasOne","belongsTo","belongsToMany"],JX=[...UJ,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"]});var j8={};jJ(j8,{registerModel:()=>ZE,registerBrowserModels:()=>YX,hasModel:()=>w8,getModelRegistry:()=>R8,getModel:()=>L8,getAllModels:()=>F8,defineModel:()=>O8,clearModelRegistry:()=>_8});function L8($){return Nh.get($)}function F8(){return[...Nh.values()]}function R8(){return Object.fromEntries(Nh)}function w8($){return Nh.has($)}function _8(){Nh.clear(),U8()}function ZE($,h){return Nh.set($,h),h}function UX(){return typeof window<"u"&&typeof document<"u"}function O8($){let h;if(UX())h=CE($);else{let A=X8($);h=Object.assign(A,{definition:$,getDefinition:()=>$,getTable:()=>$.table,getName:()=>$.name})}return ZE($.name,h),h}function YX($){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...$}}var Nh;var QA=a(()=>{LJ();WE();Nh=new Map});class L1{driver;client;tableName;indexName;entityType;keyConditions=[];filterConditions=[];projectionAttrs=[];limitValue;scanForward=!0;consistentReadValue=!1;startKey;constructor($){this.driver=V$($.config),this.client=$.client,this.tableName=$.config.tableName??""}table($){return this.tableName=$,this}index($){return this.indexName=$,this}entity($){return this.entityType=$,this}whereKey($,h,A){return this.keyConditions.push({attribute:$,operator:h,value:A}),this}wherePartitionKey($,h){return this.whereKey($,"=",h)}whereSortKey($,h){return this.whereKey($,"=",h)}whereSortKeyBeginsWith($,h){return this.keyConditions.push({attribute:$,operator:"begins_with",value:h}),this}whereSortKeyBetween($,h,A){return this.keyConditions.push({attribute:$,operator:"BETWEEN",values:[h,A]}),this}where($,h,A){return this.filterConditions.push({attribute:$,operator:h,value:A}),this}whereEquals($,h){return this.where($,"=",h)}whereLessThan($,h){return this.where($,"<",h)}whereLessThanOrEqual($,h){return this.where($,"<=",h)}whereGreaterThan($,h){return this.where($,">",h)}whereGreaterThanOrEqual($,h){return this.where($,">=",h)}whereBetween($,h,A){return this.filterConditions.push({attribute:$,operator:"BETWEEN",values:[h,A]}),this}whereBeginsWith($,h){return this.filterConditions.push({attribute:$,operator:"begins_with",value:h}),this}whereContains($,h){return this.where($,"contains",h)}whereExists($){return this.where($,"attribute_exists")}whereNotExists($){return this.where($,"attribute_not_exists")}whereIn($,h){return this.filterConditions.push({attribute:$,operator:"IN",values:h}),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(),h={TableName:$.tableName,ExpressionAttributeNames:{},ExpressionAttributeValues:{}};if($.indexName)h.IndexName=$.indexName;let A=0;if($.keyConditions.length>0){let G=[];for(let J of $.keyConditions){let H=`#key${A}`;if(h.ExpressionAttributeNames[H]=J.attribute,J.operator==="begins_with"){let E=`:keyval${A}`;h.ExpressionAttributeValues[E]=this.driver.marshall({v:J.value}).v,G.push(`begins_with(${H}, ${E})`)}else if(J.operator==="BETWEEN"){let E=`:keyval${A}a`,Y=`:keyval${A}b`;h.ExpressionAttributeValues[E]=this.driver.marshall({v:J.values?.[0]}).v,h.ExpressionAttributeValues[Y]=this.driver.marshall({v:J.values?.[1]}).v,G.push(`${H} BETWEEN ${E} AND ${Y}`)}else{let E=`:keyval${A}`;h.ExpressionAttributeValues[E]=this.driver.marshall({v:J.value}).v,G.push(`${H} ${J.operator} ${E}`)}A++}h.KeyConditionExpression=G.join(" AND ")}if($.filterConditions&&$.filterConditions.length>0){let G=[];for(let J of $.filterConditions){let H=`#flt${A}`;if(h.ExpressionAttributeNames[H]=J.attribute,J.operator==="attribute_exists")G.push(`attribute_exists(${H})`);else if(J.operator==="attribute_not_exists")G.push(`attribute_not_exists(${H})`);else if(J.operator==="begins_with"||J.operator==="contains"){let E=`:fltval${A}`;h.ExpressionAttributeValues[E]=this.driver.marshall({v:J.value}).v,G.push(`${J.operator}(${H}, ${E})`)}else if(J.operator==="BETWEEN"){let E=`:fltval${A}a`,Y=`:fltval${A}b`;h.ExpressionAttributeValues[E]=this.driver.marshall({v:J.values?.[0]}).v,h.ExpressionAttributeValues[Y]=this.driver.marshall({v:J.values?.[1]}).v,G.push(`${H} BETWEEN ${E} AND ${Y}`)}else if(J.operator==="IN"){let E=(J.values??[]).map((Y,U)=>`:fltval${A}_${U}`);J.values?.forEach((Y,U)=>{h.ExpressionAttributeValues[`:fltval${A}_${U}`]=this.driver.marshall({v:Y}).v}),G.push(`${H} IN (${E.join(", ")})`)}else{let E=`:fltval${A}`;h.ExpressionAttributeValues[E]=this.driver.marshall({v:J.value}).v,G.push(`${H} ${J.operator} ${E}`)}A++}h.FilterExpression=G.join(" AND ")}if($.projectionAttributes&&$.projectionAttributes.length>0){let G=[];for(let J of $.projectionAttributes){let H=`#proj${A}`;h.ExpressionAttributeNames[H]=J,G.push(H),A++}h.ProjectionExpression=G.join(", ")}if($.limit!==void 0)h.Limit=$.limit;if($.scanIndexForward!==void 0)h.ScanIndexForward=$.scanIndexForward;if($.exclusiveStartKey)h.ExclusiveStartKey=this.driver.marshall($.exclusiveStartKey);if($.consistentRead)h.ConsistentRead=$.consistentRead;if(Object.keys(h.ExpressionAttributeNames).length===0)delete h.ExpressionAttributeNames;if(Object.keys(h.ExpressionAttributeValues).length===0)delete h.ExpressionAttributeValues;return h}toScanRequest(){let $=this.buildScanParams(),h={TableName:$.tableName};if($.indexName)h.IndexName=$.indexName;if($.filterConditions&&$.filterConditions.length>0){let{expression:A,expressionAttributeNames:G,expressionAttributeValues:J}=this.driver.buildFilterExpression($.filterConditions);h.FilterExpression=A,h.ExpressionAttributeNames=G,h.ExpressionAttributeValues=J}if($.projectionAttributes&&$.projectionAttributes.length>0){let{expression:A,expressionAttributeNames:G}=this.driver.buildProjectionExpression($.projectionAttributes);h.ProjectionExpression=A,h.ExpressionAttributeNames={...h.ExpressionAttributeNames,...G}}if($.limit!==void 0)h.Limit=$.limit;if($.exclusiveStartKey)h.ExclusiveStartKey=this.driver.marshall($.exclusiveStartKey);if($.consistentRead)h.ConsistentRead=$.consistentRead;return h}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(),h=await this.client.query($);return{items:h.Items?.map((A)=>this.driver.unmarshall(A)),count:h.Count,scannedCount:h.ScannedCount,lastEvaluatedKey:h.LastEvaluatedKey?this.driver.unmarshall(h.LastEvaluatedKey):void 0,consumedCapacity:h.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(),h=await this.client.scan($);return{items:h.Items?.map((A)=>this.driver.unmarshall(A)),count:h.Count,scannedCount:h.ScannedCount,lastEvaluatedKey:h.LastEvaluatedKey?this.driver.unmarshall(h.LastEvaluatedKey):void 0,consumedCapacity:h.ConsumedCapacity}}async getAll(){let $=[],h;do{if(h)this.startFrom(h);let A=this.keyConditions.length>0?await this.query():await this.scan();if(A.items)$.push(...A.items);h=A.lastEvaluatedKey}while(h);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 q${driver;client;tableName;itemData={};keyData={};updateExpressions={};conditionExpr;returnValuesOption="NONE";constructor($){this.driver=V$($.config),this.client=$.client,this.tableName=$.config.tableName??""}table($){return this.tableName=$,this}key($){return this.keyData=$,this}item($){return this.itemData=$,this}set($,h){if(!this.updateExpressions.set)this.updateExpressions.set={};return this.updateExpressions.set[$]=h,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($,h){if(!this.updateExpressions.add)this.updateExpressions.add={};return this.updateExpressions.add[$]=h,this}deleteFromSet($,h){if(!this.updateExpressions.delete)this.updateExpressions.delete={};return this.updateExpressions.delete[$]=h,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:h,expressionAttributeNames:A,expressionAttributeValues:G}=this.driver.buildUpdateExpression(this.updateExpressions);if(h)$.UpdateExpression=h,$.ExpressionAttributeNames=A,$.ExpressionAttributeValues=G;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(),h=await this.client.putItem($);if(h.Attributes)return this.driver.unmarshall(h.Attributes);return}async update(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toUpdateRequest(),h=await this.client.updateItem($);if(h.Attributes)return this.driver.unmarshall(h.Attributes);return}async delete(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toDeleteRequest(),h=await this.client.deleteItem($);if(h.Attributes)return this.driver.unmarshall(h.Attributes);return}async get(){if(!this.client)throw Error("DynamoDB client not provided");let $=this.toGetRequest(),h=await this.client.getItem($);if(h.Item)return this.driver.unmarshall(h.Item);return}}function x_($){return new L1($)}function f_($){return new q$($)}function g_($){let h=V$($.config);return{query:()=>new L1($),item:()=>new q$($),driver:h,registerEntity:(A)=>h.registerEntity(A),buildKey:(A,G)=>h.buildPrimaryKey(A,G)}}var YJ=()=>{};class D8{config;entities=new Map;pkAttribute;skAttribute;typeAttribute;constructor($){this.config=$,this.pkAttribute=$.pkAttribute??"pk",this.skAttribute=$.skAttribute??"sk",this.typeAttribute=$.typeAttribute??"_type";for(let h of $.entities)this.entities.set(h.name,h)}getEntity($){return this.entities.get($)}registerEntity($){this.entities.set($.name,$)}buildKey($,h){let A=this.entities.get($);if(!A)throw Error(`Entity not found: ${$}`);let G=this.interpolatePattern(A.pkPattern,h),J=this.interpolatePattern(A.skPattern,h);return{pk:G,sk:J}}buildGSIKey($,h,A){let G=this.entities.get($);if(!G)throw Error(`Entity not found: ${$}`);let J=G.indexes?.find((Y)=>Y.name===h);if(!J)throw Error(`GSI not found: ${h} for entity ${$}`);let H=this.interpolatePattern(J.pkPattern,A),E=J.skPattern?this.interpolatePattern(J.skPattern,A):void 0;return{pk:H,sk:E}}createItem($,h){let{pk:A,sk:G}=this.buildKey($,h),J=this.entities.get($),H={[this.pkAttribute]:A,[this.skAttribute]:G,[this.typeAttribute]:$,...h};if(J.indexes)for(let E of J.indexes){let Y=this.buildGSIKey($,E.name,h),U=this.config.indexes?.find((z)=>z.name===E.name);if(U){if(H[U.pkAttribute]=Y.pk,U.skAttribute&&Y.sk)H[U.skAttribute]=Y.sk}}return H}parseEntityType($){if($[this.typeAttribute])return $[this.typeAttribute];let h=$[this.pkAttribute];if(!h)return;for(let[A,G]of this.entities){let J=G.pkPattern.split("${")[0];if(h.startsWith(J))return A}return}parseItem($){let h=this.parseEntityType($);if(!h)return;let{[this.pkAttribute]:A,[this.skAttribute]:G,[this.typeAttribute]:J,...H}=$;return{type:h,data:H}}getEntityPrefix($){let h=this.entities.get($);if(!h)throw Error(`Entity not found: ${$}`);return h.pkPattern.split("${")[0]}generateTableDefinition(){let $=[{name:this.pkAttribute,type:"S"},{name:this.skAttribute,type:"S"}],h=[];if(this.config.indexes)for(let A of this.config.indexes){if(!$.find((G)=>G.name===A.pkAttribute))$.push({name:A.pkAttribute,type:"S"});if(A.skAttribute&&!$.find((G)=>G.name===A.skAttribute))$.push({name:A.skAttribute,type:"S"});h.push({indexName:A.name,keySchema:{partitionKey:A.pkAttribute,sortKey:A.skAttribute},projection:{type:"ALL"}})}return{tableName:this.config.tableName,keySchema:{partitionKey:this.pkAttribute,sortKey:this.skAttribute},attributeDefinitions:$,globalSecondaryIndexes:h.length>0?h:void 0,billingMode:"PAY_PER_REQUEST"}}interpolatePattern($,h){return $.replace(/\$\{(\w+)\}/g,(A,G)=>{if(!(G in h))throw Error(`Missing value for pattern key: ${G}`);return String(h[G])})}}class V8{manager;entityName;options;constructor($,h,A){this.manager=$,this.entityName=h,this.options=A}async create($){let h=this.manager.createItem(this.entityName,$),A=new q$(this.options).table(this.options.config.tableName).item(h).ifNotExists("pk");if(this.options.client)await A.put();return $}async get($){let{pk:h,sk:A}=this.manager.buildKey(this.entityName,$),G=new q$(this.options).table(this.options.config.tableName).key({pk:h,sk:A});if(!this.options.client)throw Error("DynamoDB client not provided");let J=await G.get();if(!J)return;return this.manager.parseItem(J)?.data}async update($,h){let{pk:A,sk:G}=this.manager.buildKey(this.entityName,$),J=new q$(this.options).table(this.options.config.tableName).key({pk:A,sk:G}).setMany(h).ifExists("pk").returnNew();if(!this.options.client)throw Error("DynamoDB client not provided");let H=await J.update();if(!H)return;return this.manager.parseItem(H)?.data}async delete($){let{pk:h,sk:A}=this.manager.buildKey(this.entityName,$),G=new q$(this.options).table(this.options.config.tableName).key({pk:h,sk:A});if(!this.options.client)throw Error("DynamoDB client not provided");return await G.delete(),!0}query(){return new M8(this.manager,this.entityName,this.options)}async findAll(){let $=this.manager.typeAttribute??"_type",h=new L1(this.options).table(this.options.config.tableName).whereEquals($,this.entityName);if(!this.options.client)throw Error("DynamoDB client not provided");return(await h.getAll()).map((G)=>this.manager.parseItem(G)).filter((G)=>G!==void 0).map((G)=>G.data)}}class M8{manager;entityName;options;builder;pkValue;skConditions=[];constructor($,h,A){this.manager=$,this.entityName=h,this.options=A,this.builder=new L1(A).table(A.config.tableName)}wherePartitionKey($){let{pk:h}=this.manager.buildKey(this.entityName,$);this.pkValue=h;let A=this.manager.pkAttribute??"pk";return this.builder.wherePartitionKey(A,h),this}whereSortKey($){let{sk:h}=this.manager.buildKey(this.entityName,$),A=this.manager.skAttribute??"sk";return this.builder.whereSortKey(A,h),this}whereSortKeyBeginsWith($){let h=this.manager.skAttribute??"sk";return this.builder.whereSortKeyBeginsWith(h,$),this}useIndex($,h){let A=this.manager.buildGSIKey(this.entityName,$,h),G=this.manager.config.indexes?.find((J)=>J.name===$);if(!G)throw Error(`GSI configuration not found: ${$}`);return this.builder.index($),this.builder.wherePartitionKey(G.pkAttribute,A.pk),this}where($,h,A){return this.builder.where($,h,A),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((h)=>this.manager.parseItem(h)).filter((h)=>h!==void 0).map((h)=>h.data)}async first(){return this.limit(1),(await this.execute())[0]}}function S8($){return new D8($)}function Q8($,h,A){return new V8($,h,A)}var c_;var XE=a(()=>{YJ();c_={simpleEntity:($,h="id")=>({name:$,pkPattern:`${$.toUpperCase()}#\${${h}}`,skPattern:"METADATA",keyFields:[h]}),oneToMany:($,h,A="id",G="id")=>({parent:{name:$,pkPattern:`${$.toUpperCase()}#\${${A}}`,skPattern:"METADATA",keyFields:[A]},child:{name:h,pkPattern:`${$.toUpperCase()}#\${${A}}`,skPattern:`${h.toUpperCase()}#\${${G}}`,keyFields:[A,G]}}),manyToMany:($,h,A="id",G="relatedId")=>({entity:{name:$,pkPattern:`${$.toUpperCase()}#\${${A}}`,skPattern:"METADATA",keyFields:[A]},relation:{name:h,pkPattern:`${$.toUpperCase()}#\${${A}}`,skPattern:`${h.toUpperCase()}#\${${G}}`,keyFields:[A,G],indexes:[{name:"GSI1",pkPattern:`${$.toUpperCase()}#\${${G}}`,skPattern:`${h.toUpperCase()}#\${${A}}`}]}}),hierarchical:($,h="rootId",A="path")=>({name:$,pkPattern:`ROOT#\${${h}}`,skPattern:`PATH#\${${A}}`,keyFields:[h,A]})}});function C8($,h){let A={};for(let[G,J]of Object.entries($))if(J)A[G]=J.replace(/\{([^}]+)\}/g,(H,E)=>{return h[E]!==void 0?String(h[E]):`{${E}}`});return A}async function zX($){return{models:new Map}}function d_($){return $}function p_($){return $}function n_($){return $}function u_($){return $}class K8{config;driver;singleTableManager;models=new Map;queryBuilderOptions;constructor($){this.config={pkAttribute:"pk",skAttribute:"sk",entityTypeAttribute:"_et",keyDelimiter:"#",...$};let h={region:$.region,endpoint:$.endpoint,credentials:$.credentials,tableName:$.tableName};this.driver=V$(h);let A={tableName:$.tableName,pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,indexes:this.buildGSIConfig(),entities:[]};this.singleTableManager=S8(A),this.queryBuilderOptions={config:h}}setClient($){return this.queryBuilderOptions.client=$,this}async discoverModels(){if(!this.config.modelsPath)throw Error("modelsPath must be configured to use discoverModels()");let $=await zX({queryBuilder:{modelsPath:this.config.modelsPath},singleTable:{pkAttribute:this.config.pkAttribute,skAttribute:this.config.skAttribute,typeAttribute:this.config.entityTypeAttribute,delimiter:this.config.keyDelimiter}}),h=[];for(let[,A]of $.models)this.registerParsedModel(A),h.push(A);return h}registerModel($){let h=this.parseWithTooling($);return this.registerParsedModel(h)}registerParsedModel($){this.models.set($.name,$);let h=this.toSingleTableEntity($);this.singleTableManager.registerEntity(h);let A=this.toEntityMapping($);return this.driver.registerEntity(A),$}registerModels($){return $.map((h)=>this.registerModel(h))}getModel($){return this.models.get($)}getAllModels(){return Array.from(this.models.values())}repository($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return Q8(this.singleTableManager,$,this.queryBuilderOptions)}query($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return new L1(this.queryBuilderOptions).table(this.config.tableName).entity($)}item($){if(!this.models.get($))throw Error(`Model not found: ${$}`);return new q$(this.queryBuilderOptions).table(this.config.tableName)}buildKey($,h){let A=this.models.get($);if(!A)throw Error(`Model not found: ${$}`);let G=C8(A.keyPatterns,h);return{pk:G.pk,sk:G.sk}}createItem($,h){let A=this.models.get($);if(!A)throw Error(`Model not found: ${$}`);let G=C8(A.keyPatterns,h),J=G.pk,H=G.sk,E={[this.config.pkAttribute]:J,[this.config.skAttribute]:H,[this.config.entityTypeAttribute]:A.name,...h};if(A.hasTimestamps){let Y=new Date().toISOString();if(!E.createdAt)E.createdAt=Y;E.updatedAt=Y}if(A.hasVersioning){if(!E._v)E._v=1}return E}parseItem($){let h=$[this.config.entityTypeAttribute];if(!h)return;let{[this.config.pkAttribute]:A,[this.config.skAttribute]:G,[this.config.entityTypeAttribute]:J,...H}=$;return{type:h,data:H}}getDriver(){return this.driver}getSingleTableManager(){return this.singleTableManager}generateTableDefinition(){return this.singleTableManager.generateTableDefinition()}generateAccessPatterns($){let h=this.models.get($);if(!h)throw Error(`Model not found: ${$}`);return h.accessPatterns}parseWithTooling($){let h=$.name.toUpperCase(),A=$.primaryKey??"id",G=this.config.keyDelimiter,J=this.parseAttributes($),H=this.parseRelationships($,A),E={pk:`${h}${G}{${A}}`,sk:`${h}${G}{${A}}`,...this.deriveGSIKeyPatterns(h,A,G,H)},Y=this.deriveAccessPatterns($.name,h,A,H);return{name:$.name,entityType:h,primaryKey:A,attributes:J,relationships:H,keyPatterns:E,accessPatterns:Y,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 h=[];if(h.push({name:$.primaryKey??"id",fillable:!1,required:!0,nullable:!1,unique:!0,hidden:!1,dynamoDbType:"S"}),$.attributes)for(let[A,G]of Object.entries($.attributes))h.push({name:A,fillable:G.fillable??!0,required:G.required??!1,nullable:G.nullable??!0,unique:G.unique??!1,hidden:G.hidden??!1,defaultValue:G.default,cast:G.cast,dynamoDbType:this.inferDynamoDBType(G)});if($.traits?.useTimestamps)h.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)h.push({name:"deletedAt",fillable:!1,required:!1,nullable:!0,unique:!1,hidden:!1,dynamoDbType:"S"});return h}inferDynamoDBType($){if($.cast){let h=$.cast.toLowerCase();if(["integer","int","float","double","decimal","number"].includes(h))return"N";if(["boolean","bool"].includes(h))return"BOOL";if(["array","list"].includes(h))return"L";if(["object","json","map"].includes(h))return"M"}if($.validation?.rule){let h=String($.validation.rule);if(h.includes("integer")||h.includes("numeric")||h.includes("number"))return"N";if(h.includes("boolean"))return"BOOL";if(h.includes("array"))return"L";if(h.includes("object"))return"M"}return"S"}parseRelationships($,h){let A=[];if($.hasOne)for(let G of $.hasOne)A.push({type:"hasOne",relatedModel:G,foreignKey:`${$.name.toLowerCase()}Id`,localKey:h,requiresGsi:!0});if($.hasMany)for(let G of $.hasMany)A.push({type:"hasMany",relatedModel:G,foreignKey:`${$.name.toLowerCase()}Id`,localKey:h,requiresGsi:!1});if($.belongsTo)for(let G of $.belongsTo)A.push({type:"belongsTo",relatedModel:G,foreignKey:`${G.toLowerCase()}Id`,localKey:h,requiresGsi:!0});if($.belongsToMany){let G=Array.isArray($.belongsToMany)?$.belongsToMany:Object.values($.belongsToMany);for(let J of G){let H=typeof J==="string"?J:J?.model;if(!H)continue;let E=[$.name,H].sort();A.push({type:"belongsToMany",relatedModel:H,foreignKey:`${$.name.toLowerCase()}Id`,localKey:h,pivotEntity:E.join(""),requiresGsi:!0})}}return A}deriveGSIKeyPatterns($,h,A,G){let J={},H=1;for(let E of G)if(E.requiresGsi&&H<=5)J[`gsi${H}pk`]=`${E.relatedModel.toUpperCase()}${A}{${E.foreignKey}}`,J[`gsi${H}sk`]=`${$}${A}{${h}}`,E.gsiIndex=H,H++;return J}deriveAccessPatterns($,h,A,G){let J=[];J.push({name:`Get ${$} by ID`,description:`Retrieve a single ${$} by its primary key`,entityType:h,operation:"get",index:"main",keyCondition:"pk = :pk AND sk = :sk",examplePk:`${h}#123`,exampleSk:`${h}#123`,efficient:!0}),J.push({name:`List all ${$}s`,description:`Scan all ${$} entities`,entityType:h,operation:"scan",index:"scan",keyCondition:"_et = :entityType",examplePk:h,efficient:!1});for(let H of G){if(H.type==="hasMany")J.push({name:`Get ${H.relatedModel}s for ${$}`,description:`Query ${H.relatedModel}s related to a ${$}`,entityType:h,operation:"query",index:"main",keyCondition:"pk = :pk AND begins_with(sk, :skPrefix)",examplePk:`${h}#123`,exampleSk:`${H.relatedModel.toUpperCase()}#`,efficient:!0});if(H.gsiIndex){let E=`GSI${H.gsiIndex}`;J.push({name:`Get ${$}s by ${H.relatedModel}`,description:`Query ${$}s by their related ${H.relatedModel}`,entityType:h,operation:"query",index:E,keyCondition:`gsi${H.gsiIndex}pk = :pk`,examplePk:`${H.relatedModel.toUpperCase()}#123`,efficient:!0})}}return J}toSingleTableEntity($){let h=this.extractKeyFields($.keyPatterns.pk);return{name:$.name,pkPattern:$.keyPatterns.pk,skPattern:$.keyPatterns.sk,keyFields:h,indexes:this.extractGSIPatterns($.keyPatterns)}}extractKeyFields($){let h=$.match(/\{([^}]+)\}/g);if(!h)return[];return h.map((A)=>A.slice(1,-1))}extractGSIPatterns($){let h=[];for(let A=1;A<=5;A++){let G=`gsi${A}pk`,J=`gsi${A}sk`;if($[G])h.push({name:`GSI${A}`,pkPattern:$[G],skPattern:$[J]})}return h.length>0?h:void 0}toEntityMapping($){return{entityType:$.name,pkPattern:$.keyPatterns.pk,skPattern:$.keyPatterns.sk}}buildGSIConfig(){let $=this.config.gsiConfig??{},h=[];if($.gsi1pk)h.push({name:"GSI1",pkAttribute:$.gsi1pk,skAttribute:$.gsi1sk});if($.gsi2pk)h.push({name:"GSI2",pkAttribute:$.gsi2pk,skAttribute:$.gsi2sk});if($.gsi3pk)h.push({name:"GSI3",pkAttribute:$.gsi3pk,skAttribute:$.gsi3sk});return h}}function t_($){return new K8($)}function a_($){return $.accessPatterns}function e_($,h="#"){let A=$.name.toUpperCase(),G=$.primaryKey??"id";return{name:$.name,pkPattern:`${A}${h}\${${G}}`,skPattern:`${A}${h}\${${G}}`}}var B8=a(()=>{YJ();XE()});function PG($){let h={};for(let A of Object.keys($)){let G=$[A],J=G.definition??G.getDefinition?.()??G,H=Y1(J),E=J.attributes??{},Y={};for(let U of Object.keys(E))Y[U]=void 0;h[H]={columns:Y,primaryKey:J.primaryKey??"id"}}return h}var I8=()=>{};import{readdirSync as WX}from"fs";import{basename as P8,extname as N8,isAbsolute as ZX,join as T8}from"path";import XX from"process";function LX($){let h=N8($);if(!jX.has(h))return!1;let A=P8($,h);if(A.startsWith("_")||A==="index")return!1;return!A.endsWith(".d")}function FX($){if(!$||typeof $!=="object")return!1;let h=$;return typeof h.name==="string"||typeof h.table==="string"}function k8($){let h=[],A=WX($,{withFileTypes:!0}).sort((G,J)=>G.name.localeCompare(J.name));for(let G of A){let J=T8($,G.name);if(G.isDirectory()){h.push(...k8(J));continue}if(LX(G.name))h.push(J)}return h}async function C$($){let h=$.cwd??XX.cwd(),A=ZX($.modelsDir)?$.modelsDir:T8(h,$.modelsDir),G={};for(let J of k8(A)){let H=`?t=${Date.now()}-${Math.random().toString(36).slice(2)}`,E=await import(`${J}${H}`),Y=E.default??E,U=Y.definition??Y.getDefinition?.()??Y;if(!FX(U))continue;let z=U.name??P8(J,N8(J));G[z]={...U,name:z}}return G}var jX;var y8=a(()=>{jX=new Set([".ts",".mts",".cts",".js",".mjs",".cjs"])});function q8($){let h={},A={},G={},J={},H={};for(let E of Object.keys($)){let Y=$[E],U=Y.definition??Y.getDefinition?.()??Y,z=Y1(U);h[E]=z,A[z]=E,G[z]=U.primaryKey??"id";let W=(w)=>{if(!w)return{};let B={};if(Array.isArray(w)){for(let j of w){let O=pG(j);if(O)B[O.model]=O.model}return B}if(typeof w==="object"){for(let[j,O]of Object.entries(w)){let _=pG(O);if(_)B[j]=_.model}return B}return{}},Z=(w)=>{if(!w)return{};if(Array.isArray(w)){let B={};for(let j of w)if(typeof j==="string")B[j]=j;else if(j&&typeof j==="object"&&typeof j.model==="string")B[j.model]=j;return B}return w},F=(w)=>{if(!w)return{};return w};if(J[z]={hasOne:W(U.hasOne),hasMany:W(U.hasMany),belongsTo:W(U.belongsTo),belongsToMany:Z(U.belongsToMany),hasOneThrough:F(U.hasOneThrough),hasManyThrough:F(U.hasManyThrough),morphOne:W(U.morphOne),morphMany:W(U.morphMany),morphTo:U.morphTo,morphToMany:W(U.morphToMany),morphedByMany:W(U.morphedByMany)},U.scopes&&typeof U.scopes==="object"){H[z]={};for(let w of Object.keys(U.scopes)){let B=U.scopes[w];if(typeof B==="function")H[z][w]=B}}}return{modelToTable:h,tableToModel:A,primaryKeys:G,relations:J,scopes:H,models:$}}var jE=()=>{};import{existsSync as DE,mkdirSync as RX,readdirSync as wX,readFileSync as _X,writeFileSync as OX}from"fs";import{dirname as x8,join as zJ}from"path";import c8 from"process";function i0($){if(v.verbose)console.log($)}function F1($){return $.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}function LE($){return z1(v.relations?.singularizeStrategy)($)}function CU(){return[...ZJ]}function DX($){let h=$;while(h!==x8(h)){if(DE(zJ(h,"package.json")))return h;h=x8(h)}return c8.cwd()}function VX(){let $=DX(c8.cwd()),h=u$($,v.migrationDir);if(!DE(h))RX(h,{recursive:!0}),i0(`-- Created SQL directory: ${h}`);return h}function KU($){return $.trimStart().startsWith(m8)}function d8($){return $.split(`
|
|
475
|
-
`).filter((h)=>!h.trimStart().startsWith("--")).join(`
|
|
476
|
-
`).replace(/\s+/g," ").trim().replace(/;+$/,"")}function MX($){let h=new Set,A;try{A=wX($).filter((G)=>G.endsWith(".sql"))}catch{return h}for(let G of A)try{h.add(d8(_X(zJ($,G),"utf8")))}catch{}return h}function p8($,h){if(!$)return!1;let A=VX();if(Th===null)Th=MX(A);let G=d8($);if(G.length>0&&Th.has(G))return i0(`-- Migration already in the corpus, not writing it again: ${h}`),!1;KA++;let J=WJ?String(KA).padStart(10,"0"):String(Math.floor(Date.now()/1000)+KA),H=`${J}-${h}.sql`;if(!WJ){let Y=Number(J);while(DE(zJ(A,H)))Y+=1,J=String(Y),H=`${J}-${h}.sql`}let E=zJ(A,H);return OX(E,`${m8}
|
|
477
|
-
${$}`),i0(`-- Migration file created: ${H}`),h1++,ZJ.push(H),Th?.add(G),!0}function SX($,h){return $==="integer"&&h==="bigint"||$==="string"&&h==="text"}function f8($){if($.endsWith("_id"))return"bigint";if($.endsWith("_at"))return"datetime";if($.startsWith("is_")||$.startsWith("has_"))return"boolean";return}function g8($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="bigint"||$ instanceof Date)return $;return}function QX($){if($&&typeof $==="object"&&"name"in $){let h=$;if(h.name==="enum"||h.getRules&&Array.isArray(h.getRules())){if(h.enumValues&&Array.isArray(h.enumValues))return h.enumValues.map((A)=>String(A));if(h._values&&Array.isArray(h._values))return h._values.map((A)=>String(A));if(h.values&&Array.isArray(h.values))return h.values.map((A)=>String(A))}}if($&&typeof $==="object"){let h=$,A=h.allowedValues||h.enumValues||h._values||h.values;if(Array.isArray(A)&&A.length>0)return A.map((G)=>String(G))}return}function RE($){if(!$?.rules||!Array.isArray($.rules))return;for(let h of $.rules)if(h?.name==="max"||h?.name==="maxLength"){if(h.params&&typeof h.params.max==="number")return h.params.max;if(Array.isArray(h.args)&&typeof h.args[0]==="number")return h.args[0];if(typeof h.value==="number")return h.value;if(typeof h.expectedValue==="number")return h.expectedValue}return}function CX($){if(!$||typeof $!=="object")return;let h=$;if(h.name)switch(String(h.name).toLowerCase()){case"string":{let G=RE(h);return G&&G>wE?"text":"string"}case"text":return"text";case"integer":case"int":return"integer";case"bigint":return"bigint";case"float":return"float";case"number":return"integer";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum"}if(h.type){let A=String(h.type).toLowerCase();if(A==="string"||A==="text")return"string";if(A==="integer"||A==="int")return"integer";if(A==="bigint")return"bigint";if(A==="float")return"float";if(A==="number")return"integer";if(A==="boolean")return"boolean";if(A==="date")return"date";if(A==="datetime")return"datetime";if(A==="timestamptz"||A==="timestamp_tz")return"timestamptz";if(A==="json")return"json"}return}function KX($){if(typeof $!=="string")return;switch($.trim().toLowerCase().replace(/[\s-]+/g,"_")){case"varchar":case"string":return"string";case"text":return"text";case"bool":case"boolean":return"boolean";case"int":case"integer":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"number":case"numeric":case"decimal":return"decimal";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamp_tz":case"timestamptz":case"timestamp_with_time_zone":return"timestamptz";case"json":case"jsonb":return"json";case"enum":return"enum";default:return}}function AA($,h){let A=q8($),G=[];for(let Y of Object.keys($)){let U=$[Y],z=Y1(U),W=U.primaryKey??"id",Z=U.autoIncrement!==!1,F=U.attributes??{},w=[],B=[];if(!F[W])w.push({name:F1(W),type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1});let j=new Map,O=e1(U.belongsTo).length>0,_=new Set(Object.keys(F).map((K)=>F1(K))),R=new Set;for(let K of _){if(!K.endsWith("_type"))continue;let x=`${K.slice(0,-5)}_id`;if(_.has(x))R.add(x)}for(let K of e1(U.belongsTo)){let x=K.foreignKey??`${F1(K.model)}_id`,p=A.modelToTable[K.model];if(p)j.set(x,{table:p,onDelete:K.onDelete})}for(let K of Object.keys(F)){let x=F[K],p=F1(K),s=Boolean(x.validation?.rule?.isRequired),o=K===W?!1:x.nullable??!(x.required??s),q,d,u=K===W;if(q=KX(x.type)??CX(x.validation?.rule),q==="string"){let t=RE(x.validation?.rule);if(t&&t>wE)q="text"}if(!q||q==="enum"){let t=QX(x.validation?.rule);if(t&&t.length>0)q="enum",d=t}if(!q)q=f8(p);if(!q){let t=g8(x.default);if(typeof t==="string")q=t.length>255?"text":"string";else if(typeof t==="number")q=Number.isInteger(t)?"integer":"float";else if(typeof t==="boolean")q="boolean";else if(typeof t==="bigint")q="bigint";else if(t instanceof Date)q="datetime"}if(!q)q=u?"bigint":"string";let f=q==="string"?RE(x.validation?.rule):void 0,h0={name:p,type:q,isPrimaryKey:u,isUnique:Boolean(x.unique),isNullable:o,hasDefault:typeof x.default<"u",defaultValue:g8(x.default),enumValues:d,maxLength:typeof f==="number"&&f>0&&f<=wE?f:void 0};if(p.endsWith("_id")&&x.foreignKey!==!1&&!R.has(p))if(typeof x.foreignKey==="object"&&x.foreignKey!==null){let t=x.foreignKey;if(h0.references={table:t.table,column:t.column??"id",onDelete:t.onDelete,onUpdate:t.onUpdate},t.nullable!==void 0)h0.isNullable=t.nullable}else{let t=j.get(p),j0=p.replace(/_id$/,"").replace(/(^|_)([a-z])/g,(A1,V0,L$)=>L$.toUpperCase()),e0=t?.table??(O?void 0:A.modelToTable[j0]);if(e0){let A1=A.primaryKeys[e0]??"id";h0.references={table:e0,column:A1,onDelete:t?.onDelete}}}w.push(h0)}let S=e1(U.belongsTo);for(let K of S){let x=K.foreignKey??`${F1(K.model)}_id`;if(w.some((o)=>o.name===x))continue;let p=A.modelToTable[K.model],s=p?A.primaryKeys[p]??"id":void 0;w.push({name:x,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1,references:p&&s&&!R.has(x)?{table:p,column:s,onDelete:K.onDelete}:void 0})}let D=U.traits;if(D?.useTimestamps??D?.timestampable??!1){if(!w.some((K)=>K.name==="created_at"))w.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1});if(!w.some((K)=>K.name==="updated_at"))w.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(D?.useSoftDeletes??D?.softDeletable??!1){if(!w.some((K)=>K.name==="deleted_at"))w.push({name:"deleted_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1})}if(D?.useUuid??!1){if(!w.some((K)=>K.name==="uuid"))w.push({name:"uuid",type:"string",isPrimaryKey:!1,isUnique:!0,isNullable:!0,hasDefault:!1})}for(let K of U.indexes??[])B.push({name:K.name,columns:K.columns.map((x)=>F1(x)),type:K.unique?"unique":"index",where:K.where});for(let K of w)if(K.isUnique&&!K.isPrimaryKey)B.push({name:`${z}_${K.name}_unique`,columns:[K.name],type:"unique"});let C=Array.isArray(U.shardKey)?U.shardKey.map(F1):void 0,Q=Array.isArray(U.sortKey)?U.sortKey.map(F1):void 0,N=U.tableKind;G.push({table:z,columns:w,indexes:B,shardKey:C,sortKey:Q,tableKind:N})}let J=new Set(G.map((Y)=>Y.table));function H(Y){if(!J.has(Y.table))J.add(Y.table),G.push(Y)}for(let Y of Object.keys($)){let U=$[Y],z=U?.traits??{},W=Y1(U),Z=LE(W);if(z.likeable){let F=typeof z.likeable==="object"?z.likeable:{},w=F.table||`${W}_likes`,B=F.foreignKey||`${Z}_id`;H({table:w,columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"user_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"users",column:"id"}},{name:B,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:W,column:"id"}},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:`${w}_user_target_unique`,columns:["user_id",B],type:"unique"}]})}if(z.taggable)H({table:"taggables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"order",type:"integer",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:0},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggables_target_index",columns:["taggable_id","taggable_type"],type:"index"},{name:"taggables_type_slug_unique",columns:["taggable_type","slug"],type:"unique"}]}),H({table:"taggable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"tag_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"taggables",column:"id"}},{name:"taggable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"taggable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"taggable_models_owner_unique",columns:["tag_id","taggable_id","taggable_type"],type:"unique"},{name:"taggable_models_target_index",columns:["taggable_id","taggable_type"],type:"index"}]});if(z.categorizable)H({table:"categorizables",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"name",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"slug",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"description",type:"text",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1},{name:"is_active",type:"boolean",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:!0},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizables_type_slug_unique",columns:["categorizable_type","slug"],type:"unique"}]}),H({table:"categorizable_models",columns:[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"category_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:{table:"categorizables",column:"id"}},{name:"categorizable_id",type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"categorizable_type",type:"string",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1},{name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1},{name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1}],indexes:[{name:"categorizable_models_owner_unique",columns:["category_id","categorizable_id","categorizable_type"],type:"unique"},{name:"categorizable_models_target_index",columns:["categorizable_id","categorizable_type"],type:"index"}]})}for(let Y of Object.keys($)){let U=$[Y],z=U?.belongsToMany;if(!z||typeof z!=="object"||Array.isArray(z))continue;let W=Y1(U),Z=LE(W);for(let[F,w]of Object.entries(z)){let B=w;if(!B||typeof B!=="object")continue;if(B.through)continue;let j=B.pivot;if(!j||!j.columns&&!j.timestamps&&!j.uniques)continue;let O=B.model,R=$[O]?.table||`${String(O).toLowerCase()}s`,S=LE(R),D=B.table||[Z,S].sort().join("_"),y=B.foreignKey||`${Z}_id`,P=B.relatedKey||`${S}_id`,T=new Set([y,P,...Object.keys(j.columns??{})]),C=new Set;for(let p of T){if(!p.endsWith("_type"))continue;let s=`${p.slice(0,-5)}_id`;if(T.has(s))C.add(s)}let Q=(p,s)=>C.has(p)?void 0:{table:s,column:"id"},N=[{name:"id",type:"bigint",isPrimaryKey:!0,isUnique:!1,isNullable:!1,hasDefault:!1},{name:y,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:Q(y,W)},{name:P,type:"bigint",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!1,references:Q(P,R)}];if(j.columns)for(let[p,s]of Object.entries(j.columns)){let o=s,q=f8(p)??"string";N.push({name:p,type:q,isPrimaryKey:!1,isUnique:!1,isNullable:o?.nullable??!1,hasDefault:o?.default!==void 0,defaultValue:o?.default})}if(j.timestamps)N.push({name:"created_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!1,hasDefault:!0,defaultValue:$1}),N.push({name:"updated_at",type:"datetime",isPrimaryKey:!1,isUnique:!1,isNullable:!0,hasDefault:!1});let K=[],x=j.uniques&&j.uniques.length>0?j.uniques:[[y,P]];for(let p=0;p<x.length;p++){let s=x[p];K.push({name:`${D}_${s.join("_")}_unique${p>0?`_${p}`:""}`,columns:[...s],type:"unique"})}H({table:D,columns:N,indexes:K})}}let E=new Map(G.map((Y)=>[Y.table,Y]));for(let Y of G)for(let U of Y.columns){if(!U.references)continue;let z=E.get(U.references.table)?.columns.find((W)=>W.name===U.references.column);if(!z||U.type===z.type)continue;U.type=z.type,U.maxLength=z.maxLength,U.enumValues=z.enumValues,U.enumTypeName=z.enumTypeName}return{dialect:h.dialect,vitessSharded:h.vitessSharded,tables:G}}function cG($,h={}){KA=0,h1=0,R1=0,ZJ=[],Th=null,WJ=!0;let A=h.dryRun?()=>!1:p8,G=[],J=y$($.dialect,{vitessSharded:$.vitessSharded}),{tables:H,deferredForeignKeys:E}=n8($.tables,$.dialect);for(let[U,z]of H.entries()){let W={...z,columns:z.columns.map((j)=>E.has(kh(z.table,j.name))?{...j,references:void 0}:j)},Z=[],F=new Set;for(let j of W.columns)if(j.type==="enum"&&j.enumValues&&j.enumValues.length>0){let O=`${W.table}_${j.name}_type`;if(j.enumTypeName=O,!F.has(O)){let _=J.createEnumType(O,j.enumValues);if(_)Z.push(_);F.add(O)}}let w=J.createTable(W);Z.push(w);for(let j of W.indexes)Z.push(J.createIndex(W.table,j,W.columns));if(U===H.length-1)for(let j of H)for(let O of j.columns){if(!O.references||!E.has(kh(j.table,O.name)))continue;let _=J.addForeignKey(j.table,O.name,O.references.table,O.references.column,O.references.onDelete,O.references.onUpdate);if(_)Z.push(_)}G.push(...Z);let B=Z.join(`
|
|
478
|
-
|
|
479
|
-
`);A(B,`create-${W.table}-table`)}if(h1+R1===0)i0("-- Nothing to migrate");else{let U=[];if(h1>0)U.push(`${h1} created`);if(R1>0)U.push(`${R1} updated`);i0(`-- Migration files: ${U.join(", ")}`)}return G}function kh($,h){return`${$}\x00${h}`}function n8($,h){if(h==="sqlite"||$.length<2)return{tables:$,deferredForeignKeys:new Set};let A=new Map($.map((U)=>[U.table,U])),G=new Map;for(let U of $)G.set(U.table,new Set(U.columns.map((z)=>z.references?.table).filter((z)=>Boolean(z&&z!==U.table&&A.has(z)))));let J=[],H=new Set;while(J.length<$.length){let U=$.find((z)=>!H.has(z.table)&&[...G.get(z.table)??[]].every((W)=>H.has(W)));if(!U)break;J.push(U),H.add(U.table)}let E=new Set($.filter((U)=>!H.has(U.table)).map((U)=>U.table)),Y=new Set;for(let U of $){if(!E.has(U.table))continue;for(let z of U.columns)if(z.references&&E.has(z.references.table)&&z.references.table!==U.table)Y.add(kh(U.table,z.name))}return J.push(...$.filter((U)=>E.has(U.table))),{tables:J,deferredForeignKeys:Y}}function V3($){return cG($).join(`
|
|
480
|
-
`)}function M3($,h){return TX($,h).join(`
|
|
481
|
-
`)}function BU($){let h=s0("crypto");function A(J){if(J==null||typeof J!=="object"||J instanceof Date)return J;if(Array.isArray(J))return J.map((E)=>A(E));let H={};for(let E of Object.keys(J).sort())H[E]=A(J[E]);return H}let G=JSON.stringify(A($));return h.createHash("sha256").update(G).digest("hex")}function v8($){let h={};for(let A of $)h[A.table]=A;return h}function CA($){let h={};for(let A of $)h[A.name]=A;return h}function _E($,h){if(h==="sqlite"){if($.name.endsWith("_id")&&t1($.type))return"INTEGER";switch($.type){case"string":case"text":case"date":case"datetime":case"timestamptz":case"json":case"enum":return"TEXT";case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}if(h==="mysql"||h==="vitess"||h==="singlestore")switch($.type){case"string":return`VARCHAR(${$.maxLength??255})`;case"text":return"TEXT";case"boolean":return"TINYINT(1)";case"integer":return"INTEGER";case"bigint":return"BIGINT";case"float":return"REAL";case"double":return"DOUBLE";case"decimal":return"DECIMAL";case"date":return"DATE";case"datetime":case"timestamptz":return"DATETIME";case"json":return"JSON";case"enum":return"ENUM";default:return $.type}return $.type}function OE($,h){if(!$.hasDefault||$.defaultValue===void 0)return;let A=$.defaultValue;if(A instanceof Date)return A.toISOString();if(typeof A==="boolean")return A?"1":"0";if(typeof A==="bigint"||typeof A==="number")return String(A);let G=String(A).trim();if(G=G.replace(/::[\w ]+$/i,"").trim(),G.startsWith("'")&&G.endsWith("'")||G.startsWith('"')&&G.endsWith('"'))G=G.slice(1,-1);let J=G.toUpperCase();if(["UTC_TIMESTAMP","UTC_TIMESTAMP()","(UTC_TIMESTAMP)","(UTC_TIMESTAMP())","TIMEZONE('UTC', NOW())","TIMEZONE('UTC'::TEXT, NOW())","(NOW() AT TIME ZONE 'UTC')","NOW() AT TIME ZONE 'UTC'"].includes(J.replace(/\s+/g," ")))return $1;if(h==="sqlite"&&J==="CURRENT_TIMESTAMP")return $1;if(["CURRENT_TIMESTAMP","NOW()","CURRENT_DATE","CURRENT_TIME","NULL","TRUE","FALSE"].includes(J))return J==="NOW()"?"CURRENT_TIMESTAMP":J;if($.type==="boolean"){if(/^(?:1|t|true|yes)$/i.test(G))return"1";if(/^(?:0|f|false|no)$/i.test(G))return"0"}if(/^-?\d+(?:\.\d+)?$/.test(G))return String(Number(G));return G}function BX($,h,A){if(_E($,A)!==_E(h,A))return!0;if($.isNullable!==h.isNullable)return!0;if($.hasDefault!==h.hasDefault)return!0;if(OE($,A)!==OE(h,A))return!0;if($.isUnique!==h.isUnique)return!0;if($.type==="enum"&&h.type==="enum"){let G=($.enumValues||[]).slice().sort().join(","),J=(h.enumValues||[]).slice().sort().join(",");if(G!==J)return!0}return!1}function b8($,h){return JSON.stringify([_E($,h),$.isPrimaryKey,$.isUnique,$.isNullable,$.hasDefault,OE($,h)??null,($.enumValues??[]).slice().sort(),$.references?[$.references.table,$.references.column,$.references.onDelete??null,$.references.onUpdate??null]:null])}function IX($,h,A){let G=Object.keys($).filter((W)=>!h[W]),J=Object.keys(h).filter((W)=>!$[W]),H=new Map,E=new Map;for(let W of G){let Z=b8($[W],A),F=H.get(Z)??[];F.push(W),H.set(Z,F)}for(let W of J){let Z=b8(h[W],A),F=E.get(Z)??[];F.push(W),E.set(Z,F)}let Y=[],U=new Set,z=new Set;for(let[W,Z]of H){let F=E.get(W);if(Z.length===1&&F&&F.length===1)Y.push({from:Z[0],to:F[0]}),U.add(Z[0]),z.add(F[0])}return{renames:Y,removed:G.filter((W)=>!U.has(W)),added:J.filter((W)=>!z.has(W))}}function PX($,h){let A=$.columns.find((G)=>G.name===h);if(A&&(A.isPrimaryKey||A.isUnique||A.references))return!0;return $.indexes.some((G)=>G.columns.includes(h))}function NX($,h){if(Boolean($)!==Boolean(h))return!0;if(!$||!h)return!1;if(($.constraintNames?.length??0)>1)return!0;let A=(G)=>(G??"no action").toLowerCase();return $.table!==h.table||$.column!==h.column||A($.onDelete)!==A(h.onDelete)||A($.onUpdate)!==A(h.onUpdate)}function u8($,h){return`${$.type}:${K$(h,$.name)}:${$.columns.join(",")}`}function FE($,h){let A={};for(let G of $)A[u8(G,h)]=G;return A}function KH($,h,A={}){if(!$||$.dialect!==h.dialect){let R=cG(h,{dryRun:A.dryRun}),S=h.tables.map((D)=>({kind:"create_table",table:D.table,destructive:!1,sql:""}));return{statements:R,operations:S}}let G=A.applyRenames!==!1,J=A.preserveUnknownColumns===!0,H=A.dryRun?()=>!1:p8;KA=0,h1=0,R1=0,ZJ=[],Th=null,WJ=!1;let E=[],Y=[],U=y$(h.dialect,{vitessSharded:h.vitessSharded}),z=h.dialect,W=v8($.tables),Z=v8(h.tables);for(let R of Object.keys(W))if(!Z[R]){let S=U.dropTable(R);E.push(S),Y.push({kind:"drop_table",table:R,destructive:!0,sql:S}),H(S,`drop-${R}-table`),i0(`-- Detected dropped table: ${R}`)}let F=Object.keys(Z).filter((R)=>!W[R]).map((R)=>Z[R]),{tables:w,deferredForeignKeys:B}=n8(F,z);for(let[R,S]of w.entries()){let D={...S,columns:S.columns.map((Q)=>B.has(kh(S.table,Q.name))?{...Q,references:void 0}:Q)},y=[],P=new Set;for(let Q of D.columns)if(Q.type==="enum"&&Q.enumValues&&Q.enumValues.length>0){let N=`${D.table}_${Q.name}_type`;if(Q.enumTypeName=N,!P.has(N)){let K=U.createEnumType(N,Q.enumValues);if(K)y.push(K);P.add(N)}}let T=U.createTable(D);y.push(T);for(let Q of D.indexes){let N=U.createIndex(D.table,Q,D.columns);y.push(N),Y.push({kind:"create_index",table:D.table,column:Q.name,destructive:!1,sql:N})}for(let Q of S.columns)if(Q.references&&!B.has(kh(S.table,Q.name)))Y.push({kind:"add_foreign_key",table:S.table,column:Q.name,destructive:!1,sql:T});if(R===w.length-1)for(let Q of w)for(let N of Q.columns){if(!N.references||!B.has(kh(Q.table,N.name)))continue;let K=U.addForeignKey(Q.table,N.name,N.references.table,N.references.column,N.references.onDelete,N.references.onUpdate);if(!K)continue;y.push(K),Y.push({kind:"add_foreign_key",table:Q.table,column:N.name,destructive:!1,sql:K})}E.push(...y),Y.push({kind:"create_table",table:D.table,destructive:!1,sql:T});let C=y.join(`
|
|
482
|
-
|
|
483
|
-
`);H(C,`create-${D.table}-table`)}let j=new Set;for(let R of Object.keys(Z)){let S=W[R],D=Z[R];if(!S)continue;let y=CA(S.columns),P=CA(D.columns);for(let T of Object.keys(P)){let C=P[T];if(C.type!=="enum"||!C.enumValues||C.enumValues.length===0)continue;let Q=`${D.table}_${C.name}_type`;if(C.enumTypeName=Q,y[T])continue;if(!j.has(Q)){let N=U.createEnumType(Q,C.enumValues);if(N)E.push(N),Y.push({kind:"create_enum",table:D.table,column:C.name,destructive:!1,sql:N}),H(N,`create-${Q}-enum`);j.add(Q)}}}for(let R of Object.keys(Z)){let S=W[R],D=Z[R];if(!S)continue;let y=CA(S.columns),P=FE(S.indexes,S.table),T=CA(D.columns),C=FE(D.indexes,D.table),Q=[],N=Object.keys(y).filter((q)=>!T[q]),K=Object.keys(T).filter((q)=>!y[q]);if(G&&!J){let q=IX(y,T,z);Q=q.renames,N=q.removed,K=q.added}if(J){let q=N.map((u)=>y[u]),d=S.indexes.filter((u)=>!C[u8(u,S.table)]);if(q.length>0||d.length>0){if(q.length>0)i0(`-- Keeping ${q.length} column(s) on "${D.table}" no model declares: ${N.join(", ")} \u2014 reconciled from the database, where an undeclared column is out of scope rather than removed`);if(d.length>0)i0(`-- Keeping ${d.length} index(es) on "${D.table}" no model declares: ${d.map((u)=>u.name).join(", ")} \u2014 reconciled from the database, where an undeclared index is out of scope rather than removed`);D={...D,columns:[...D.columns,...q],indexes:[...D.indexes,...d]},T=CA(D.columns),C=FE(D.indexes,D.table)}N=[]}let x=Object.keys(T).filter((q)=>y[q]&&BX(y[q],T[q],z)),p=Object.keys(T).filter((q)=>y[q]&&NX(y[q].references,T[q].references));if(z==="sqlite"){if(x.length>0||p.length>0||N.some((d)=>PX(S,d))){let d={},u=new Map(Q.map((j0)=>[j0.to,j0.from]));for(let j0 of D.columns)if(y[j0.name])d[j0.name]=j0.name;else if(u.has(j0.name))d[j0.name]=u.get(j0.name);let f=`_qb_tmp_${D.table}`,h0=0;while((W[f]||Z[f])&&h0<100)h0+=1,f=`_qb_tmp_${D.table}_${h0}`;let t=U.rebuildTable({target:D,tempName:f,columnSource:d});E.push(t);let K0=x.some((j0)=>y[j0].type!==T[j0].type);Y.push({kind:"rebuild_table",table:D.table,destructive:N.length>0||K0,sql:t});for(let j0 of Q)Y.push({kind:"rename_column",table:D.table,from:j0.from,to:j0.to,destructive:!1,confidence:"high",sql:t});for(let j0 of N)Y.push({kind:"drop_column",table:D.table,column:j0,destructive:!0,sql:t});i0(`-- Detected SQLite table rebuild required: ${D.table}`),H(t,`alter-${D.table}-table`);continue}}let s=[],o=!1;for(let q of Object.keys(P))if(!C[q]){let d=P[q],u=U.dropIndex(D.table,d.name);s.push(u),E.push(u),Y.push({kind:"drop_index",table:D.table,column:d.name,destructive:!1,sql:u}),i0(`-- Detected dropped index: ${d.name} from ${D.table}`),o=!0}for(let q of Q){let d=U.renameColumn(D.table,q.from,q.to);s.push(d),E.push(d),Y.push({kind:"rename_column",table:D.table,from:q.from,to:q.to,destructive:!1,confidence:"high",sql:d}),i0(`-- Detected renamed column: ${D.table}.${q.from} -> ${q.to}`),o=!0}for(let q of N){let d=U.dropColumn(D.table,q);s.push(d),E.push(d),Y.push({kind:"drop_column",table:D.table,column:q,destructive:!0,sql:d}),i0(`-- Detected dropped column: ${D.table}.${q}`),o=!0}for(let q of x){let d=y[q],u=T[q],f=U.modifyColumn(D.table,u);s.push(f),E.push(f),Y.push({kind:"modify_column",table:D.table,column:q,destructive:d.type!==u.type&&!SX(d.type,u.type),sql:f}),i0(`-- Detected column change: ${D.table}.${q} (${d.type} -> ${u.type})`),o=!0}for(let q of p){let d=T[q];if(!d.references)continue;let u=U.addForeignKey(D.table,d.name,d.references.table,d.references.column,d.references.onDelete,d.references.onUpdate,y[q].references?.constraintNames);if(!u)continue;s.push(u),E.push(u),Y.push({kind:"add_foreign_key",table:D.table,column:q,destructive:!1,sql:u}),i0(`-- Detected foreign-key change: ${D.table}.${q} -> ${d.references.table}(${d.references.column})`),o=!0}for(let q of K){let d=T[q],u=U.addColumn(D.table,d);if(s.push(u),E.push(u),Y.push({kind:"add_column",table:D.table,column:d.name,destructive:!1,sql:u}),i0(`-- Detected new column: ${D.table}.${d.name}`),o=!0,d.references){let f=U.addForeignKey(D.table,d.name,d.references.table,d.references.column,d.references.onDelete,d.references.onUpdate);if(f)s.push(f),E.push(f),Y.push({kind:"add_foreign_key",table:D.table,column:d.name,destructive:!1,sql:f})}}for(let q of Object.keys(C))if(!P[q]){let d=C[q],u=U.createIndex(D.table,d,D.columns);s.push(u),E.push(u),Y.push({kind:"create_index",table:D.table,column:d.name,destructive:!1,sql:u}),i0(`-- Detected new index: ${d.name} in ${D.table}`),o=!0}if(o){let q=s.join(`
|
|
484
|
-
|
|
485
|
-
`);H(q,`alter-${D.table}-table`)}}if(h1+R1===0)i0("-- Nothing to migrate");else{let R=[];if(h1>0)R.push(`${h1} created`);if(R1>0)R.push(`${R1} updated`);i0(`-- Migration files: ${R.join(", ")}`)}return{statements:E.length===0?["-- No changes detected"]:E,operations:Y}}function TX($,h,A={}){return KH($,h,A).statements}var KA=0,h1=0,R1=0,WJ=!0,ZJ,Th=null,m8="-- qb:generated",wE=767,$1="UTC_TIMESTAMP";var i8=a(()=>{f0();eh();fG();jE();$A();ZJ=[]});function Q3($){return $}class kX{get order(){return 100}get description(){return}}function K3($){return $}function s8($){switch($){case"text":return"text";case"string":case"enum":return"varchar";case"integer":case"bigint":return"integer";case"float":case"double":case"decimal":return"fractional";case"boolean":return"boolean";case"date":case"datetime":case"timestamptz":return"date";case"json":return"json";default:return"other"}}function r8($){let h=String($??"").toLowerCase().trim();if(/^(?:bool|boolean|bit)\b/.test(h)||h==="tinyint(1)")return"boolean";if(/^(?:json|jsonb)\b/.test(h))return"json";if(/^(?:bytea|blob|binary|varbinary)\b/.test(h))return"binary";if(/^(?:date|time|timestamp|datetime)\b/.test(h))return"date";if(/(?:^|\b)(?:varchar|character varying|nvarchar|char)\b/.test(h))return"varchar";if(/^(?:text|longtext|mediumtext|tinytext|clob|citext)\b/.test(h))return"text";if(/^(?:decimal|numeric|real|double|money)\b/.test(h)||/^float\d*\b/.test(h))return"fractional";if(/^(?:integer|bigint|smallint|tinyint|serial|bigserial|smallserial|mediumint)\b/.test(h)||/^int\d*\b/.test(h))return"integer";return"other"}function l8($,h,A){if($===h)return!0;if(A==="sqlite"){if($==="boolean"&&h==="integer")return!0;if(($==="date"||$==="json")&&h==="text")return!0}if(G0(A)&&$==="boolean"&&h==="integer")return!0;if($==="varchar"&&h==="text")return!0;if($==="integer"&&h==="fractional")return!0;if($==="other"||h==="other")return!0;return!1}async function yX($,h={}){let A=h.dialect??v.dialect,G=$.tables.map((z)=>z.table),J=await LH({tables:G}),H=new Map(J.map((z)=>[z.table.toLowerCase(),z])),E=[],Y=[],U=[];for(let z of $.tables){let W=H.get(z.table.toLowerCase());if(!W){E.push(z.table);continue}let Z=new Map(W.columns.map((F)=>[F.name.toLowerCase(),F]));for(let F of z.columns){let w=Z.get(F.name.toLowerCase()),B=s8(F.type);if(!w){Y.push({table:z.table,column:F.name,expected:B});continue}let j=r8(w.sqlType);if(!l8(B,j,A))U.push({table:z.table,column:F.name,expected:B,actual:j,actualSqlType:w.sqlType})}}return{missingTables:E,missingColumns:Y,typeMismatches:U,clean:E.length===0&&Y.length===0&&U.length===0}}function qX($){if($.clean)return"";let h=[];if($.missingTables.length>0)h.push(` Missing tables: ${$.missingTables.join(", ")}`);for(let J of $.missingColumns.slice(0,10))h.push(` \u2022 ${J.table}.${J.column} is missing (models declare ${J.expected})`);for(let J of $.typeMismatches.slice(0,10))h.push(` \u2022 ${J.table}.${J.column} is ${J.actualSqlType}, models declare ${J.expected}`);let A=Math.min($.missingColumns.length,10)+Math.min($.typeMismatches.length,10),G=$.missingColumns.length+$.typeMismatches.length;if(G>A)h.push(` + ${G-A} more`);return["The live schema does not match the models.",...h,"","Migrations will NOT fix this on their own: the runner only applies files that have","not run yet, and a corrected `CREATE TABLE IF NOT EXISTS` is a no-op against a table","that already exists. Regenerate and apply the difference, or rebuild the schema."].join(`
|
|
486
|
-
`)}var o8=a(()=>{f0();NG()});var m0=a(()=>{QA();QA();o8();hY();LJ();oh();QA();f0();eh();YJ();XE();B8();fE();I8();y8();jE();i8();XH();WE();VG()});m0();export{d9 as wipeDatabase,I7 as waitReady,aU as validateSchema,Q7 as unsafe,u_ as unmarshallItem,ZH as toTableName,p_ as toModelInstance,d_ as toDynamoDBItem,lW as toDialectPlaceholders,WZ as tinker,Y1 as tableNameFor,OZ as tableInfo,iW as stripTrailingS,x9 as startConsole,e_ as stacksModelToEntity,l9 as sqlTypeToAttr,S7 as sql,z1 as singularizerFor,qU as showModel,y9 as setQueryCacheMaxSize,R9 as setConfig,P_ as seedModel,wU as saveMigrationSnapshot,l8 as satisfies,uU as runSeeders,D7 as runSeeder,uW as runBenchmark,TW as resolveSqlitePragmas,Q1 as resolvePivot,C8 as resolveKeyPattern,OG as resolveDialect,DU as resetDatabase,Q9 as resetConnection,mU as relationDiagram,ZE as registerModel,YX as registerBrowserModels,qF as raw,bU as queryExplainAll,Y7 as ping,zX as parseStacksModels,c9 as optimizeDatabase,qU as modelShow,jH as modelNameForTable,d8 as migrationBody,TU as migrateStatus,A7 as migrateRollback,Rz as migrateModels,H7 as migrateList,oZ as migrateGenerate,n_ as marshallObject,V7 as makeSeeder,xZ as makeModel,C$ as loadModels,CU as lastCreatedMigrationFiles,KF as iterateAllPivots,G0 as isMysqlLike,SX as isLosslessTypeChange,KU as isGeneratedMigrationSql,Fz as isDefinitionEqual,nX as isBrowser,LH as introspectDatabase,DZ as introspect,i9 as inspectTable,sW as inflectSingular,LZ as importData,g1 as hashTableDefinition,BU as hashMigrationPlan,w8 as hasModel,x0 as getPlaceholders,r as getPlaceholder,R8 as getModelRegistry,L8 as getModel,y$ as getDialectDriver,B_ as getDatabase,DG as getConfig,pX as getBrowserConfig,F8 as getAllModels,V3 as generateSqlString,cG as generateSql,t9 as generateModelSource,vG as generateMigration,M3 as generateDiffSqlString,TX as generateDiffSql,KH as generateDiffOperations,mU as generateDiagram,a_ as generateAccessPatterns,M7 as freshDatabase,qX as formatSchemaDrift,_Z as file,r8 as familyOfSqlType,s8 as familyOfDeclared,RJ as extractTableDefinition,NE as extractModelSchema,$8 as extractInsertId,eY as extractChanges,jZ as exportData,bU as explainAllQueries,wZ as explain,OU as executeMigration,aW as escapeStringLiteral,Xj as dynamo,FZ as dumpDatabase,K3 as defineSeeder,Q3 as defineModels,O8 as defineModel,YF as defineConfig,j9 as defaultConfig,d9 as dbWipe,RZ as dbStats,c9 as dbOptimize,v9 as dbInfo,I_ as createTableFromModel,S8 as createSingleTableManager,Q8 as createRepository,J0 as createQueryBuilder,X8 as createModel,yE as createMigrationDriver,GY as createFakerCompatLayer,t_ as createDynamoDBToolingAdapter,x_ as createDynamoDBQueryBuilder,f_ as createDynamoDBItemBuilder,V$ as createDynamoDBDriver,g_ as createDynamoDBClient,jj as createDynamo,f1 as createClient,CE as createBrowserModel,uX as createBrowserDb,TE as convertSchemaToDefinition,K_ as configureOrm,Lz as configureModels,dX as configureBrowser,v as config,k9 as clearQueryCache,_8 as clearModelRegistry,U8 as clearLocalModels,B7 as checkSchema,OE as canonicalizeDefault,_E as canonicalStorageType,UZ as cacheStats,YZ as cacheConfig,EZ as cacheClear,q8 as buildSchemaMeta,AA as buildMigrationPlan,wJ as buildDynamoDBMigrationPlan,PG as buildDatabaseSchema,QE as browserQuery,iX as browserAuth,yX as auditSchemaDrift,uh as applySqliteBootstrapPragmas,yG as VitessDriver,$1 as UTC_CLOCK_DEFAULT,V8 as SingleTableRepository,M8 as SingleTableQueryBuilder,c_ as SingleTablePatterns,D8 as SingleTableManager,kG as SingleStoreDriver,kX as Seeder,xG as SQLiteDriver,TG as PostgresDriver,d0 as MySQLDriver,BE as Model,T$ as MIGRATIONS_TABLE,m8 as GENERATED_MARKER,xE as EntityQueryBuilder,K8 as DynamoDBToolingAdapter,L1 as DynamoDBQueryBuilder,xA as DynamoDBMigrationTracker,OJ as DynamoDBMigrationDriver,q$ as DynamoDBItemBuilder,FJ as DynamoDBDriverImpl,kA as DynamoDBClient,NW as DEFAULT_SQLITE_PRAGMAS,f$ as BrowserQueryError,SE as BrowserQueryBuilder,Z8 as BelongsToManyRelationBuilder};
|
|
2
|
+
import{$,$a as hb,A,Aa as Ia,Ab as _b,B,Ba as Ja,Bb as $b,C,Ca as Ka,Cb as ac,D,Da as La,Db as bc,E,Ea as Ma,Eb as cc,F,Fa as Na,Fb as dc,G,Ga as Oa,Gb as ec,H,Ha as Pa,Hb as fc,I,Ia as Qa,Ib as gc,J,Ja as Ra,Jb as hc,K,Ka as Sa,L,La as Ta,M,Ma as Ua,N,Na as Va,O,Oa as Wa,P,Pa as Xa,Q,Qa as Ya,R,Ra as Za,S,Sa as _a,T,Ta as $a,U,Ua as ab,V,Va as bb,W,Wa as cb,X,Xa as db,Y,Ya as eb,Z,Za as fb,_,_a as gb,a,aa as ca,ab as ib,b,ba as da,bb as jb,c,ca as ea,cb as kb,d,da as fa,db as lb,e,ea as ga,eb as mb,f,fb as nb,g,gb as ob,h,hb as pb,i,ia as ha,ib as qb,j,ja as ia,jb as rb,k,ka as ja,kb as Kb,l,la as ka,lb as Lb,m,ma as la,mb as Mb,n,na as ma,nb as Nb,o,oa as na,ob as Ob,p,pa as oa,pb as Pb,q,qa as pa,qb as Qb,r,ra as qa,rb as Rb,s,sa as ra,sb as Sb,t,ta as sa,tb as Tb,u,ua as ta,ub as Ub,v,va as ua,vb as Vb,w,wa as va,wb as Wb,x,xa as wa,xb as Xb,y,ya as xa,yb as Yb,z,za as Ha,zb as Zb}from"../chunk-yw12p1mp.js";import{Kb as ya,Lb as za,Mb as Aa,Nb as Ba,Ob as Ca,Pb as Da,Qb as Ea,Rb as Fa,Sb as Ga}from"../chunk-fkjeeh31.js";import{$b as wb,Vb as aa,Wb as ba,Xb as sb,Yb as tb,Zb as ub,_b as vb,ac as xb,bc as yb,cc as zb,dc as Ab,ec as Bb,fc as Cb,gc as Db,hc as Eb,ic as Fb,jc as Gb,kc as Hb,lc as Ib,mc as Jb}from"../chunk-605xwkdk.js";import"../chunk-c6mb5jxz.js";export{M as wipeDatabase,xa as waitReady,va as validateSchema,ua as unsafe,nb as unmarshallItem,o as toTableName,lb as toModelInstance,kb as toDynamoDBItem,v as toDialectPlaceholders,F as tinker,p as tableNameFor,Q as tableInfo,q as stripTrailingS,E as startConsole,rb as stacksModelToEntity,S as sqlTypeToAttr,ta as sql,s as singularizerFor,la as showModel,A as setQueryCacheMaxSize,h as setConfig,Qa as seedModel,da as saveMigrationSnapshot,fc as satisfies,pa as runSeeders,qa as runSeeder,n as runBenchmark,k as resolveSqlitePragmas,t as resolvePivot,ib as resolveKeyPattern,d as resolveDialect,ga as resetDatabase,m as resetConnection,oa as relationDiagram,Wa as registerModel,Ya as registerBrowserModels,w as raw,na as queryExplainAll,ma as ping,jb as parseStacksModels,L as optimizeDatabase,la as modelShow,T as modelNameForTable,Qb as migrationBody,ja as migrateStatus,ia as migrateRollback,Gb as migrateModels,ka as migrateList,ha as migrateGenerate,mb as marshallObject,ra as makeSeeder,W as makeModel,Lb as loadModels,Nb as lastCreatedMigrationFiles,u as iterateAllPivots,a as isMysqlLike,Rb as isLosslessTypeChange,Pb as isGeneratedMigrationSql,Bb as isDefinitionEqual,Aa as isBrowser,V as introspectDatabase,R as introspect,P as inspectTable,r as inflectSingular,H as importData,wb as hashTableDefinition,Wb as hashMigrationPlan,Ua as hasModel,f as getPlaceholders,e as getPlaceholder,Ta as getModelRegistry,Ra as getModel,ca as getDialectDriver,Ma as getDatabase,g as getConfig,za as getBrowserConfig,Sa as getAllModels,Ub as generateSqlString,Tb as generateSql,U as generateModelSource,ea as generateMigration,Vb as generateDiffSqlString,$b as generateDiffSql,_b as generateDiffOperations,oa as generateDiagram,qb as generateAccessPatterns,sa as freshDatabase,hc as formatSchemaDrift,O as file,ec as familyOfSqlType,dc as familyOfDeclared,xb as extractTableDefinition,yb as extractModelSchema,Ka as extractInsertId,Ja as extractChanges,G as exportData,na as explainAllQueries,N as explain,fa as executeMigration,x as escapeStringLiteral,Ib as dynamo,I as dumpDatabase,cc as defineSeeder,ac as defineModels,Xa as defineModel,i as defineConfig,b as defaultConfig,M as dbWipe,K as dbStats,L as dbOptimize,J as dbInfo,Pa as createTableFromModel,fb as createSingleTableManager,gb as createRepository,y as createQueryBuilder,Oa as createModel,Fb as createMigrationDriver,Ha as createFakerCompatLayer,pb as createDynamoDBToolingAdapter,$a as createDynamoDBQueryBuilder,ab as createDynamoDBItemBuilder,ba as createDynamoDBDriver,bb as createDynamoDBClient,Jb as createDynamo,tb as createClient,Fa as createBrowserModel,Ea as createBrowserDb,zb as convertSchemaToDefinition,La as configureOrm,ub as configureModels,ya as configureBrowser,c as config,z as clearQueryCache,Va as clearModelRegistry,Ia as clearLocalModels,wa as checkSchema,Zb as canonicalizeDefault,Xb as canonicalStorageType,C as cacheStats,D as cacheConfig,B as cacheClear,Mb as buildSchemaMeta,Sb as buildMigrationPlan,Ab as buildDynamoDBMigrationPlan,Kb as buildDatabaseSchema,Da as browserQuery,Ga as browserAuth,gc as auditSchemaDrift,l as applySqliteBootstrapPragmas,_ as VitessDriver,Yb as UTC_CLOCK_DEFAULT,db as SingleTableRepository,eb as SingleTableQueryBuilder,hb as SingleTablePatterns,cb as SingleTableManager,Z as SingleStoreDriver,bc as Seeder,$ as SQLiteDriver,Y as PostgresDriver,X as MySQLDriver,vb as Model,Cb as MIGRATIONS_TABLE,Ob as GENERATED_MARKER,Hb as EntityQueryBuilder,ob as DynamoDBToolingAdapter,Za as DynamoDBQueryBuilder,Db as DynamoDBMigrationTracker,Eb as DynamoDBMigrationDriver,_a as DynamoDBItemBuilder,aa as DynamoDBDriverImpl,sb as DynamoDBClient,j as DEFAULT_SQLITE_PRAGMAS,Ba as BrowserQueryError,Ca as BrowserQueryBuilder,Na as BelongsToManyRelationBuilder};
|