bun-query-builder 0.2.55 → 0.2.58
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 +2 -2
- package/dist/{chunk-9ps7fkza.js → chunk-1mmf5p5n.js} +93 -93
- package/dist/{chunk-x8tfs1sw.js → chunk-739qq8wk.js} +1 -1
- package/dist/{chunk-7e64yq76.js → chunk-asdkg5va.js} +2 -2
- package/dist/{chunk-5vqqnp0w.js → chunk-d2b8tt64.js} +1 -1
- package/dist/{chunk-y718nsbf.js → chunk-j9778t8e.js} +1 -1
- package/dist/chunk-rgnkzv8c.js +2 -0
- package/dist/client.d.ts +13 -0
- package/dist/meta.d.ts +1 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-gp6krpcs.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var{defineProperty:e,getOwnPropertyNames:g,getOwnPropertyDescriptor:h}=Object,i=Object.prototype.hasOwnProperty;function j(a){return this[a]}var m=(a)=>{var b=(f??=new WeakMap).get(a),c;if(b)return b;if(b=e({},"__esModule",{value:!0}),a&&typeof a==="object"||typeof a==="function"){for(var d of g(a))if(!i.call(b,d))e(b,d,{get:j.bind(a,d),enumerable:!(c=h(a,d))||c.enumerable})}return f.set(a,b),b},f;var k=(a)=>a;function l(a,b){this[a]=k.bind(null,b)}var n=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0,configurable:!0,set:l.bind(b,c)})};var o=(a,b)=>()=>(a&&(b=a(a=0)),b);var p=import.meta.require;
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as pc,n as qc,o as rc,p as sc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qc as T}from"./chunk-x8tfs1sw.js";function I(z){K={...K,...z}}function R(){return K}function P(){return typeof window<"u"&&typeof document<"u"}async function D(){if(K.getToken){let z=K.getToken();return z instanceof Promise?z:z}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function W(){let z={"Content-Type":"application/json",Accept:"application/json",...K.headers},F=await D();if(F)z.Authorization=`Bearer ${F}`;return z}async function X(z){if(z.status===401)throw K.onUnauthorized?.(),new Y("Unauthorized",401);if(!z.ok){let G=await z.json().catch(()=>({message:"Request failed"}));throw new Y(G.message||`HTTP ${z.status}`,z.status)}let F=await z.json();if(K.transformResponse)return K.transformResponse(F);return F}class x{state;constructor(z){this.state={table:z,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...z){return this.state.selectColumns=z,this}where(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}andWhere(z,F,G){return G===void 0?this.where(z,F):this.where(z,F,G)}whereNull(z){return this.where(z,"is",null)}whereNotNull(z){return this.where(z,"is not",null)}whereIn(z,F){return this.where(z,"in",F)}whereNotIn(z,F){return this.where(z,"not in",F)}orderBy(z,F="asc"){return this.state.orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}latest(z="created_at"){return this.orderBy(z,"desc")}oldest(z="created_at"){return this.orderBy(z,"asc")}limit(z){return this.state.limitValue=z,this}offset(z){return this.state.offsetValue=z,this}skip(z){return this.offset(z)}take(z){return this.limit(z)}with(...z){return this.state.withRelations.push(...z),this}buildQueryParams(){let z=new URLSearchParams;for(let F of this.state.wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this.state.orderBy.length>0){let F=this.state.orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this.state.limitValue!==void 0)z.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)z.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))z.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)z.append("include",this.state.withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.state.table}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return Array.isArray(G)?G:G.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this.state.table} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G);return"data"in J&&!Array.isArray(J.data)?J.data:J}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this.state.table} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.state.table}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async create(z){let F=`${K.baseUrl}/${this.state.table}`,G=K.transformRequest?K.transformRequest(z):z,J=await fetch(F,{method:"POST",headers:await W(),body:JSON.stringify(G)}),L=await X(J);return"data"in L&&!Array.isArray(L.data)?L.data:L}async insert(z){return this.create(z)}async update(z,F){let G=`${K.baseUrl}/${this.state.table}/${z}`,J=K.transformRequest?K.transformRequest(F):F,L=await fetch(G,{method:"PATCH",headers:await W(),body:JSON.stringify(J)}),U=await X(L);return"data"in U&&!Array.isArray(U.data)?U.data:U}async delete(z){let F=`${K.baseUrl}/${this.state.table}/${z}`;return(await fetch(F,{method:"DELETE",headers:await W()})).ok}async destroy(z){return this.delete(z)}async paginate(z=1,F=15){this.limit(F).offset((z-1)*F);let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.state.table}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()});return X(L)}toState(){return{...this.state}}}function q(z){return new x(z)}function H(){return new Proxy({},{get:(z,F)=>{return()=>q(F)}})}class j{_attributes;_definition;constructor(z,F={}){this._definition=z,this._attributes={...F}}get(z){return this._attributes[z]}set(z,F){this._attributes[z]=F}get attributes(){return{...this._attributes}}get id(){let z=this._definition.primaryKey||"id";return this._attributes[z]}toJSON(){let z=new Set;for(let[G,J]of Object.entries(this._definition.attributes))if(J.hidden)z.add(G);let F={};for(let[G,J]of Object.entries(this._attributes))if(!z.has(G))F[G]=J;return F}}class N{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(z){this._definition=z}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this._wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this._wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}whereIn(z,F){return this._wheres.push({column:z,operator:"in",value:F,boolean:"and"}),this}whereNotIn(z,F){return this._wheres.push({column:z,operator:"not in",value:F,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not",value:null,boolean:"and"}),this}whereLike(z,F){return this._wheres.push({column:z,operator:"like",value:F,boolean:"and"}),this}orderBy(z,F="asc"){return this._orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}orderByAsc(z){return this.orderBy(z,"asc")}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}select(...z){return this._select=z,this}with(...z){return this._withRelations.push(...z),this}latest(z="created_at"){return this.orderByDesc(z)}oldest(z="created_at"){return this.orderByAsc(z)}buildQueryParams(){let z=new URLSearchParams;for(let F of this._wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this._orderBy.length>0){let F=this._orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this._limit!==void 0)z.append("limit",String(this._limit));if(this._offset!==void 0)z.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))z.append("fields",this._select.join(","));if(this._withRelations.length>0)z.append("include",this._withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.getTablePath()}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return(Array.isArray(G)?G:G.data).map((L)=>new j(this._definition,L))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this._definition.name} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G),L="data"in J&&!Array.isArray(J.data)?J.data:J;return new j(this._definition,L)}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this._definition.name} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.getTablePath()}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async pluck(z){return this._select=[z],(await this.get()).map((G)=>G.get(z))}async paginate(z=1,F=15){this._limit=F,this._offset=(z-1)*F;let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.getTablePath()}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()}),U=await X(L);return{...U,data:U.data.map((Z)=>new j(this._definition,Z))}}}function k(z){return new Proxy({query:()=>new N(z),where(G,J,L){return new N(z).where(G,J,L)},orWhere(G,J,L){return new N(z).orWhere(G,J,L)},whereIn(G,J){return new N(z).whereIn(G,J)},whereNotIn(G,J){return new N(z).whereNotIn(G,J)},whereNull(G){return new N(z).whereNull(G)},whereNotNull(G){return new N(z).whereNotNull(G)},whereLike(G,J){return new N(z).whereLike(G,J)},orderBy(G,J="asc"){return new N(z).orderBy(G,J)},orderByDesc(G){return new N(z).orderByDesc(G)},select(...G){return new N(z).select(...G)},limit:(G)=>new N(z).limit(G),take:(G)=>new N(z).take(G),skip:(G)=>new N(z).skip(G),latest:(G="created_at")=>new N(z).latest(G),oldest:(G="created_at")=>new N(z).oldest(G),async find(G){return new N(z).find(G)},async findOrFail(G){return new N(z).findOrFail(G)},async all(){return new N(z).get()},async first(){return new N(z).first()},async firstOrFail(){return new N(z).firstOrFail()},async count(){return new N(z).count()},async exists(){return new N(z).exists()},async paginate(G,J){return new N(z).paginate(G,J)},async pluck(G){return new N(z).pluck(G)},async create(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}`,U=K.transformRequest?K.transformRequest(G):G,Z=await fetch(L,{method:"POST",headers:await W(),body:JSON.stringify(U)}),_=await X(Z),$="data"in _&&!Array.isArray(_.data)?_.data:_;return new j(z,$)},async update(G,J){let L=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,U=`${K.baseUrl}/${L}/${G}`,Z=K.transformRequest?K.transformRequest(J):J,_=await fetch(U,{method:"PATCH",headers:await W(),body:JSON.stringify(Z)}),$=await X(_),A="data"in $&&!Array.isArray($.data)?$.data:$;return new j(z,A)},async delete(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}/${G}`;return(await fetch(L,{method:"DELETE",headers:await W()})).ok},async destroy(G){return this.delete(G)},getDefinition:()=>z,getTable:()=>z.table},{get(G,J){if(typeof J==="string"&&J.startsWith("where")&&J.length>5){let L=J.slice(5),U=L.charAt(0).toLowerCase()+L.slice(1);if(U in z.attributes||U==="id"||U===z.primaryKey)return(Z)=>new N(z).where(U,Z)}return Reflect.get(G,J)}})}var K,Y,E,V;var S=T(()=>{K={baseUrl:""};Y=class Y extends Error{status;constructor(z,F){super(z);this.name="BrowserQueryError",this.status=F}};E={async login(z){let F=await fetch(`${K.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Login failed"}));throw new Y(L.message||"Login failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async register(z){let F=await fetch(`${K.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Registration failed"}));throw new Y(L.message||"Registration failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async logout(){if(await D())try{await fetch(`${K.baseUrl}/logout`,{method:"POST",headers:await W()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await D())return null;try{let F=await fetch(`${K.baseUrl}/user`,{method:"GET",headers:await W()});if(F.status===401)return K.onUnauthorized?.(),null;if(!F.ok)return null;let G=await F.json();return G.user||G}catch{return null}},async check(){return await this.user()!==null},getToken:D},V=q});
|
|
3
|
-
export{I as
|
|
2
|
+
import{rc as T}from"./chunk-739qq8wk.js";function I(z){K={...K,...z}}function R(){return K}function P(){return typeof window<"u"&&typeof document<"u"}async function D(){if(K.getToken){let z=K.getToken();return z instanceof Promise?z:z}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function W(){let z={"Content-Type":"application/json",Accept:"application/json",...K.headers},F=await D();if(F)z.Authorization=`Bearer ${F}`;return z}async function X(z){if(z.status===401)throw K.onUnauthorized?.(),new Y("Unauthorized",401);if(!z.ok){let G=await z.json().catch(()=>({message:"Request failed"}));throw new Y(G.message||`HTTP ${z.status}`,z.status)}let F=await z.json();if(K.transformResponse)return K.transformResponse(F);return F}class x{state;constructor(z){this.state={table:z,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...z){return this.state.selectColumns=z,this}where(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}andWhere(z,F,G){return G===void 0?this.where(z,F):this.where(z,F,G)}whereNull(z){return this.where(z,"is",null)}whereNotNull(z){return this.where(z,"is not",null)}whereIn(z,F){return this.where(z,"in",F)}whereNotIn(z,F){return this.where(z,"not in",F)}orderBy(z,F="asc"){return this.state.orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}latest(z="created_at"){return this.orderBy(z,"desc")}oldest(z="created_at"){return this.orderBy(z,"asc")}limit(z){return this.state.limitValue=z,this}offset(z){return this.state.offsetValue=z,this}skip(z){return this.offset(z)}take(z){return this.limit(z)}with(...z){return this.state.withRelations.push(...z),this}buildQueryParams(){let z=new URLSearchParams;for(let F of this.state.wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this.state.orderBy.length>0){let F=this.state.orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this.state.limitValue!==void 0)z.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)z.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))z.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)z.append("include",this.state.withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.state.table}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return Array.isArray(G)?G:G.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this.state.table} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G);return"data"in J&&!Array.isArray(J.data)?J.data:J}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this.state.table} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.state.table}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async create(z){let F=`${K.baseUrl}/${this.state.table}`,G=K.transformRequest?K.transformRequest(z):z,J=await fetch(F,{method:"POST",headers:await W(),body:JSON.stringify(G)}),L=await X(J);return"data"in L&&!Array.isArray(L.data)?L.data:L}async insert(z){return this.create(z)}async update(z,F){let G=`${K.baseUrl}/${this.state.table}/${z}`,J=K.transformRequest?K.transformRequest(F):F,L=await fetch(G,{method:"PATCH",headers:await W(),body:JSON.stringify(J)}),U=await X(L);return"data"in U&&!Array.isArray(U.data)?U.data:U}async delete(z){let F=`${K.baseUrl}/${this.state.table}/${z}`;return(await fetch(F,{method:"DELETE",headers:await W()})).ok}async destroy(z){return this.delete(z)}async paginate(z=1,F=15){this.limit(F).offset((z-1)*F);let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.state.table}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()});return X(L)}toState(){return{...this.state}}}function q(z){return new x(z)}function H(){return new Proxy({},{get:(z,F)=>{return()=>q(F)}})}class j{_attributes;_definition;constructor(z,F={}){this._definition=z,this._attributes={...F}}get(z){return this._attributes[z]}set(z,F){this._attributes[z]=F}get attributes(){return{...this._attributes}}get id(){let z=this._definition.primaryKey||"id";return this._attributes[z]}toJSON(){let z=new Set;for(let[G,J]of Object.entries(this._definition.attributes))if(J.hidden)z.add(G);let F={};for(let[G,J]of Object.entries(this._attributes))if(!z.has(G))F[G]=J;return F}}class N{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(z){this._definition=z}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this._wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this._wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}whereIn(z,F){return this._wheres.push({column:z,operator:"in",value:F,boolean:"and"}),this}whereNotIn(z,F){return this._wheres.push({column:z,operator:"not in",value:F,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not",value:null,boolean:"and"}),this}whereLike(z,F){return this._wheres.push({column:z,operator:"like",value:F,boolean:"and"}),this}orderBy(z,F="asc"){return this._orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}orderByAsc(z){return this.orderBy(z,"asc")}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}select(...z){return this._select=z,this}with(...z){return this._withRelations.push(...z),this}latest(z="created_at"){return this.orderByDesc(z)}oldest(z="created_at"){return this.orderByAsc(z)}buildQueryParams(){let z=new URLSearchParams;for(let F of this._wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this._orderBy.length>0){let F=this._orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this._limit!==void 0)z.append("limit",String(this._limit));if(this._offset!==void 0)z.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))z.append("fields",this._select.join(","));if(this._withRelations.length>0)z.append("include",this._withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.getTablePath()}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return(Array.isArray(G)?G:G.data).map((L)=>new j(this._definition,L))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this._definition.name} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G),L="data"in J&&!Array.isArray(J.data)?J.data:J;return new j(this._definition,L)}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this._definition.name} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.getTablePath()}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async pluck(z){return this._select=[z],(await this.get()).map((G)=>G.get(z))}async paginate(z=1,F=15){this._limit=F,this._offset=(z-1)*F;let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.getTablePath()}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()}),U=await X(L);return{...U,data:U.data.map((Z)=>new j(this._definition,Z))}}}function k(z){return new Proxy({query:()=>new N(z),where(G,J,L){return new N(z).where(G,J,L)},orWhere(G,J,L){return new N(z).orWhere(G,J,L)},whereIn(G,J){return new N(z).whereIn(G,J)},whereNotIn(G,J){return new N(z).whereNotIn(G,J)},whereNull(G){return new N(z).whereNull(G)},whereNotNull(G){return new N(z).whereNotNull(G)},whereLike(G,J){return new N(z).whereLike(G,J)},orderBy(G,J="asc"){return new N(z).orderBy(G,J)},orderByDesc(G){return new N(z).orderByDesc(G)},select(...G){return new N(z).select(...G)},limit:(G)=>new N(z).limit(G),take:(G)=>new N(z).take(G),skip:(G)=>new N(z).skip(G),latest:(G="created_at")=>new N(z).latest(G),oldest:(G="created_at")=>new N(z).oldest(G),async find(G){return new N(z).find(G)},async findOrFail(G){return new N(z).findOrFail(G)},async all(){return new N(z).get()},async first(){return new N(z).first()},async firstOrFail(){return new N(z).firstOrFail()},async count(){return new N(z).count()},async exists(){return new N(z).exists()},async paginate(G,J){return new N(z).paginate(G,J)},async pluck(G){return new N(z).pluck(G)},async create(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}`,U=K.transformRequest?K.transformRequest(G):G,Z=await fetch(L,{method:"POST",headers:await W(),body:JSON.stringify(U)}),_=await X(Z),$="data"in _&&!Array.isArray(_.data)?_.data:_;return new j(z,$)},async update(G,J){let L=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,U=`${K.baseUrl}/${L}/${G}`,Z=K.transformRequest?K.transformRequest(J):J,_=await fetch(U,{method:"PATCH",headers:await W(),body:JSON.stringify(Z)}),$=await X(_),A="data"in $&&!Array.isArray($.data)?$.data:$;return new j(z,A)},async delete(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}/${G}`;return(await fetch(L,{method:"DELETE",headers:await W()})).ok},async destroy(G){return this.delete(G)},getDefinition:()=>z,getTable:()=>z.table},{get(G,J){if(typeof J==="string"&&J.startsWith("where")&&J.length>5){let L=J.slice(5),U=L.charAt(0).toLowerCase()+L.slice(1);if(U in z.attributes||U==="id"||U===z.primaryKey)return(Z)=>new N(z).where(U,Z)}return Reflect.get(G,J)}})}var K,Y,E,V;var S=T(()=>{K={baseUrl:""};Y=class Y extends Error{status;constructor(z,F){super(z);this.name="BrowserQueryError",this.status=F}};E={async login(z){let F=await fetch(`${K.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Login failed"}));throw new Y(L.message||"Login failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async register(z){let F=await fetch(`${K.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Registration failed"}));throw new Y(L.message||"Registration failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async logout(){if(await D())try{await fetch(`${K.baseUrl}/logout`,{method:"POST",headers:await W()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await D())return null;try{let F=await fetch(`${K.baseUrl}/user`,{method:"GET",headers:await W()});if(F.status===401)return K.onUnauthorized?.(),null;if(!F.ok)return null;let G=await F.json();return G.user||G}catch{return null}},async check(){return await this.user()!==null},getToken:D},V=q});
|
|
3
|
+
export{I as Mb,R as Nb,P as Ob,Y as Pb,x as Qb,q as Rb,H as Sb,k as Tb,E as Ub,V as Vb,S as Wb};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qc as Nt,rc as B}from"./chunk-x8tfs1sw.js";import{existsSync as tr}from"fs";import{join as rr}from"path";import ar from"process";import{existsSync as ut,statSync as dt}from"fs";import{join as ir,relative as nr,resolve as ft}from"path";import Ee from"process";import{Buffer as M}from"buffer";import{createCipheriv as or,createDecipheriv as sr,randomBytes as We}from"crypto";import{closeSync as Ie,createReadStream as gt,createWriteStream as lr,existsSync as pe,fsyncSync as pt,openSync as yt,writeFileSync as cr}from"fs";import{access as hr,constants as bt,mkdir as mr,readdir as ye,rename as wt,stat as L,unlink as be,writeFile as Je}from"fs/promises";import{isAbsolute as ur,join as F,resolve as dr}from"path";import g from"process";import{pipeline as fr}from"stream/promises";import{createGzip as Ct}from"zlib";import D from"process";import $ from"process";import we from"process";import{existsSync as Ce}from"fs";import{resolve as ze}from"path";import{existsSync as gr}from"fs";import{existsSync as Ye,mkdirSync as pr,readdirSync as yr,readFileSync as br,writeFileSync as wr}from"fs";import{homedir as H}from"os";import{dirname as vt,resolve as w}from"path";import R from"process";import{existsSync as Cr,readdirSync as vr}from"fs";import{extname as _e,resolve as St}from"path";import Sr from"process";import{spawnSync as fa}from"child_process";import{existsSync as O,readFileSync as ga}from"fs";import{join as j}from"path";import qt from"process";function Ar(e,t){this[e]=kr.bind(null,t)}class at{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!ut(e))return!0;return dt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=ut(r)?dt(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class it{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Pr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Nr(e){return e.getStats().size*2}function xr(e,t={}){let r=Ee.cwd();while(r.includes("storage"))r=ft(r,"..");let a=ft(r,e||"");if(t?.relative)return nr(Ee.cwd(),a);return a}function p(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Rr(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $<"u"){let e=$.type;if(e==="renderer"||e==="worker")return!1;return!!($.versions&&($.versions.node||$.versions.bun))}return!1}class Rt{async format(e){let t=await Rr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:D.pid,hostname:t(),environment:D.env.NODE_ENV||"development",platform:D.platform,version:D.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D.env.NODE_ENV||D.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class He{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...V},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Rt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Se,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Se};return{...Se,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:V.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await hr(this.config.logDirectory,bt.F_OK|bt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await mr(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!pe(this.currentLogFile))await Je(this.currentLogFile,"",{mode:420});if(a=yt(this.currentLogFile,"a",420),cr(a,l,{flag:"a"}),pt(a),a!==void 0)Ie(a),a=void 0;if((await L(this.currentLogFile)).size===0){if(await Je(this.currentLogFile,l,{flag:"w",mode:420}),(await L(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Ie(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F(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 F(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return F(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return We(16).toString("hex")}generateKey(){return We(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=We(16),a=or("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=Ct(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await L(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ye(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await L(r).catch(()=>null))try{if(await wt(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await be(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Je(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await L(r).catch(()=>null))await wt(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await ye(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await be(F(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=gt(e),a=lr(t),i=Ct();await fr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pe(this.currentLogFile))try{let e=yt(this.currentLogFile,"r+");pt(e),Ie(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ye(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await be(F(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ur(t)||t.startsWith("./")||t.startsWith("../"))t=dr(t);else return null;return pe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Lt[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
2
|
+
import{rc as Nt,sc as B}from"./chunk-739qq8wk.js";import{existsSync as tr}from"fs";import{join as rr}from"path";import ar from"process";import{existsSync as ut,statSync as dt}from"fs";import{join as ir,relative as nr,resolve as ft}from"path";import Ee from"process";import{Buffer as M}from"buffer";import{createCipheriv as or,createDecipheriv as sr,randomBytes as We}from"crypto";import{closeSync as Ie,createReadStream as gt,createWriteStream as lr,existsSync as pe,fsyncSync as pt,openSync as yt,writeFileSync as cr}from"fs";import{access as hr,constants as bt,mkdir as mr,readdir as ye,rename as wt,stat as L,unlink as be,writeFile as Je}from"fs/promises";import{isAbsolute as ur,join as F,resolve as dr}from"path";import g from"process";import{pipeline as fr}from"stream/promises";import{createGzip as Ct}from"zlib";import D from"process";import $ from"process";import we from"process";import{existsSync as Ce}from"fs";import{resolve as ze}from"path";import{existsSync as gr}from"fs";import{existsSync as Ye,mkdirSync as pr,readdirSync as yr,readFileSync as br,writeFileSync as wr}from"fs";import{homedir as H}from"os";import{dirname as vt,resolve as w}from"path";import R from"process";import{existsSync as Cr,readdirSync as vr}from"fs";import{extname as _e,resolve as St}from"path";import Sr from"process";import{spawnSync as fa}from"child_process";import{existsSync as O,readFileSync as ga}from"fs";import{join as j}from"path";import qt from"process";function Ar(e,t){this[e]=kr.bind(null,t)}class at{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!ut(e))return!0;return dt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=ut(r)?dt(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class it{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Pr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Nr(e){return e.getStats().size*2}function xr(e,t={}){let r=Ee.cwd();while(r.includes("storage"))r=ft(r,"..");let a=ft(r,e||"");if(t?.relative)return nr(Ee.cwd(),a);return a}function p(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Rr(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $<"u"){let e=$.type;if(e==="renderer"||e==="worker")return!1;return!!($.versions&&($.versions.node||$.versions.bun))}return!1}class Rt{async format(e){let t=await Rr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:D.pid,hostname:t(),environment:D.env.NODE_ENV||"development",platform:D.platform,version:D.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D.env.NODE_ENV||D.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class He{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...V},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Rt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Se,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Se};return{...Se,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:V.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await hr(this.config.logDirectory,bt.F_OK|bt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await mr(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!pe(this.currentLogFile))await Je(this.currentLogFile,"",{mode:420});if(a=yt(this.currentLogFile,"a",420),cr(a,l,{flag:"a"}),pt(a),a!==void 0)Ie(a),a=void 0;if((await L(this.currentLogFile)).size===0){if(await Je(this.currentLogFile,l,{flag:"w",mode:420}),(await L(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Ie(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F(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 F(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return F(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return We(16).toString("hex")}generateKey(){return We(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=We(16),a=or("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=Ct(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await L(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ye(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await L(r).catch(()=>null))try{if(await wt(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await be(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Je(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await L(r).catch(()=>null))await wt(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await ye(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await be(F(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=gt(e),a=lr(t),i=Ct();await fr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pe(this.currentLogFile))try{let e=yt(this.currentLogFile,"r+");pt(e),Ie(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ye(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await be(F(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ur(t)||t.startsWith("./")||t.startsWith("../"))t=dr(t);else return null;return pe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Lt[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
3
3
|
`);for(let b of S)if(b.trim()&&!b.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:f.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
|
|
4
4
|
`;if(l)h+=`${l}
|
|
5
5
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(i,n)=>{},finish:(i)=>{},interrupt:(i,n)=>{}};if(!this.enabled)return r;let a=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:a,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,n="info")=>{if(!p()&&g.stdout.isTTY)g.stdout.write(`
|
|
@@ -4,4 +4,4 @@ class y{config;entityMappings=new Map;constructor(W){if(this.config=W,W.entityMa
|
|
|
4
4
|
`,S=w.map((B)=>B.toLowerCase()).join(";"),A=await b($),r=[W,L,H,R,S,A].join(`
|
|
5
5
|
`),l=await b(r),f="AWS4-HMAC-SHA256",c=`${z}/${Q}/${J}/aws4_request`,n=[f,X,c,l].join(`
|
|
6
6
|
`),s=await e(U.secretAccessKey,z,Q,J),i=await P(s,n),t=Array.from(new Uint8Array(i)).map((B)=>B.toString(16).padStart(2,"0")).join(""),a=`${f} Credential=${U.accessKeyId}/${c}, SignedHeaders=${S}, Signature=${t}`;return{...j,authorization:a}}class I{config;endpoint;credentials;constructor(W){if(this.config=W,this.endpoint=W.endpoint??`https://dynamodb.${W.region}.amazonaws.com`,this.credentials=W.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(W,Y){let Z=new URL(this.endpoint),$=JSON.stringify(Y),U={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${W}`},Q=await WW("POST",Z,U,$,this.credentials,this.config.region,"dynamodb"),J=await fetch(Z.toString(),{method:"POST",headers:Q,body:$});if(!J.ok){let F=await J.text(),X;try{let z=JSON.parse(F);X=z.message??z.Message??F}catch{X=F}throw Error(`DynamoDB ${W} failed: ${J.status} - ${X}`)}return J.json()}async query(W){return this.execute("Query",W)}async scan(W){return this.execute("Scan",W)}async getItem(W){return this.execute("GetItem",W)}async putItem(W){return this.execute("PutItem",W)}async updateItem(W){return this.execute("UpdateItem",W)}async deleteItem(W){return this.execute("DeleteItem",W)}async batchGetItem(W){return this.execute("BatchGetItem",W)}async batchWriteItem(W){return this.execute("BatchWriteItem",W)}async transactWriteItems(W){return this.execute("TransactWriteItems",W)}async describeTable(W){return this.execute("DescribeTable",{TableName:W})}async createTable(W){return this.execute("CreateTable",W)}async deleteTable(W){return this.execute("DeleteTable",{TableName:W})}async listTables(W){return this.execute("ListTables",W??{})}async updateTable(W){return this.execute("UpdateTable",W)}async updateTimeToLive(W){return this.execute("UpdateTimeToLive",W)}async describeTimeToLive(W){return this.execute("DescribeTimeToLive",{TableName:W})}}function q(W){return new I(W)}var O={region:process.env.AWS_REGION??"us-east-1"},h=null,k=null;function YW(W){O={...O,...W},h=null,k=null}function _(){if(!h)h=q({region:O.region??"us-east-1",endpoint:O.endpoint,credentials:O.credentials});return h}function E(){if(!k)k=D({region:O.region??"us-east-1",endpoint:O.endpoint,credentials:O.credentials});return k}class v{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(W={}){this._attributes={...W},this._original={...W};for(let[Y,Z]of Object.entries(W))this[Y]=Z}static query(){return new g(this)}static async find(W){let Y=this,Z=_(),$=E(),U=`${Y.pkPrefix}${Y.keyDelimiter}${W}`,Q=Y.skPrefix;try{let J=await Z.getItem({TableName:Y.tableName,Key:$.marshall({[Y.pkAttribute]:U,[Y.skAttribute]:Q})});if(!J.Item)return null;let F=$.unmarshall(J.Item),X=new Y(F);return X._exists=!0,X}catch(J){return console.error("Find error:",J),null}}static async findOrFail(W){let Y=await this.find(W);if(!Y)throw Error(`${this.name} not found with id: ${W}`);return Y}static async all(){return this.query().get()}static async create(W){let Y=this,Z=_(),$=E(),U=W[Y.primaryKey];if(!U)throw Error(`${Y.primaryKey} is required`);let Q=`${Y.pkPrefix}${Y.keyDelimiter}${U}`,J=Y.skPrefix,F=new Date().toISOString(),X={...W,[Y.pkAttribute]:Q,[Y.skAttribute]:J,[Y.entityTypeAttribute]:Y.name};if(Y.timestamps)X[Y.createdAtField]=F,X[Y.updatedAtField]=F;await Z.putItem({TableName:Y.tableName,Item:$.marshall(X),ConditionExpression:`attribute_not_exists(${Y.pkAttribute})`});let z=new Y(X);return z._exists=!0,z}static async updateOrCreate(W,Y){let Z=this,$=W[Z.primaryKey],U=await Z.find($);if(U)return await U.update(Y),U;return Z.create({...W,...Y})}static where(W,Y,Z){return this.query().where(W,Y,Z)}static wherePk(W){return this.query().wherePk(W)}getKey(){let W=this.constructor;return this[W.primaryKey]}getAttribute(W){return this._attributes[W]}setAttribute(W,Y){return this._attributes[W]=Y,this[W]=Y,this}getAttributes(){return{...this._attributes}}isDirty(W){if(W)return this._attributes[W]!==this._original[W];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let W={};for(let[Y,Z]of Object.entries(this._attributes))if(Z!==this._original[Y])W[Y]=Z;return W}async save(){if(this._exists){let W=this.getDirty();if(Object.keys(W).length>0)await this.update(W)}else{let Y=await this.constructor.create(this._attributes);this._attributes=Y._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(W){let Y=this.constructor,Z=_(),$=E(),U=this.getKey(),Q=`${Y.pkPrefix}${Y.keyDelimiter}${U}`,J=Y.skPrefix,F=new Date().toISOString(),X={...W};if(Y.timestamps)X[Y.updatedAtField]=F;let z=[],L={},H={},j=0;for(let[w,R]of Object.entries(X)){let S=`#attr${j}`,A=`:val${j}`;L[S]=w,H[A]=$.marshall({v:R}).v,z.push(`${S} = ${A}`),j++}await Z.updateItem({TableName:Y.tableName,Key:$.marshall({[Y.pkAttribute]:Q,[Y.skAttribute]:J}),UpdateExpression:`SET ${z.join(", ")}`,ExpressionAttributeNames:L,ExpressionAttributeValues:H});for(let[w,R]of Object.entries(X))this._attributes[w]=R,this[w]=R;return this._original={...this._attributes},this}async delete(){let W=this.constructor,Y=_(),Z=E(),$=this.getKey(),U=`${W.pkPrefix}${W.keyDelimiter}${$}`,Q=W.skPrefix;return await Y.deleteItem({TableName:W.tableName,Key:Z.marshall({[W.pkAttribute]:U,[W.skAttribute]:Q})}),this._exists=!1,!0}async refresh(){let Y=await this.constructor.find(this.getKey());if(Y){this._attributes=Y._attributes,this._original={...this._attributes};for(let[Z,$]of Object.entries(this._attributes))this[Z]=$}return this}toObject(){let W=this.constructor,Y={...this._attributes};return delete Y[W.pkAttribute],delete Y[W.skAttribute],delete Y[W.entityTypeAttribute],Y}toJSON(){return this.toObject()}}class g{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(W){this.ModelClass=W}wherePk(W){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${W}`,this}where(W,Y,Z){if(Z===void 0)this._filterConditions.push({attribute:W,operator:"=",value:Y});else this._filterConditions.push({attribute:W,operator:Y,value:Z});return this}whereIn(W,Y){return this._filterConditions.push({attribute:W,operator:"IN",values:Y}),this}whereBetween(W,Y,Z){return this._filterConditions.push({attribute:W,operator:"BETWEEN",value:Y,values:[Y,Z]}),this}whereBeginsWith(W,Y){return this._filterConditions.push({attribute:W,operator:"begins_with",value:Y}),this}whereExists(W){return this._filterConditions.push({attribute:W,operator:"attribute_exists"}),this}whereNotExists(W){return this._filterConditions.push({attribute:W,operator:"attribute_not_exists"}),this}orderBy(W){return this._scanForward=W==="asc",this}limit(W){return this._limitValue=W,this}select(...W){return this._projectionAttrs.push(...W),this}index(W){return this._indexName=W,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(W){return this._startKey=W,this}buildRequest(){let W=E(),Y={TableName:this.ModelClass.tableName};if(this._indexName)Y.IndexName=this._indexName;let Z={},$={},U=0,Q=[];if(this._pkValue){let J=`#pk${U}`,F=`:pk${U}`;Z[J]=this.ModelClass.pkAttribute,$[F]={S:this._pkValue},Q.push(`${J} = ${F}`),U++}if(this._skCondition){let J=`#sk${U}`;switch(Z[J]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let F=`:sk${U}`;$[F]={S:this._skCondition.value},Q.push(`${J} = ${F}`);break}case"begins_with":{let F=`:sk${U}`;$[F]={S:this._skCondition.value},Q.push(`begins_with(${J}, ${F})`);break}}U++}if(Q.length>0)Y.KeyConditionExpression=Q.join(" AND ");if(this._filterConditions.length>0){let J=[];for(let F of this._filterConditions){let X=`#flt${U}`;if(Z[X]=F.attribute,F.operator==="attribute_exists")J.push(`attribute_exists(${X})`);else if(F.operator==="attribute_not_exists")J.push(`attribute_not_exists(${X})`);else if(F.operator==="IN"&&F.values){let z=F.values.map((L,H)=>`:flt${U}_${H}`);F.values.forEach((L,H)=>{$[`:flt${U}_${H}`]=W.marshall({v:L}).v}),J.push(`${X} IN (${z.join(", ")})`)}else if(F.operator==="BETWEEN"&&F.values){let z=`:flt${U}a`,L=`:flt${U}b`;$[z]=W.marshall({v:F.values[0]}).v,$[L]=W.marshall({v:F.values[1]}).v,J.push(`${X} BETWEEN ${z} AND ${L}`)}else if(F.operator==="begins_with"){let z=`:flt${U}`;$[z]=W.marshall({v:F.value}).v,J.push(`begins_with(${X}, ${z})`)}else{let z=`:flt${U}`;$[z]=W.marshall({v:F.value}).v,J.push(`${X} ${F.operator} ${z}`)}U++}Y.FilterExpression=J.join(" AND ")}if(this._projectionAttrs.length>0){let J=[];for(let F of this._projectionAttrs){let X=`#proj${U}`;Z[X]=F,J.push(X),U++}Y.ProjectionExpression=J.join(", ")}if(Object.keys(Z).length>0)Y.ExpressionAttributeNames=Z;if(Object.keys($).length>0)Y.ExpressionAttributeValues=$;if(this._limitValue!==void 0)Y.Limit=this._limitValue;if(Y.ScanIndexForward=this._scanForward,this._consistentReadValue)Y.ConsistentRead=!0;if(this._startKey)Y.ExclusiveStartKey=W.marshall(this._startKey);return Y}async get(){let W=_(),Y=E(),Z=this.buildRequest();return((this._pkValue!==void 0?await W.query(Z):await W.scan(Z)).Items??[]).map((J)=>{let F=Y.unmarshall(J),X=new this.ModelClass(F);return X._exists=!0,X})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let W=_(),Y=this.buildRequest();return Y.Select="COUNT",(this._pkValue!==void 0?await W.query(Y):await W.scan(Y)).Count??0}async paginate(W,Y){let Z=E();if(Y)this._startKey=Y;this._limitValue=W;let $=_(),U=this.buildRequest(),J=this._pkValue!==void 0?await $.query(U):await $.scan(U);return{items:(J.Items??[]).map((X)=>{let z=Z.unmarshall(X),L=new this.ModelClass(z);return L._exists=!0,L}),lastKey:J.LastEvaluatedKey?Z.unmarshall(J.LastEvaluatedKey):void 0}}}function T(W){let Y=JSON.stringify({tableName:W.tableName,keySchema:W.keySchema,attributeDefinitions:[...W.attributeDefinitions||[]].sort(($,U)=>$.name.localeCompare(U.name)),globalSecondaryIndexes:[...W.globalSecondaryIndexes||[]].sort(($,U)=>$.indexName.localeCompare(U.indexName)),localSecondaryIndexes:[...W.localSecondaryIndexes||[]].sort(($,U)=>$.indexName.localeCompare(U.indexName)),billingMode:W.billingMode,ttlAttribute:W.ttlAttribute,streamSpecification:W.streamSpecification}),Z=0;for(let $=0;$<Y.length;$++){let U=Y.charCodeAt($);Z=(Z<<5)-Z+U,Z=Z&Z}return Math.abs(Z).toString(16).padStart(8,"0")}function C(W){let Y=p(W);return m(Y)}function p(W){return{tableName:W.tableName||"",pkAttribute:W.pkAttribute||"pk",skAttribute:W.skAttribute||"sk",pkPrefix:W.pkPrefix||"",skPrefix:W.skPrefix||"METADATA",entityTypeAttribute:W.entityTypeAttribute||"_et",timestamps:W.timestamps!==!1,ttlAttribute:W.ttlAttribute,gsis:W.gsis,lsis:W.lsis,billingMode:W.billingMode||"PAY_PER_REQUEST",provisionedThroughput:W.provisionedThroughput,streamEnabled:W.streamEnabled,streamViewType:W.streamViewType}}function m(W){let Y=[{name:W.pkAttribute,type:"S"},{name:W.skAttribute,type:"S"}],Z=[];if(W.gsis)for(let $ of W.gsis){if(!Y.some((U)=>U.name===$.pkAttribute))Y.push({name:$.pkAttribute,type:"S"});if($.skAttribute&&!Y.some((U)=>U.name===$.skAttribute))Y.push({name:$.skAttribute,type:"S"});Z.push({indexName:$.indexName,keySchema:{partitionKey:$.pkAttribute,sortKey:$.skAttribute},projection:{type:Array.isArray($.projection)?"INCLUDE":$.projection||"ALL",nonKeyAttributes:Array.isArray($.projection)?$.projection:void 0},provisionedThroughput:$.provisionedThroughput})}return{tableName:W.tableName,keySchema:{partitionKey:W.pkAttribute,sortKey:W.skAttribute},attributeDefinitions:Y,globalSecondaryIndexes:Z.length>0?Z:void 0,billingMode:W.billingMode,provisionedThroughput:W.provisionedThroughput,ttlAttribute:W.ttlAttribute,streamSpecification:W.streamEnabled?{enabled:!0,viewType:W.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function K(W,Y){let Z=[],$=Y.tableName;if(!W)Z.push({type:"CREATE_TABLE",tableName:$,details:{definition:Y}});else{let U=W.keySchema.partitionKey!==Y.keySchema.partitionKey,Q=W.keySchema.sortKey!==Y.keySchema.sortKey;if(U||Q)console.warn(`[Migration] Table ${$}: Key schema changes require table recreation. Current: pk=${W.keySchema.partitionKey}, sk=${W.keySchema.sortKey}. Target: pk=${Y.keySchema.partitionKey}, sk=${Y.keySchema.sortKey}. This operation is not supported automatically.`);let J=W.globalSecondaryIndexes||[],F=Y.globalSecondaryIndexes||[],X=new Set(J.map((j)=>j.indexName)),z=new Set(F.map((j)=>j.indexName));for(let j of F)if(!X.has(j.indexName))Z.push({type:"ADD_GSI",tableName:$,details:{gsi:j}});for(let j of J)if(!z.has(j.indexName))Z.push({type:"DELETE_GSI",tableName:$,details:{indexName:j.indexName}});if(W.billingMode!==Y.billingMode&&Y.billingMode)Z.push({type:"UPDATE_BILLING_MODE",tableName:$,details:{billingMode:Y.billingMode,provisionedThroughput:Y.provisionedThroughput}});if(W.ttlAttribute!==Y.ttlAttribute)Z.push({type:"UPDATE_TTL",tableName:$,details:{ttlAttribute:Y.ttlAttribute||null,enabled:!!Y.ttlAttribute}});let L=W.streamSpecification?.enabled,H=Y.streamSpecification?.enabled;if(L!==H)if(H)Z.push({type:"ENABLE_STREAM",tableName:$,details:{viewType:Y.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else Z.push({type:"DISABLE_STREAM",tableName:$,details:{}})}return{tableName:$,operations:Z,timestamp:new Date().toISOString(),hash:T(Y)}}function ZW(W,Y){return T(W)===T(Y)}var G="_qb_migrations",V="MIGRATION",d="VERSION";class M{client;initialized=!1;constructor(W){this.client=W}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(G),this.initialized=!0}catch(W){if(W.message?.includes("ResourceNotFoundException")||W.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${G}`),await this.client.createTable({TableName:G,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(G),this.initialized=!0;else throw W}}async waitForTableActive(W,Y=30){for(let Z=0;Z<Y;Z++){try{if((await this.client.describeTable(W)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise(($)=>setTimeout($,1000))}throw Error(`Table ${W} did not become active within ${Y} seconds`)}async getLatestState(W){await this.ensureMigrationsTable();let Y=`${V}#${W}`,Z=await this.client.query({TableName:G,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:Y}},ScanIndexForward:!1,Limit:1});if(!Z.Items||Z.Items.length===0)return null;return this.unmarshallState(Z.Items[0])}async getHistory(W){await this.ensureMigrationsTable();let Y=`${V}#${W}`,Z=await this.client.query({TableName:G,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:Y}},ScanIndexForward:!1});if(!Z.Items)return[];return Z.Items.map(($)=>this.unmarshallState($))}async recordMigration(W,Y,Z){await this.ensureMigrationsTable();let $=await this.getLatestState(W),U=Z??($?$.version+1:1),Q=`${V}#${W}`,J=`${d}#${String(U).padStart(6,"0")}`,F={tableName:W,hash:T(Y),definition:Y,appliedAt:new Date().toISOString(),version:U};return await this.client.putItem({TableName:G,Item:this.marshallState(F,Q,J)}),console.log(`[Migration] Recorded migration for ${W} (version ${U})`),F}async listTrackedTables(){await this.ensureMigrationsTable();let W=await this.client.scan({TableName:G,ProjectionExpression:"pk"});if(!W.Items)return[];let Y=new Set;for(let Z of W.Items){let U=(Z.pk?.S||"").replace(`${V}#`,"");if(U)Y.add(U)}return Array.from(Y)}async hasMigrations(W){return await this.getLatestState(W)!==null}async deleteMigrationHistory(W){await this.ensureMigrationsTable();let Y=await this.getHistory(W),Z=`${V}#${W}`;for(let $ of Y){let U=`${d}#${String($.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:G,Key:{pk:{S:Z},sk:{S:U}}})}console.log(`[Migration] Deleted migration history for ${W}`)}marshallState(W,Y,Z){return{pk:{S:Y},sk:{S:Z},tableName:{S:W.tableName},hash:{S:W.hash},definition:{S:JSON.stringify(W.definition)},appliedAt:{S:W.appliedAt},version:{N:String(W.version)}}}unmarshallState(W){return{tableName:W.tableName?.S||"",hash:W.hash?.S||"",definition:JSON.parse(W.definition?.S||"{}"),appliedAt:W.appliedAt?.S||"",version:Number(W.version?.N||0)}}}class N{client;tracker;config;constructor(W){this.config=W,this.client=q({region:W.region,endpoint:W.endpoint,credentials:W.credentials}),this.tracker=new M(this.client)}async execute(W){let Y={tableName:W.tableName,success:!0,operations:[]};if(W.operations.length===0)return this.log(`[Migration] No changes needed for ${W.tableName}`),Y;this.log(`[Migration] Executing ${W.operations.length} operations for ${W.tableName}`);try{for(let Z of W.operations)await this.executeOperation(Z),Y.operations.push(Z.type);this.log(`[Migration] Successfully applied ${Y.operations.length} operations to ${W.tableName}`)}catch(Z){Y.success=!1,Y.error=Z.message,console.error(`[Migration] Failed to execute migration for ${W.tableName}:`,Z)}return Y}async executeOperation(W){if(this.log(`[Migration] Executing ${W.type} on ${W.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${W.type}`,W.details);return}switch(W.type){case"CREATE_TABLE":await this.createTable(W.details.definition);break;case"DELETE_TABLE":await this.deleteTable(W.tableName);break;case"ADD_GSI":await this.addGSI(W.tableName,W.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(W.tableName,W.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(W.tableName,W.details.ttlAttribute,W.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(W.tableName,W.details.billingMode,W.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(W.tableName,W.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(W.tableName);break;default:throw Error(`Unknown migration operation type: ${W.type}`)}}async createTable(W){let Y={TableName:W.tableName,KeySchema:[{AttributeName:W.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:W.attributeDefinitions.map((Z)=>({AttributeName:Z.name,AttributeType:Z.type})),BillingMode:W.billingMode||"PAY_PER_REQUEST"};if(W.keySchema.sortKey)Y.KeySchema.push({AttributeName:W.keySchema.sortKey,KeyType:"RANGE"});if(W.billingMode==="PROVISIONED"&&W.provisionedThroughput)Y.ProvisionedThroughput={ReadCapacityUnits:W.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:W.provisionedThroughput.writeCapacityUnits};if(W.globalSecondaryIndexes&&W.globalSecondaryIndexes.length>0)Y.GlobalSecondaryIndexes=W.globalSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:Z.keySchema.partitionKey,KeyType:"HASH"},...Z.keySchema.sortKey?[{AttributeName:Z.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}},...Z.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:Z.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:Z.provisionedThroughput.writeCapacityUnits}}:{}}));if(W.localSecondaryIndexes&&W.localSecondaryIndexes.length>0)Y.LocalSecondaryIndexes=W.localSecondaryIndexes.map((Z)=>({IndexName:Z.indexName,KeySchema:[{AttributeName:W.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:Z.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:Z.projection.type,...Z.projection.nonKeyAttributes?{NonKeyAttributes:Z.projection.nonKeyAttributes}:{}}}));if(W.streamSpecification?.enabled)Y.StreamSpecification={StreamEnabled:!0,StreamViewType:W.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${W.tableName}`),await this.client.createTable(Y),await this.waitForTableActive(W.tableName),W.ttlAttribute)await this.updateTTL(W.tableName,W.ttlAttribute,!0);this.log(`[Migration] Table created: ${W.tableName}`)}async deleteTable(W){this.log(`[Migration] Deleting table: ${W}`),await this.client.deleteTable(W),this.log(`[Migration] Table deleted: ${W}`)}async addGSI(W,Y){this.log(`[Migration] Adding GSI ${Y.indexName} to ${W}`);let Z=await this.client.describeTable(W),$=new Set(Z.Table?.AttributeDefinitions?.map((J)=>J.AttributeName)||[]),U=[];if(!$.has(Y.keySchema.partitionKey))U.push({AttributeName:Y.keySchema.partitionKey,AttributeType:"S"});if(Y.keySchema.sortKey&&!$.has(Y.keySchema.sortKey))U.push({AttributeName:Y.keySchema.sortKey,AttributeType:"S"});let Q={TableName:W,AttributeDefinitions:U.length>0?U:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:Y.indexName,KeySchema:[{AttributeName:Y.keySchema.partitionKey,KeyType:"HASH"},...Y.keySchema.sortKey?[{AttributeName:Y.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:Y.projection.type,...Y.projection.nonKeyAttributes?{NonKeyAttributes:Y.projection.nonKeyAttributes}:{}},...Y.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:Y.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:Y.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(Q),await this.waitForGSIActive(W,Y.indexName),this.log(`[Migration] GSI ${Y.indexName} added to ${W}`)}async deleteGSI(W,Y){this.log(`[Migration] Deleting GSI ${Y} from ${W}`);let Z={TableName:W,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:Y}}]};await this.executeUpdateTable(Z),this.log(`[Migration] GSI ${Y} deleted from ${W}`)}async updateTTL(W,Y,Z){this.log(`[Migration] Updating TTL on ${W}: ${Z?Y:"disabled"}`);let $={TableName:W,TimeToLiveSpecification:{Enabled:Z,AttributeName:Y||"ttl"}};await this.executeUpdateTimeToLive($),this.log(`[Migration] TTL updated on ${W}`)}async updateBillingMode(W,Y,Z){this.log(`[Migration] Updating billing mode on ${W} to ${Y}`);let $={TableName:W,BillingMode:Y};if(Y==="PROVISIONED"&&Z)$.ProvisionedThroughput={ReadCapacityUnits:Z.readCapacityUnits,WriteCapacityUnits:Z.writeCapacityUnits};await this.executeUpdateTable($),await this.waitForTableActive(W),this.log(`[Migration] Billing mode updated on ${W}`)}async enableStream(W,Y){this.log(`[Migration] Enabling stream on ${W} with view type ${Y}`);let Z={TableName:W,StreamSpecification:{StreamEnabled:!0,StreamViewType:Y}};await this.executeUpdateTable(Z),await this.waitForTableActive(W),this.log(`[Migration] Stream enabled on ${W}`)}async disableStream(W){this.log(`[Migration] Disabling stream on ${W}`);let Y={TableName:W,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(Y),await this.waitForTableActive(W),this.log(`[Migration] Stream disabled on ${W}`)}async executeUpdateTable(W){await this.client.updateTable(W)}async executeUpdateTimeToLive(W){await this.client.updateTimeToLive(W)}async waitForTableActive(W,Y=60){this.log(`[Migration] Waiting for table ${W} to become active...`);for(let Z=0;Z<Y;Z++){try{let U=(await this.client.describeTable(W)).Table?.TableStatus;if(U==="ACTIVE")return;this.log(`[Migration] Table status: ${U}, waiting...`)}catch{}await new Promise(($)=>setTimeout($,2000))}throw Error(`Table ${W} did not become active within ${Y*2} seconds`)}async waitForGSIActive(W,Y,Z=120){this.log(`[Migration] Waiting for GSI ${Y} to become active...`);for(let $=0;$<Z;$++){try{let Q=(await this.client.describeTable(W)).Table?.GlobalSecondaryIndexes?.find((F)=>F.IndexName===Y);if(Q?.IndexStatus==="ACTIVE")return;let J=Q?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${J}, waiting...`)}catch{}await new Promise((U)=>setTimeout(U,5000))}throw Error(`GSI ${Y} did not become active within ${Z*5} seconds`)}async migrateModel(W){let Y=C(W),Z=null;try{let Q=await this.client.describeTable(Y.tableName);if(Q.Table)Z=this.tableInfoToDefinition(Q.Table)}catch(Q){if(!Q.message?.includes("ResourceNotFoundException")&&!Q.message?.includes("not found"))throw Q}let $=K(Z,Y),U=await this.execute($);if(U.success&&!this.config.dryRun)U.state=await this.tracker.recordMigration(Y.tableName,Y);return U}async migrateModels(W){let Y=[];for(let Z of W)try{let $=await this.migrateModel(Z);Y.push($)}catch($){Y.push({tableName:Z.tableName||"unknown",success:!1,operations:[],error:$.message})}return Y}async getStatus(){let W=new Map,Y=await this.tracker.listTrackedTables();for(let Z of Y){let $=await this.tracker.getLatestState(Z);W.set(Z,$)}return W}tableInfoToDefinition(W){let Y={partitionKey:"",sortKey:void 0};for(let U of W.KeySchema||[])if(U.KeyType==="HASH")Y.partitionKey=U.AttributeName;else if(U.KeyType==="RANGE")Y.sortKey=U.AttributeName;let Z=(W.AttributeDefinitions||[]).map((U)=>({name:U.AttributeName,type:U.AttributeType})),$=(W.GlobalSecondaryIndexes||[]).map((U)=>{let Q={partitionKey:"",sortKey:void 0};for(let J of U.KeySchema||[])if(J.KeyType==="HASH")Q.partitionKey=J.AttributeName;else if(J.KeyType==="RANGE")Q.sortKey=J.AttributeName;return{indexName:U.IndexName,keySchema:Q,projection:{type:U.Projection?.ProjectionType||"ALL",nonKeyAttributes:U.Projection?.NonKeyAttributes},provisionedThroughput:U.ProvisionedThroughput?{readCapacityUnits:U.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:U.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:W.TableName,keySchema:Y,attributeDefinitions:Z,globalSecondaryIndexes:$.length>0?$:void 0,billingMode:W.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:W.ProvisionedThroughput?{readCapacityUnits:W.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:W.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:W.TimeToLiveDescription?.AttributeName,streamSpecification:W.StreamSpecification?{enabled:W.StreamSpecification.StreamEnabled,viewType:W.StreamSpecification.StreamViewType}:void 0}}log(...W){if(this.config.verbose||this.config.dryRun)console.log(...W)}}function u(W){return new N(W)}async function $W(W,Y){return u(Y).migrateModels(W)}class o{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(W,Y,Z,$){this.driver=W,this.client=Y,this.tableName=Z,this.pkAttribute=$.pkAttribute,this.skAttribute=$.skAttribute,this.entityTypeAttr=$.entityTypeAttribute,this.delimiter=$.keyDelimiter}entity(W){return this._entityType=W,this}pk(W){return this._pkValue=W,this}get sk(){let W=this;return{equals(Y){return W._skCondition={type:"eq",value:Y},W},beginsWith(Y){return W._skCondition={type:"begins_with",value:Y},W},between(Y,Z){return W._skCondition={type:"between",value:Y,value2:Z},W},lt(Y){return W._skCondition={type:"lt",value:Y},W},lte(Y){return W._skCondition={type:"lte",value:Y},W},gt(Y){return W._skCondition={type:"gt",value:Y},W},gte(Y){return W._skCondition={type:"gte",value:Y},W}}}index(W){return this._indexName=W,this}project(...W){return this._projectionAttrs.push(...W),this}filter(W,Y,Z){return this._filterConditions.push({attribute:W,operator:Y,value:Z}),this}where(W,Y){return this.filter(W,"=",Y)}whereIn(W,Y){return this._filterConditions.push({attribute:W,operator:"IN",values:Y}),this}limit(W){return this._limitValue=W,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(W){return this._startKey=W,this}toRequest(){let W={TableName:this.tableName};if(this._indexName)W.IndexName=this._indexName;let Y=[],Z={},$={},U=0;if(this._pkValue){let Q=`#pk${U}`,J=`:pk${U}`;Z[Q]=this.pkAttribute,$[J]={S:this._pkValue},Y.push(`${Q} = ${J}`),U++}if(this._skCondition){let Q=`#sk${U}`;switch(Z[Q]=this.skAttribute,this._skCondition.type){case"eq":{let J=`:sk${U}`;$[J]={S:this._skCondition.value},Y.push(`${Q} = ${J}`);break}case"begins_with":{let J=`:sk${U}`;$[J]={S:this._skCondition.value},Y.push(`begins_with(${Q}, ${J})`);break}case"between":{let J=`:sk${U}a`,F=`:sk${U}b`;$[J]={S:this._skCondition.value},$[F]={S:this._skCondition.value2},Y.push(`${Q} BETWEEN ${J} AND ${F}`);break}case"lt":{let J=`:sk${U}`;$[J]={S:this._skCondition.value},Y.push(`${Q} < ${J}`);break}case"lte":{let J=`:sk${U}`;$[J]={S:this._skCondition.value},Y.push(`${Q} <= ${J}`);break}case"gt":{let J=`:sk${U}`;$[J]={S:this._skCondition.value},Y.push(`${Q} > ${J}`);break}case"gte":{let J=`:sk${U}`;$[J]={S:this._skCondition.value},Y.push(`${Q} >= ${J}`);break}}U++}if(Y.length>0)W.KeyConditionExpression=Y.join(" AND ");if(this._filterConditions.length>0){let Q=[];for(let J of this._filterConditions){let F=`#flt${U}`;if(Z[F]=J.attribute,J.operator==="IN"&&J.values){let X=J.values.map((z,L)=>`:flt${U}_${L}`);J.values.forEach((z,L)=>{$[`:flt${U}_${L}`]=this.driver.marshall({v:z}).v}),Q.push(`${F} IN (${X.join(", ")})`)}else{let X=`:flt${U}`;$[X]=this.driver.marshall({v:J.value}).v,Q.push(`${F} ${J.operator} ${X}`)}U++}W.FilterExpression=Q.join(" AND ")}if(this._projectionAttrs.length>0){let Q=[];for(let J of this._projectionAttrs){let F=`#proj${U}`;Z[F]=J,Q.push(F),U++}W.ProjectionExpression=Q.join(", ")}if(Object.keys(Z).length>0)W.ExpressionAttributeNames=Z;if(Object.keys($).length>0)W.ExpressionAttributeValues=$;if(this._limitValue!==void 0)W.Limit=this._limitValue;if(W.ScanIndexForward=this._scanForward,this._consistentRead)W.ConsistentRead=!0;if(this._startKey)W.ExclusiveStartKey=this.driver.marshall(this._startKey);return W}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let W=this.toRequest();return((this._pkValue!==void 0?await this.client.query(W):await this.client.scan(W)).Items??[]).map(($)=>this.driver.unmarshall($))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let W=[],Y;do{if(Y)this._startKey=Y;let Z=this.toRequest(),U=this._pkValue!==void 0?await this.client.query(Z):await this.client.scan(Z),Q=(U.Items??[]).map((J)=>this.driver.unmarshall(J));W.push(...Q),Y=U.LastEvaluatedKey?this.driver.unmarshall(U.LastEvaluatedKey):void 0}while(Y);return W}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let W=this.toRequest();return W.Select="COUNT",(this._pkValue!==void 0?await this.client.query(W):await this.client.scan(W)).Count??0}}class x{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(W){let Y={region:W.region,tableName:W.table,endpoint:W.endpoint,credentials:W.credentials};return this.driver=D(Y),this.tableName=W.table,this.pkAttribute=W.pkAttribute??"pk",this.skAttribute=W.skAttribute??"sk",this.entityTypeAttr=W.entityTypeAttribute??"_et",this.delimiter=W.keyDelimiter??"#",this}setClient(W){return this.client=W,this}registerEntity(W){if(this.entityMappings.set(W.entityType,W),this.driver)this.driver.registerEntity(W);return this}entity(W){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new o(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(W)}async batchWrite(W){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 Y=[];for(let Z of W)if(Z.put){let $={...Z.put.item,[this.entityTypeAttr]:Z.put.entity};Y.push({PutRequest:{Item:this.driver.marshall($)}})}else if(Z.delete)Y.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}});if(Y.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:Y}})}async transactWrite(W){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 Y=[];for(let Z of W)if(Z.put){let $={...Z.put.item,[this.entityTypeAttr]:Z.put.entity},U={Put:{TableName:this.tableName,Item:this.driver.marshall($)}};if(Z.put.condition)U.Put.ConditionExpression=Z.put.condition;Y.push(U)}else if(Z.update){let $={[this.pkAttribute]:Z.update.pk};if(Z.update.sk)$[this.skAttribute]=Z.update.sk;let U=[],Q={},J={},F=0;if(Z.update.set){let X=[];for(let[z,L]of Object.entries(Z.update.set)){let H=`#set${F}`,j=`:set${F}`;Q[H]=z,J[j]=this.driver.marshall({v:L}).v,X.push(`${H} = ${j}`),F++}if(X.length>0)U.push(`SET ${X.join(", ")}`)}if(Z.update.add){let X=[];for(let[z,L]of Object.entries(Z.update.add)){let H=`#add${F}`,j=`:add${F}`;Q[H]=z,J[j]={N:String(L)},X.push(`${H} ${j}`),F++}if(X.length>0)U.push(`ADD ${X.join(", ")}`)}if(Z.update.remove&&Z.update.remove.length>0){let X=[];for(let z of Z.update.remove){let L=`#rem${F}`;Q[L]=z,X.push(L),F++}U.push(`REMOVE ${X.join(", ")}`)}Y.push({Update:{TableName:this.tableName,Key:this.driver.marshall($),UpdateExpression:U.join(" "),ExpressionAttributeNames:Q,ExpressionAttributeValues:J}})}else if(Z.delete){let $={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.delete.pk,[this.skAttribute]:Z.delete.sk})}};if(Z.delete.condition)$.Delete.ConditionExpression=Z.delete.condition;Y.push($)}else if(Z.conditionCheck)Y.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:Z.conditionCheck.pk,[this.skAttribute]:Z.conditionCheck.sk}),ConditionExpression:Z.conditionCheck.condition}});if(Y.length>0)await this.client.transactWriteItems({TransactItems:Y})}getDriver(){return this.driver}}var TW=new x;function SW(){return new x}
|
|
7
|
-
export{y as
|
|
7
|
+
export{y as Xb,D as Yb,I as Zb,q as _b,YW as $b,v as ac,T as bc,C as cc,p as dc,m as ec,K as fc,ZW as gc,G as hc,M as ic,N as jc,u as kc,$W as lc,o as mc,TW as nc,SW as oc};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{da as a,ea as b,fa as c,ga as d,ha as e,ia as f,ja as g}from"./chunk-1mmf5p5n.js";import"./chunk-asdkg5va.js";import"./chunk-j9778t8e.js";import"./chunk-739qq8wk.js";export{a as saveMigrationSnapshot,d as resetDatabase,b as generateMigration,c as executeMigration,e as deleteMigrationFiles,f as copyModelsToGenerated,g as clearGeneratedDirectory};
|
package/dist/client.d.ts
CHANGED
|
@@ -66,6 +66,19 @@ export declare function raw(strings: TemplateStringsArray | string, ...values: u
|
|
|
66
66
|
* the quoting changes nothing but the parse.
|
|
67
67
|
*/
|
|
68
68
|
export declare function quoteColumnForDialect(name: string, dialect?: unknown): string;
|
|
69
|
+
/**
|
|
70
|
+
* A date, in the literal shape the dialect will accept.
|
|
71
|
+
*
|
|
72
|
+
* `new Date().toISOString()` is `2026-08-19T04:37:11.396Z`, which Postgres
|
|
73
|
+
* takes and MySQL refuses outright - "Incorrect datetime value" - because the
|
|
74
|
+
* `T`, the fraction and the `Z` are all outside what a `DATETIME` literal may
|
|
75
|
+
* contain. So an application that writes the obvious thing is correct until the
|
|
76
|
+
* engine changes under it, and then it is not, at the point of the write.
|
|
77
|
+
*
|
|
78
|
+
* Naive UTC, deliberately: a `DATETIME` stores no zone, and reading one back as
|
|
79
|
+
* though it were local is the other half of the same bug.
|
|
80
|
+
*/
|
|
81
|
+
export declare function temporalLiteral(value: unknown, dialect?: unknown): unknown;
|
|
69
82
|
/**
|
|
70
83
|
* Format a value for safe interpolation into a relationship-subquery
|
|
71
84
|
* fragment. Numbers / booleans / null pass through; everything else is
|
package/dist/meta.d.ts
CHANGED
package/dist/src/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Mb as a,Nb as b,Ob as c,Pb as d,Qb as e,Rb as f,Sb as g,Tb as h,Ub as i,Vb as j,Wb as k}from"../chunk-asdkg5va.js";import"../chunk-739qq8wk.js";k();export{c as isBrowser,b as getBrowserConfig,j as default,h as createBrowserModel,g as createBrowserDb,a as configureBrowser,f as browserQuery,i as browserAuth,d as BrowserQueryError,e as BrowserQueryBuilder};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$b as
|
|
2
|
+
import{$b as c,Zb as a,_b as b,ac as d,bc as e,cc as f,dc as g,ec as h,fc as i,gc as j,hc as k,ic as l,jc as m,kc as n,lc as o,mc as p,nc as q,oc as r}from"../../chunk-j9778t8e.js";import"../../chunk-739qq8wk.js";export{o as migrateModels,j as isDefinitionEqual,e as hashTableDefinition,f as extractTableDefinition,g as extractModelSchema,q as dynamo,n as createMigrationDriver,r as createDynamo,b as createClient,h as convertSchemaToDefinition,c as configureModels,i as buildDynamoDBMigrationPlan,d as Model,k as MIGRATIONS_TABLE,p as EntityQueryBuilder,l as DynamoDBMigrationTracker,m as DynamoDBMigrationDriver,a as DynamoDBClient};
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$,$a as hb,A,Aa as
|
|
2
|
+
import{$,$a as hb,A,Aa as za,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,Kb as ic,L,La as Ta,Lb as jc,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,ab as ib,b,ba,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,fa as ha,fb as nb,g,ga as ia,gb as ob,h,hb as pb,i,ib as qb,j,jb as rb,k,ka as ja,kb as sb,l,la as ka,lb as tb,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 ya,zb as Zb}from"../chunk-1mmf5p5n.js";import{Mb as Aa,Nb as Ba,Ob as Ca,Pb as Da,Qb as Ea,Rb as Fa,Sb as Ga,Tb as Ha,Ub as Ia}from"../chunk-asdkg5va.js";import{$b as wb,Xb as ca,Yb as da,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,nc as Kb,oc as Lb}from"../chunk-j9778t8e.js";import"../chunk-739qq8wk.js";export{O as wipeDatabase,za as waitReady,xa as validateSchema,wa as unsafe,pb as unmarshallItem,o as toTableName,nb as toModelInstance,mb as toDynamoDBItem,v as toDialectPlaceholders,H as tinker,y as temporalLiteral,p as tableNameFor,S as tableInfo,q as stripTrailingS,G as startConsole,tb as stacksModelToEntity,U as sqlTypeToAttr,va as sql,s as singularizerFor,na as showModel,C as setQueryCacheMaxSize,h as setConfig,Sa as seedModel,fa as saveMigrationSnapshot,hc as satisfies,ra as runSeeders,sa as runSeeder,n as runBenchmark,k as resolveSqlitePragmas,t as resolvePivot,kb as resolveKeyPattern,d as resolveDialect,ia as resetDatabase,m as resetConnection,qa as relationDiagram,Ya as registerModel,_a as registerBrowserModels,w as raw,x as quoteColumnForDialect,pa as queryExplainAll,oa as ping,lb as parseStacksModels,N as optimizeDatabase,na as modelShow,V as modelNameForTable,Sb as migrationBody,la as migrateStatus,ka as migrateRollback,Ib as migrateModels,ma as migrateList,ja as migrateGenerate,ob as marshallObject,ta as makeSeeder,Y as makeModel,Nb as loadModels,Pb as lastCreatedMigrationFiles,u as iterateAllPivots,a as isMysqlLike,Tb as isLosslessTypeChange,Rb as isGeneratedMigrationSql,Db as isDefinitionEqual,Ca as isBrowser,X as introspectDatabase,T as introspect,R as inspectTable,r as inflectSingular,J as importData,yb as hashTableDefinition,Yb as hashMigrationPlan,Wa as hasModel,f as getPlaceholders,e as getPlaceholder,Va as getModelRegistry,Ta as getModel,ea as getDialectDriver,Oa as getDatabase,g as getConfig,Ba as getBrowserConfig,Ua as getAllModels,Wb as generateSqlString,Vb as generateSql,W as generateModelSource,ga as generateMigration,Xb as generateDiffSqlString,bc as generateDiffSql,ac as generateDiffOperations,qa as generateDiagram,sb as generateAccessPatterns,ua as freshDatabase,jc as formatSchemaDrift,Q as file,gc as familyOfSqlType,fc as familyOfDeclared,zb as extractTableDefinition,Ab as extractModelSchema,Ma as extractInsertId,La as extractChanges,I as exportData,pa as explainAllQueries,P as explain,ha as executeMigration,z as escapeStringLiteral,Kb as dynamo,K as dumpDatabase,ec as defineSeeder,cc as defineModels,Za as defineModel,i as defineConfig,b as defaultConfig,O as dbWipe,M as dbStats,N as dbOptimize,L as dbInfo,Ra as createTableFromModel,hb as createSingleTableManager,ib as createRepository,A as createQueryBuilder,Qa as createModel,Hb as createMigrationDriver,Ja as createFakerCompatLayer,rb as createDynamoDBToolingAdapter,bb as createDynamoDBQueryBuilder,cb as createDynamoDBItemBuilder,da as createDynamoDBDriver,db as createDynamoDBClient,Lb as createDynamo,vb as createClient,Ha as createBrowserModel,Ga as createBrowserDb,Bb as convertSchemaToDefinition,Na as configureOrm,wb as configureModels,Aa as configureBrowser,c as config,B as clearQueryCache,Xa as clearModelRegistry,Ka as clearLocalModels,ya as checkSchema,$b as canonicalizeDefault,Zb as canonicalStorageType,E as cacheStats,F as cacheConfig,D as cacheClear,Ob as buildSchemaMeta,Ub as buildMigrationPlan,Cb as buildDynamoDBMigrationPlan,Mb as buildDatabaseSchema,Fa as browserQuery,Ia as browserAuth,ic as auditSchemaDrift,l as applySqliteBootstrapPragmas,aa as VitessDriver,_b as UTC_CLOCK_DEFAULT,fb as SingleTableRepository,gb as SingleTableQueryBuilder,jb as SingleTablePatterns,eb as SingleTableManager,$ as SingleStoreDriver,dc as Seeder,ba as SQLiteDriver,_ as PostgresDriver,Z as MySQLDriver,xb as Model,Eb as MIGRATIONS_TABLE,Qb as GENERATED_MARKER,Jb as EntityQueryBuilder,qb as DynamoDBToolingAdapter,$a as DynamoDBQueryBuilder,Fb as DynamoDBMigrationTracker,Gb as DynamoDBMigrationDriver,ab as DynamoDBItemBuilder,ca as DynamoDBDriverImpl,ub as DynamoDBClient,j as DEFAULT_SQLITE_PRAGMAS,Da as BrowserQueryError,Ea as BrowserQueryBuilder,Pa as BelongsToManyRelationBuilder};
|
package/package.json
CHANGED
package/dist/chunk-gp6krpcs.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ca as a,da as b,ea as c,fa as d,ga as e,ha as f,ia as g}from"./chunk-9ps7fkza.js";import"./chunk-7e64yq76.js";import"./chunk-y718nsbf.js";import"./chunk-x8tfs1sw.js";export{a as saveMigrationSnapshot,d as resetDatabase,b as generateMigration,c as executeMigration,e as deleteMigrationFiles,f as copyModelsToGenerated,g as clearGeneratedDirectory};
|