bun-query-builder 0.3.3 → 0.3.4
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 +6 -6
- package/dist/chunk-afbb8bx3.js +384 -0
- package/dist/chunk-cwf5anrk.js +2 -0
- package/dist/{chunk-4cs1xx1d.js → chunk-jwwbnv83.js} +2 -2
- package/dist/{chunk-3xpe6b57.js → chunk-mbt007va.js} +3 -3
- package/dist/chunk-ne1tyjpr.js +2 -0
- package/dist/{chunk-hjgcemhy.js → chunk-qa7wq5xr.js} +14 -14
- package/dist/chunk-wq450xdk.js +3 -0
- package/dist/chunk-yr0kc2zt.js +3 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/package.json +4 -4
- package/dist/chunk-5eatvs7h.js +0 -384
- package/dist/chunk-axxs7680.js +0 -3
- package/dist/chunk-c7m701dd.js +0 -3
- package/dist/chunk-g2ryjpbk.js +0 -2
- package/dist/chunk-zbjamkgf.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{tt,T,C,R}from"./chunk-afbb8bx3.js";import"./chunk-yr0kc2zt.js";import"./chunk-mbt007va.js";import"./chunk-wq450xdk.js";import"./chunk-qa7wq5xr.js";import"./chunk-jwwbnv83.js";export{C as executeMigration,T as generateMigration,R as resetDatabase,tt as saveMigrationSnapshot};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var n={baseUrl:""};function en(e){n={...n,...e}}function tn(){return n}function nn(){return typeof window<"u"&&typeof document<"u"}async function w(){if(n.getToken){let e=n.getToken();return e instanceof Promise?e:e}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function l(){let e={"Content-Type":"application/json",Accept:"application/json",...n.headers},t=await w();if(t)e.Authorization=`Bearer ${t}`;return e}async function u(e){if(e.status===401)throw n.onUnauthorized?.(),new g("Unauthorized",401);if(!e.ok){let r=await e.json().catch(()=>({message:"Request failed"}));throw new g(r.message||`HTTP ${e.status}`,e.status)}let t=await e.json();if(n.transformResponse)return n.transformResponse(t);return t}class g extends Error{status;constructor(e,t){super(e);this.name="BrowserQueryError",this.status=t}}class ze{state;constructor(e){this.state={table:e,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...e){return this.state.selectColumns=e,this}where(e,t,r){if(r===void 0)this.state.wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this.state.wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}andWhere(e,t,r){return r===void 0?this.where(e,t):this.where(e,t,r)}whereNull(e){return this.where(e,"is",null)}whereNotNull(e){return this.where(e,"is not",null)}whereIn(e,t){return this.where(e,"in",t)}whereNotIn(e,t){return this.where(e,"not in",t)}orderBy(e,t="asc"){return this.state.orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}limit(e){return this.state.limitValue=e,this}offset(e){return this.state.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}with(...e){return this.state.withRelations.push(...e),this}buildQueryParams(){let e=new URLSearchParams;for(let t of this.state.wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this.state.orderBy.length>0){let t=this.state.orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this.state.limitValue!==void 0)e.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)e.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))e.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)e.append("include",this.state.withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.state.table}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return Array.isArray(r)?r:r.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new g(`No ${this.state.table} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r);return"data"in s&&!Array.isArray(s.data)?s.data:s}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new g(`${this.state.table} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.state.table}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async create(e){let t=`${n.baseUrl}/${this.state.table}`,r=n.transformRequest?n.transformRequest(e):e,s=await fetch(t,{method:"POST",headers:await l(),body:JSON.stringify(r)}),a=await u(s);return"data"in a&&!Array.isArray(a.data)?a.data:a}async insert(e){return this.create(e)}async update(e,t){let r=`${n.baseUrl}/${this.state.table}/${e}`,s=n.transformRequest?n.transformRequest(t):t,a=await fetch(r,{method:"PATCH",headers:await l(),body:JSON.stringify(s)}),i=await u(a);return"data"in i&&!Array.isArray(i.data)?i.data:i}async delete(e){let t=`${n.baseUrl}/${this.state.table}/${e}`;return(await fetch(t,{method:"DELETE",headers:await l()})).ok}async destroy(e){return this.delete(e)}async paginate(e=1,t=15){this.limit(t).offset((e-1)*t);let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.state.table}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()});return u(a)}toState(){return{...this.state}}}function Ye(e){return new ze(e)}function rn(){return new Proxy({},{get:(e,t)=>()=>Ye(t)})}class h{_attributes;_definition;constructor(e,t={}){this._definition=e,this._attributes={...t}}get(e){return this._attributes[e]}set(e,t){this._attributes[e]=t}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}toJSON(){let e=new Set;for(let[r,s]of Object.entries(this._definition.attributes))if(s.hidden)e.add(r);let t={};for(let[r,s]of Object.entries(this._attributes))if(!e.has(r))t[r]=s;return t}}class o{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(e){this._definition=e}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(e,t,r){if(r===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}whereNull(e){return this._wheres.push({column:e,operator:"is",value:null,boolean:"and"}),this}whereNotNull(e){return this._wheres.push({column:e,operator:"is not",value:null,boolean:"and"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orderBy(e,t="asc"){return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){return this._withRelations.push(...e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderByAsc(e)}buildQueryParams(){let e=new URLSearchParams;for(let t of this._wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this._orderBy.length>0){let t=this._orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this._limit!==void 0)e.append("limit",String(this._limit));if(this._offset!==void 0)e.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))e.append("fields",this._select.join(","));if(this._withRelations.length>0)e.append("include",this._withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.getTablePath()}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return(Array.isArray(r)?r:r.data).map((a)=>new h(this._definition,a))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new g(`No ${this._definition.name} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r),a="data"in s&&!Array.isArray(s.data)?s.data:s;return new h(this._definition,a)}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new g(`${this._definition.name} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.getTablePath()}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async pluck(e){return this._select=[e],(await this.get()).map((r)=>r.get(e))}async paginate(e=1,t=15){this._limit=t,this._offset=(e-1)*t;let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.getTablePath()}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()}),i=await u(a);return{...i,data:i.data.map((d)=>new h(this._definition,d))}}}function Ie(e){return new Proxy({query:()=>new o(e),where(r,s,a){return new o(e).where(r,s,a)},orWhere(r,s,a){return new o(e).orWhere(r,s,a)},whereIn(r,s){return new o(e).whereIn(r,s)},whereNotIn(r,s){return new o(e).whereNotIn(r,s)},whereNull(r){return new o(e).whereNull(r)},whereNotNull(r){return new o(e).whereNotNull(r)},whereLike(r,s){return new o(e).whereLike(r,s)},orderBy(r,s="asc"){return new o(e).orderBy(r,s)},orderByDesc(r){return new o(e).orderByDesc(r)},select(...r){return new o(e).select(...r)},limit:(r)=>new o(e).limit(r),take:(r)=>new o(e).take(r),skip:(r)=>new o(e).skip(r),latest:(r="created_at")=>new o(e).latest(r),oldest:(r="created_at")=>new o(e).oldest(r),async find(r){return new o(e).find(r)},async findOrFail(r){return new o(e).findOrFail(r)},async all(){return new o(e).get()},async first(){return new o(e).first()},async firstOrFail(){return new o(e).firstOrFail()},async count(){return new o(e).count()},async exists(){return new o(e).exists()},async paginate(r,s){return new o(e).paginate(r,s)},async pluck(r){return new o(e).pluck(r)},async create(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}`,i=n.transformRequest?n.transformRequest(r):r,d=await fetch(a,{method:"POST",headers:await l(),body:JSON.stringify(i)}),c=await u(d),f="data"in c&&!Array.isArray(c.data)?c.data:c;return new h(e,f)},async update(r,s){let a=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,i=`${n.baseUrl}/${a}/${r}`,d=n.transformRequest?n.transformRequest(s):s,c=await fetch(i,{method:"PATCH",headers:await l(),body:JSON.stringify(d)}),f=await u(c),y="data"in f&&!Array.isArray(f.data)?f.data:f;return new h(e,y)},async delete(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}/${r}`;return(await fetch(a,{method:"DELETE",headers:await l()})).ok},async destroy(r){return this.delete(r)},getDefinition:()=>e,getTable:()=>e.table},{get(r,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let a=s.slice(5),i=a.charAt(0).toLowerCase()+a.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(d)=>new o(e).where(i,d)}return Reflect.get(r,s)}})}var sn={async login(e){let t=await fetch(`${n.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Login failed"}));throw new g(a.message||"Login failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async register(e){let t=await fetch(`${n.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Registration failed"}));throw new g(a.message||"Registration failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async logout(){if(await w())try{await fetch(`${n.baseUrl}/logout`,{method:"POST",headers:await l()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await w())return null;try{let t=await fetch(`${n.baseUrl}/user`,{method:"GET",headers:await l()});if(t.status===401)return n.onUnauthorized?.(),null;if(!t.ok)return null;let r=await t.json();return r.user||r}catch{return null}},async check(){return await this.user()!==null},getToken:w},kn=Ye;
|
|
3
|
-
export{en,tn,nn,g,
|
|
2
|
+
var n={baseUrl:""};function en(e){n={...n,...e}}function tn(){return n}function nn(){return typeof window<"u"&&typeof document<"u"}async function w(){if(n.getToken){let e=n.getToken();return e instanceof Promise?e:e}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function l(){let e={"Content-Type":"application/json",Accept:"application/json",...n.headers},t=await w();if(t)e.Authorization=`Bearer ${t}`;return e}async function u(e){if(e.status===401)throw n.onUnauthorized?.(),new g("Unauthorized",401);if(!e.ok){let r=await e.json().catch(()=>({message:"Request failed"}));throw new g(r.message||`HTTP ${e.status}`,e.status)}let t=await e.json();if(n.transformResponse)return n.transformResponse(t);return t}class g extends Error{status;constructor(e,t){super(e);this.name="BrowserQueryError",this.status=t}}class Ye{state;constructor(e){this.state={table:e,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...e){return this.state.selectColumns=e,this}where(e,t,r){if(r===void 0)this.state.wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this.state.wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}andWhere(e,t,r){return r===void 0?this.where(e,t):this.where(e,t,r)}whereNull(e){return this.where(e,"is",null)}whereNotNull(e){return this.where(e,"is not",null)}whereIn(e,t){return this.where(e,"in",t)}whereNotIn(e,t){return this.where(e,"not in",t)}orderBy(e,t="asc"){return this.state.orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}limit(e){return this.state.limitValue=e,this}offset(e){return this.state.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}with(...e){return this.state.withRelations.push(...e),this}buildQueryParams(){let e=new URLSearchParams;for(let t of this.state.wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this.state.orderBy.length>0){let t=this.state.orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this.state.limitValue!==void 0)e.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)e.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))e.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)e.append("include",this.state.withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.state.table}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return Array.isArray(r)?r:r.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new g(`No ${this.state.table} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r);return"data"in s&&!Array.isArray(s.data)?s.data:s}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new g(`${this.state.table} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.state.table}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async create(e){let t=`${n.baseUrl}/${this.state.table}`,r=n.transformRequest?n.transformRequest(e):e,s=await fetch(t,{method:"POST",headers:await l(),body:JSON.stringify(r)}),a=await u(s);return"data"in a&&!Array.isArray(a.data)?a.data:a}async insert(e){return this.create(e)}async update(e,t){let r=`${n.baseUrl}/${this.state.table}/${e}`,s=n.transformRequest?n.transformRequest(t):t,a=await fetch(r,{method:"PATCH",headers:await l(),body:JSON.stringify(s)}),i=await u(a);return"data"in i&&!Array.isArray(i.data)?i.data:i}async delete(e){let t=`${n.baseUrl}/${this.state.table}/${e}`;return(await fetch(t,{method:"DELETE",headers:await l()})).ok}async destroy(e){return this.delete(e)}async paginate(e=1,t=15){this.limit(t).offset((e-1)*t);let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.state.table}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()});return u(a)}toState(){return{...this.state}}}function Xe(e){return new Ye(e)}function rn(){return new Proxy({},{get:(e,t)=>()=>Xe(t)})}class h{_attributes;_definition;constructor(e,t={}){this._definition=e,this._attributes={...t}}get(e){return this._attributes[e]}set(e,t){this._attributes[e]=t}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}toJSON(){let e=new Set;for(let[r,s]of Object.entries(this._definition.attributes))if(s.hidden)e.add(r);let t={};for(let[r,s]of Object.entries(this._attributes))if(!e.has(r))t[r]=s;return t}}class o{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(e){this._definition=e}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(e,t,r){if(r===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}whereNull(e){return this._wheres.push({column:e,operator:"is",value:null,boolean:"and"}),this}whereNotNull(e){return this._wheres.push({column:e,operator:"is not",value:null,boolean:"and"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orderBy(e,t="asc"){return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){return this._withRelations.push(...e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderByAsc(e)}buildQueryParams(){let e=new URLSearchParams;for(let t of this._wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this._orderBy.length>0){let t=this._orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this._limit!==void 0)e.append("limit",String(this._limit));if(this._offset!==void 0)e.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))e.append("fields",this._select.join(","));if(this._withRelations.length>0)e.append("include",this._withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.getTablePath()}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return(Array.isArray(r)?r:r.data).map((a)=>new h(this._definition,a))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new g(`No ${this._definition.name} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r),a="data"in s&&!Array.isArray(s.data)?s.data:s;return new h(this._definition,a)}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new g(`${this._definition.name} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.getTablePath()}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async pluck(e){return this._select=[e],(await this.get()).map((r)=>r.get(e))}async paginate(e=1,t=15){this._limit=t,this._offset=(e-1)*t;let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.getTablePath()}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()}),i=await u(a);return{...i,data:i.data.map((d)=>new h(this._definition,d))}}}function Le(e){return new Proxy({query:()=>new o(e),where(r,s,a){return new o(e).where(r,s,a)},orWhere(r,s,a){return new o(e).orWhere(r,s,a)},whereIn(r,s){return new o(e).whereIn(r,s)},whereNotIn(r,s){return new o(e).whereNotIn(r,s)},whereNull(r){return new o(e).whereNull(r)},whereNotNull(r){return new o(e).whereNotNull(r)},whereLike(r,s){return new o(e).whereLike(r,s)},orderBy(r,s="asc"){return new o(e).orderBy(r,s)},orderByDesc(r){return new o(e).orderByDesc(r)},select(...r){return new o(e).select(...r)},limit:(r)=>new o(e).limit(r),take:(r)=>new o(e).take(r),skip:(r)=>new o(e).skip(r),latest:(r="created_at")=>new o(e).latest(r),oldest:(r="created_at")=>new o(e).oldest(r),async find(r){return new o(e).find(r)},async findOrFail(r){return new o(e).findOrFail(r)},async all(){return new o(e).get()},async first(){return new o(e).first()},async firstOrFail(){return new o(e).firstOrFail()},async count(){return new o(e).count()},async exists(){return new o(e).exists()},async paginate(r,s){return new o(e).paginate(r,s)},async pluck(r){return new o(e).pluck(r)},async create(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}`,i=n.transformRequest?n.transformRequest(r):r,d=await fetch(a,{method:"POST",headers:await l(),body:JSON.stringify(i)}),c=await u(d),f="data"in c&&!Array.isArray(c.data)?c.data:c;return new h(e,f)},async update(r,s){let a=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,i=`${n.baseUrl}/${a}/${r}`,d=n.transformRequest?n.transformRequest(s):s,c=await fetch(i,{method:"PATCH",headers:await l(),body:JSON.stringify(d)}),f=await u(c),y="data"in f&&!Array.isArray(f.data)?f.data:f;return new h(e,y)},async delete(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}/${r}`;return(await fetch(a,{method:"DELETE",headers:await l()})).ok},async destroy(r){return this.delete(r)},getDefinition:()=>e,getTable:()=>e.table},{get(r,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let a=s.slice(5),i=a.charAt(0).toLowerCase()+a.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(d)=>new o(e).where(i,d)}return Reflect.get(r,s)}})}var sn={async login(e){let t=await fetch(`${n.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Login failed"}));throw new g(a.message||"Login failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async register(e){let t=await fetch(`${n.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Registration failed"}));throw new g(a.message||"Registration failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async logout(){if(await w())try{await fetch(`${n.baseUrl}/logout`,{method:"POST",headers:await l()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await w())return null;try{let t=await fetch(`${n.baseUrl}/user`,{method:"GET",headers:await l()});if(t.status===401)return n.onUnauthorized?.(),null;if(!t.ok)return null;let r=await t.json();return r.user||r}catch{return null}},async check(){return await this.user()!==null},getToken:w},kn=Xe;
|
|
3
|
+
export{en,tn,nn,g,Ye,Xe,rn,Le,sn,kn};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
class
|
|
2
|
+
class wt{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityMappings)for(let e of t.entityMappings)this.registerEntity(e)}createTable(t){return{...t,billingMode:t.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(t){return{tableName:t}}registerEntity(t){this.entityMappings.set(t.entityType,t)}getEntityMapping(t){return this.entityMappings.get(t)}buildPrimaryKey(t,e){let i=this.entityMappings.get(t);if(!i)throw Error(`No entity mapping found for type: ${t}`);let n=this.interpolatePattern(i.pkPattern,e),r=this.interpolatePattern(i.skPattern,e);return{pk:n,sk:r}}parseEntityFromItem(t){let e=t.pk||t.PK;if(!e)return null;for(let[i,n]of this.entityMappings){let r=n.pkPattern.split("${")[0];if(e.startsWith(r))return{entityType:i,data:this.unmarshall(t)}}return null}buildQueryParams(t){return{tableName:t.tableName??this.config.tableName??"",keyConditions:t.keyConditions??[],...t}}buildScanParams(t){return{tableName:t.tableName??this.config.tableName??"",...t}}buildGetItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildPutItemParams(t){return{tableName:t.tableName??this.config.tableName??"",item:t.item??{},...t}}buildUpdateItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},updateExpressions:t.updateExpressions??{},...t}}buildDeleteItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildBatchGetItemParams(t){return{requestItems:t.requestItems??{}}}buildBatchWriteItemParams(t){return{requestItems:t.requestItems??{}}}buildTransactWriteParams(t){return{transactItems:t.transactItems??[],...t}}buildKeyConditionExpression(t){return this.buildExpression(t,"AND")}buildFilterExpression(t){return this.buildExpression(t,"AND")}buildUpdateExpression(t){let e={},i={},n=[],r=0;if(t.set&&Object.keys(t.set).length>0){let a=[];for(let[s,o]of Object.entries(t.set)){let l=`#attr${r}`,u=`:val${r}`;e[l]=s,i[u]=this.marshallValue(o),a.push(`${l} = ${u}`),r++}n.push(`SET ${a.join(", ")}`)}if(t.remove&&t.remove.length>0){let a=[];for(let s of t.remove){let o=`#attr${r}`;e[o]=s,a.push(o),r++}n.push(`REMOVE ${a.join(", ")}`)}if(t.add&&Object.keys(t.add).length>0){let a=[];for(let[s,o]of Object.entries(t.add)){let l=`#attr${r}`,u=`:val${r}`;e[l]=s,i[u]=this.marshallValue(o),a.push(`${l} ${u}`),r++}n.push(`ADD ${a.join(", ")}`)}if(t.delete&&Object.keys(t.delete).length>0){let a=[];for(let[s,o]of Object.entries(t.delete)){let l=`#attr${r}`,u=`:val${r}`;e[l]=s,i[u]=this.marshallValue(o),a.push(`${l} ${u}`),r++}n.push(`DELETE ${a.join(", ")}`)}return{expression:n.join(" "),expressionAttributeNames:e,expressionAttributeValues:i}}buildProjectionExpression(t){let e={},i=[];return t.forEach((n,r)=>{let a=`#proj${r}`;e[a]=n,i.push(a)}),{expression:i.join(", "),expressionAttributeNames:e}}marshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return e}unmarshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.unmarshallValue(n);return e}interpolatePattern(t,e){return t.replace(/\$\{(\w+)\}/g,(i,n)=>{if(!(n in e))throw Error(`Missing value for pattern key: ${n}`);return String(e[n])})}buildExpression(t,e){let i={},n={},r=[];return t.forEach((a,s)=>{let o=`#attr${s}`;i[o]=a.attribute;let l;switch(a.operator){case"=":case"<":case"<=":case">":case">=":{let u=`:val${s}`;n[u]=this.marshallValue(a.value),l=`${o} ${a.operator} ${u}`;break}case"BETWEEN":{let u=`:val${s}a`,y=`:val${s}b`;n[u]=this.marshallValue(a.values?.[0]),n[y]=this.marshallValue(a.values?.[1]),l=`${o} BETWEEN ${u} AND ${y}`;break}case"begins_with":{let u=`:val${s}`;n[u]=this.marshallValue(a.value),l=`begins_with(${o}, ${u})`;break}case"contains":{let u=`:val${s}`;n[u]=this.marshallValue(a.value),l=`contains(${o}, ${u})`;break}case"attribute_exists":l=`attribute_exists(${o})`;break;case"attribute_not_exists":l=`attribute_not_exists(${o})`;break;case"attribute_type":{let u=`:val${s}`;n[u]={S:a.value},l=`attribute_type(${o}, ${u})`;break}case"IN":{let u=(a.values??[]).map((y,p)=>`:val${s}_${p}`);a.values?.forEach((y,p)=>{n[`:val${s}_${p}`]=this.marshallValue(y)}),l=`${o} IN (${u.join(", ")})`;break}default:throw Error(`Unknown operator: ${a.operator}`)}r.push(l)}),{expression:r.join(` ${e} `),expressionAttributeNames:i,expressionAttributeValues:n}}marshallValue(t){if(t===null||t===void 0)return{NULL:!0};if(typeof t==="string")return{S:t};if(typeof t==="number")return{N:String(t)};if(typeof t==="boolean")return{BOOL:t};if(t instanceof Uint8Array||Buffer.isBuffer(t))return{B:t};if(Array.isArray(t)){if(t.length===0)return{L:[]};let e=typeof t[0],i=t.every((r)=>typeof r==="string"),n=t.every((r)=>typeof r==="number");if(i)return{SS:t};if(n)return{NS:t.map(String)};return{L:t.map((r)=>this.marshallValue(r))}}if(typeof t==="object"){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return{M:e}}return{S:String(t)}}unmarshallValue(t){if(!t||typeof t!=="object")return t;if("S"in t)return t.S;if("N"in t)return Number(t.N);if("BOOL"in t)return t.BOOL;if("NULL"in t)return null;if("B"in t)return t.B;if("SS"in t)return t.SS;if("NS"in t)return t.NS.map(Number);if("BS"in t)return t.BS;if("L"in t)return t.L.map((e)=>this.unmarshallValue(e));if("M"in t){let e={};for(let[i,n]of Object.entries(t.M))e[i]=this.unmarshallValue(n);return e}return t}}function c(t){return new wt(t)}async function S(t,e){let i=t instanceof ArrayBuffer?t:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",n,new TextEncoder().encode(e))}async function w(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(e)).map((i)=>i.toString(16).padStart(2,"0")).join("")}async function W(t,e,i,n){let r=await S(new TextEncoder().encode(`AWS4${t}`),e),a=await S(r,i),s=await S(a,n);return S(s,"aws4_request")}async function q(t,e,i,n,r,a,s){let l=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),u=l.slice(0,8),y=e.pathname,p=e.search.slice(1),m={...i,host:e.host,"x-amz-date":l};if(r.sessionToken)m["x-amz-security-token"]=r.sessionToken;let h=Object.keys(m).sort(),f=h.map((T)=>`${T.toLowerCase()}:${m[T].trim()}`).join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,A=h.map((T)=>T.toLowerCase()).join(";"),B=await w(n),M=[t,y,p,f,A,B].join(`
|
|
5
5
|
`),K=await w(M),P="AWS4-HMAC-SHA256",_=`${u}/${a}/${s}/aws4_request`,L=[P,l,_,K].join(`
|
|
6
|
-
`),O=await W(r.secretAccessKey,u,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class Q{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.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(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await q("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let u=JSON.parse(o);l=u.message??u.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function E(t){return new Q(t)}var g={region:process.env.AWS_REGION??"us-east-1"},v=null,N=null;function wt(t){g={...g,...t},v=null,N=null}function b(){if(!v)v=E({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return v}function D(){if(!N)N=c({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return N}class qe{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(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new R(this)}static async find(t){let e=this,i=b(),n=D(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=b(),n=D(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let u=new e(l);return u._exists=!0,u}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=b(),n=D(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let u=[],y={},p={},m=0;for(let[h,f]of Object.entries(l)){let A=`#attr${m}`,B=`:val${m}`;y[A]=h,p[B]=n.marshall({v:f}).v,u.push(`${A} = ${B}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${u.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:p});for(let[h,f]of Object.entries(l))this._attributes[h]=f,this[h]=f;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=b(),i=D(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class R{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=D(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let u=o.values.map((y,p)=>`:flt${r}_${p}`);o.values.forEach((y,p)=>{n[`:flt${r}_${p}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${u.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let u=`:flt${r}a`,y=`:flt${r}b`;n[u]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${u} AND ${y}`)}else if(o.operator==="begins_with"){let u=`:flt${r}`;n[u]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${u})`)}else{let u=`:flt${r}`;n[u]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${u}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=b(),e=D(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=b(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=D();if(e)this._startKey=e;this._limitValue=t;let n=b(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let u=i.unmarshall(l),y=new this.ModelClass(u);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function x(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function ke(t){let e=We(t);return Ue(e)}function We(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function Ue(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Ce(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),u=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!u.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,p=e.streamSpecification?.enabled;if(y!==p)if(p)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:x(e)}}function St(t,e){return x(t)===x(e)}var d="_qb_migrations",k="MIGRATION",C="VERSION";class G{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(d),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${d}`),await this.client.createTable({TableName:d,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(d),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${k}#${t}`,i=await this.client.query({TableName:d,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${k}#${t}`,i=await this.client.query({TableName:d,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${k}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:x(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:d,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:d,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${k}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${k}#${t}`;for(let n of e){let r=`${C}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:d,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class Re{client;tracker;config;constructor(t){this.config=t,this.client=E({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new G(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=ke(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Ce(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function Ve(t){return new Re(t)}async function Dt(t,e){return Ve(e).migrateModels(t)}class He{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((u,y)=>`:flt${r}_${y}`);s.values.forEach((u,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:u}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class I{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=c(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new He(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){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 e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){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 e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[u,y]of Object.entries(i.update.set)){let p=`#set${o}`,m=`:set${o}`;a[p]=u,s[m]=this.driver.marshall({v:y}).v,l.push(`${p} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[u,y]of Object.entries(i.update.add)){let p=`#add${o}`,m=`:add${o}`;a[p]=u,s[m]={N:String(y)},l.push(`${p} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let u of i.update.remove){let y=`#rem${o}`;a[y]=u,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var jt=new I;function qt(){return new I}
|
|
7
|
-
export{
|
|
6
|
+
`),O=await W(r.secretAccessKey,u,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class Q{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.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(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await q("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let u=JSON.parse(o);l=u.message??u.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function E(t){return new Q(t)}var g={region:process.env.AWS_REGION??"us-east-1"},v=null,N=null;function St(t){g={...g,...t},v=null,N=null}function b(){if(!v)v=E({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return v}function D(){if(!N)N=c({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return N}class We{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(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new R(this)}static async find(t){let e=this,i=b(),n=D(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=b(),n=D(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let u=new e(l);return u._exists=!0,u}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=b(),n=D(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let u=[],y={},p={},m=0;for(let[h,f]of Object.entries(l)){let A=`#attr${m}`,B=`:val${m}`;y[A]=h,p[B]=n.marshall({v:f}).v,u.push(`${A} = ${B}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${u.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:p});for(let[h,f]of Object.entries(l))this._attributes[h]=f,this[h]=f;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=b(),i=D(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class R{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=D(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let u=o.values.map((y,p)=>`:flt${r}_${p}`);o.values.forEach((y,p)=>{n[`:flt${r}_${p}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${u.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let u=`:flt${r}a`,y=`:flt${r}b`;n[u]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${u} AND ${y}`)}else if(o.operator==="begins_with"){let u=`:flt${r}`;n[u]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${u})`)}else{let u=`:flt${r}`;n[u]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${u}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=b(),e=D(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=b(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=D();if(e)this._startKey=e;this._limitValue=t;let n=b(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let u=i.unmarshall(l),y=new this.ModelClass(u);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function x(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function Ce(t){let e=Ue(t);return Ve(e)}function Ue(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function Ve(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Re(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),u=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!u.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,p=e.streamSpecification?.enabled;if(y!==p)if(p)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:x(e)}}function Dt(t,e){return x(t)===x(e)}var d="_qb_migrations",k="MIGRATION",C="VERSION";class G{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(d),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${d}`),await this.client.createTable({TableName:d,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(d),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${k}#${t}`,i=await this.client.query({TableName:d,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${k}#${t}`,i=await this.client.query({TableName:d,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${k}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:x(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:d,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:d,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${k}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${k}#${t}`;for(let n of e){let r=`${C}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:d,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class Ae{client;tracker;config;constructor(t){this.config=t,this.client=E({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new G(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=Ce(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Re(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function He(t){return new Ae(t)}async function $t(t,e){return He(e).migrateModels(t)}class Qe{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((u,y)=>`:flt${r}_${y}`);s.values.forEach((u,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:u}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class I{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=c(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new Qe(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){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 e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){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 e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[u,y]of Object.entries(i.update.set)){let p=`#set${o}`,m=`:set${o}`;a[p]=u,s[m]=this.driver.marshall({v:y}).v,l.push(`${p} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[u,y]of Object.entries(i.update.add)){let p=`#add${o}`,m=`:add${o}`;a[p]=u,s[m]={N:String(y)},l.push(`${p} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let u of i.update.remove){let y=`#rem${o}`;a[y]=u,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var jt=new I;function qt(){return new I}
|
|
7
|
+
export{wt,c,Q,E,St,We,x,Ce,Ue,Ve,Re,Dt,d,G,Ae,He,$t,Qe,jt,qt};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wt,Ut,Vt,Ht,Qt,At,Gt,Jt}from"./chunk-wq450xdk.js";import"./chunk-qa7wq5xr.js";import"./chunk-jwwbnv83.js";export{Qt as clearModelRegistry,Gt as defineModel,Ut as getAllModels,Wt as getModel,Vt as getModelRegistry,Ht as hasModel,Jt as registerBrowserModels,At as registerModel};
|