bun-query-builder 0.2.67 → 0.2.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Ye,b,k,C}from"./chunk-1dv5caj0.js";import"./chunk-kwpppy92.js";import"./chunk-8pz2q01r.js";import"./chunk-7xvyccgk.js";export{k as executeMigration,b as generateMigration,C as resetDatabase,Ye as saveMigrationSnapshot};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"./chunk-b4hmws4w.js";import"./chunk-7xvyccgk.js";export{Vt as clearModelRegistry,Ht as defineModel,qt as getAllModels,jt as getModel,Wt as getModelRegistry,Ut as hasModel,Qt as registerBrowserModels,vt as registerModel};
2
+ import{jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"./chunk-8pz2q01r.js";import"./chunk-7xvyccgk.js";export{Vt as clearModelRegistry,Ht as defineModel,qt as getAllModels,jt as getModel,Wt as getModelRegistry,Ut as hasModel,Qt as registerBrowserModels,vt as registerModel};
@@ -3,5 +3,5 @@ class ht{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityM
3
3
  `)+`
4
4
  `,S=h.map((A)=>A.toLowerCase()).join(";"),B=await w(n),M=[t,y,p,T,S,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 Q(r.secretAccessKey,u,a,s),j=await x(O,L),G=Array.from(new Uint8Array(j)).map((A)=>A.toString(16).padStart(2,"0")).join(""),W=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${S}, Signature=${G}`;return{...m,authorization:W}}class U{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 D(t){return new U(t)}var g={region:process.env.AWS_REGION??"us-east-1"},v=null,N=null;function gt(t){g={...g,...t},v=null,N=null}function b(){if(!v)v=D({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return v}function f(){if(!N)N=c({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return N}class Ie{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=f(),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=f(),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=f(),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,T]of Object.entries(l)){let S=`#attr${m}`,B=`:val${m}`;y[S]=h,p[B]=n.marshall({v:T}).v,u.push(`${S} = ${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,T]of Object.entries(l))this._attributes[h]=T,this[h]=T;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=b(),i=f(),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=f(),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=f(),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=f();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 E(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 xe(t){let e=Le(t);return Ke(e)}function Le(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 Ke(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 ve(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:E(e)}}function pt(t,e){return E(t)===E(e)}var d="_qb_migrations",k="MIGRATION",C="VERSION";class V{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:E(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 ke{client;tracker;config;constructor(t){this.config=t,this.client=D({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new V(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=xe(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=ve(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 Fe(t){return new ke(t)}async function yt(t,e){return Fe(e).migrateModels(t)}class je{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 je(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 Ot=new I;function _t(){return new I}
7
- export{ht,c,U,D,gt,Ie,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,_t};
6
+ `),O=await Q(r.secretAccessKey,u,a,s),j=await x(O,L),G=Array.from(new Uint8Array(j)).map((A)=>A.toString(16).padStart(2,"0")).join(""),W=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${S}, Signature=${G}`;return{...m,authorization:W}}class U{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 D(t){return new U(t)}var g={region:process.env.AWS_REGION??"us-east-1"},v=null,N=null;function gt(t){g={...g,...t},v=null,N=null}function b(){if(!v)v=D({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return v}function f(){if(!N)N=c({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return N}class _e{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=f(),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=f(),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=f(),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,T]of Object.entries(l)){let S=`#attr${m}`,B=`:val${m}`;y[S]=h,p[B]=n.marshall({v:T}).v,u.push(`${S} = ${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,T]of Object.entries(l))this._attributes[h]=T,this[h]=T;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=b(),i=f(),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=f(),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=f(),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=f();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 E(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 xe(t){let e=Le(t);return Ke(e)}function Le(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 Ke(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 ve(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:E(e)}}function pt(t,e){return E(t)===E(e)}var d="_qb_migrations",k="MIGRATION",C="VERSION";class V{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:E(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 ke{client;tracker;config;constructor(t){this.config=t,this.client=D({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new V(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=xe(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=ve(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 Fe(t){return new ke(t)}async function yt(t,e){return Fe(e).migrateModels(t)}class je{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 je(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 Ot=new I;function It(){return new I}
7
+ export{ht,c,U,D,gt,_e,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,It};
package/dist/client.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { config } from './config';
2
2
  import { resetConnection } from './db';
3
3
  import type { AnyDatabaseSchema } from './schema';
4
+ import type { DeferredInsert } from './sqlite-deferred-inserts';
4
5
  import type { DriverConnection } from './db';
5
6
  import type { QueryHooks, SupportedDialect } from './types';
6
7
  import type { SchemaMeta } from './meta';
@@ -399,6 +400,8 @@ export declare interface QueryBuilder<DB extends AnyDatabaseSchema> {
399
400
  raw: (strings: TemplateStringsArray, ...values: unknown[]) => SqlFragment
400
401
  simple: (strings: TemplateStringsArray, ...values: unknown[]) => unknown
401
402
  unsafe: <TRow extends Record<string, unknown> = Record<string, unknown>>(query: string, params?: unknown[]) => Promise<TRow[]>
403
+ deferInsert?: DeferredInsert
404
+ flushDeferredInserts?: () => void
402
405
  file: <TRow extends Record<string, unknown> = Record<string, unknown>>(path: string, params?: unknown[]) => Promise<TRow[]>
403
406
  reserve: () => Promise<(QueryBuilder<DB> & { release: () => void })>
404
407
  close: (opts?: { timeout?: number }) => Promise<void>
package/dist/db.d.ts CHANGED
@@ -2,6 +2,7 @@ import { Database } from 'bun:sqlite';
2
2
  import { SQL } from 'bun';
3
3
  import type { SQLQueryBindings } from 'bun:sqlite';
4
4
  import type { DatabaseConfig, PoolConfig, SupportedDialect } from './types';
5
+ import type { DeferredInsert } from './sqlite-deferred-inserts';
5
6
  /**
6
7
  * The one place user values become driver bindings.
7
8
  *
@@ -140,6 +141,7 @@ export declare interface EmbeddedValue {
140
141
  }
141
142
  export declare interface DriverQuery {
142
143
  execute: () => Promise<any>
144
+ executeSync?: () => any
143
145
  values?: () => any
144
146
  raw?: () => any
145
147
  toString: () => string
@@ -159,6 +161,8 @@ export declare interface DriverConnection {
159
161
  unsafe: (sql: string, values?: unknown[]) => AwaitableDriverQuery
160
162
  query?: (sql: string, params?: unknown[]) => any
161
163
  close?: () => Promise<void> | void
164
+ deferInsert?: DeferredInsert
165
+ flushDeferredInserts?: () => void
162
166
  _prepareStatement?: (sql: string) => any
163
167
  [key: string]: any
164
168
  }
@@ -166,6 +170,8 @@ export declare interface DriverConnection {
166
170
  export type AwaitableDriverQuery = DriverQuery & PromiseLike<any>;
167
171
  declare class SQLiteWrapper {
168
172
  constructor(filename: string);
173
+ deferInsert: DeferredInsert;
174
+ flushDeferredInserts(): void;
169
175
  query(sql: string, params?: SQLQueryBindings[]): any[];
170
176
  run(sql: string, params?: SQLQueryBindings[]): any;
171
177
  close(): void;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export type { DeferredInsert } from './sqlite-deferred-inserts';
1
2
  // Resolve ambiguous re-exports by explicitly choosing which module's version to use
2
3
  export type { WhereOperator } from './browser';
3
4
  export type { ModelQueryBuilder } from './dynamodb/index';
package/dist/orm.d.ts CHANGED
@@ -213,7 +213,7 @@ export declare interface WriteResultLike {
213
213
  * populated only for `belongsToMany` relations.
214
214
  */
215
215
  declare interface ResolvedRelation {
216
- type: 'hasMany' | 'hasOne' | 'belongsTo' | 'belongsToMany' | 'hasManyThrough' | 'hasOneThrough'
216
+ type: 'hasMany' | 'hasOne' | 'belongsTo' | 'belongsToMany' | 'hasManyThrough' | 'hasOneThrough' | 'morphMany' | 'morphOne'
217
217
  relatedModelName: string
218
218
  relatedTable: string
219
219
  foreignKey: string
@@ -225,6 +225,8 @@ declare interface ResolvedRelation {
225
225
  pivotTable?: string
226
226
  pivotFkParent?: string
227
227
  pivotFkRelated?: string
228
+ morphTypeColumn?: string
229
+ morphTypeValue?: string
228
230
  pivotColumns?: string[]
229
231
  pivotModelName?: string
230
232
  pivotTimestamps?: boolean
@@ -0,0 +1,11 @@
1
+ import type { Database, SQLQueryBindings } from 'bun:sqlite';
2
+ export type DeferredInsert = (table: string, record: Readonly<Record<string, SQLQueryBindings | undefined>>) => Promise<void>;
3
+ /** Native work stays synchronous so close and transaction barriers can drain it. */
4
+ export declare class SQLiteDeferredInserts {
5
+ constructor(database: Database);
6
+ get hasPending(): boolean;
7
+ append: DeferredInsert;
8
+ flush(): void;
9
+ assertUsable(): void;
10
+ close(): void;
11
+ }
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{U,D,gt,Ie,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,_t}from"../../chunk-55jccfgb.js";export{U as DynamoDBClient,ke as DynamoDBMigrationDriver,V as DynamoDBMigrationTracker,je as EntityQueryBuilder,d as MIGRATIONS_TABLE,Ie as Model,ve as buildDynamoDBMigrationPlan,gt as configureModels,Ke as convertSchemaToDefinition,D as createClient,_t as createDynamo,Fe as createMigrationDriver,Ot as dynamo,Le as extractModelSchema,xe as extractTableDefinition,E as hashTableDefinition,pt as isDefinitionEqual,yt as migrateModels};
2
+ import{U,D,gt,_e,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,It}from"../../chunk-kwpppy92.js";export{U as DynamoDBClient,ke as DynamoDBMigrationDriver,V as DynamoDBMigrationTracker,je as EntityQueryBuilder,d as MIGRATIONS_TABLE,_e as Model,ve as buildDynamoDBMigrationPlan,gt as configureModels,Ke as convertSchemaToDefinition,D as createClient,It as createDynamo,Fe as createMigrationDriver,Ot as dynamo,Le as extractModelSchema,xe as extractTableDefinition,E as hashTableDefinition,pt as isDefinitionEqual,yt as migrateModels};
package/dist/src/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{J,S,Zt,en,l,kt,Ct,i,Qe,Ge,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,_,ae,oe,Je,Be,ze,v,le,a,ce,ue,de,fe,f,Ye,b,k,C,me,he,I,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De,T,m,tn,nn,rn,Xe,Ze,et,tt,nt,sn,rt,Rt,an,on,ln,cn,it,un,dn,fn,$e,u,st,at,ot,lt,ct,At,W,Ee,mn,hn,ut,Pe,g,Oe,_e,Mt,gn,Nt,pn,dt,ft,mt,Bt,Pt}from"../chunk-trp12g5x.js";import{ht,c,U,D,gt,Ie,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,_t}from"../chunk-55jccfgb.js";import{n,bt,e,H,t,s,Q,qe,yn,It,Lt,G,bn,Ue,p,Kt,Ft,y,Tn,wt,St,Dt,$t,wn,Sn,Dn,Et,xt,$n,En,jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"../chunk-b4hmws4w.js";import{Gt,Jt,zt,h,Ve,He,Yt,Ne,Xt}from"../chunk-7xvyccgk.js";export{Et as BelongsToManyRelationBuilder,Ve as BrowserQueryBuilder,h as BrowserQueryError,It as DEFAULT_SQLITE_PRAGMAS,U as DynamoDBClient,ht as DynamoDBDriverImpl,m as DynamoDBItemBuilder,ke as DynamoDBMigrationDriver,V as DynamoDBMigrationTracker,T as DynamoDBQueryBuilder,it as DynamoDBToolingAdapter,je as EntityQueryBuilder,ot as GENERATED_MARKER,d as MIGRATIONS_TABLE,Ie as Model,a as MySQLDriver,ce as PostgresDriver,fe as SQLiteDriver,Nt as Seeder,ue as SingleStoreDriver,Xe as SingleTableManager,sn as SingleTablePatterns,et as SingleTableQueryBuilder,Ze as SingleTableRepository,g as UTC_CLOCK_DEFAULT,de as VitessDriver,G as applySqliteBootstrapPragmas,Bt as auditSchemaDrift,Xt as browserAuth,He as browserQuery,$e as buildDatabaseSchema,ve as buildDynamoDBMigrationPlan,W as buildMigrationPlan,st as buildSchemaMeta,z as cacheClear,X as cacheConfig,Y as cacheStats,Pe as canonicalStorageType,Oe as canonicalizeDefault,Se as checkSchema,St as clearLocalModels,Vt as clearModelRegistry,Qe as clearQueryCache,e as config,Gt as configureBrowser,gt as configureModels,wn as configureOrm,Ke as convertSchemaToDefinition,Yt as createBrowserDb,Ne as createBrowserModel,D as createClient,_t as createDynamo,rn as createDynamoDBClient,c as createDynamoDBDriver,nn as createDynamoDBItemBuilder,tn as createDynamoDBQueryBuilder,un as createDynamoDBToolingAdapter,wt as createFakerCompatLayer,Fe as createMigrationDriver,xt as createModel,i as createQueryBuilder,nt as createRepository,tt as createSingleTableManager,$n as createTableFromModel,B as dbInfo,P as dbOptimize,re as dbStats,O as dbWipe,bt as defaultConfig,yn as defineConfig,Ht as defineModel,gn as defineModels,pn as defineSeeder,ne as dumpDatabase,Ot as dynamo,Ct as escapeStringLiteral,k as executeMigration,ie as explain,K as explainAllQueries,ee as exportData,Dt as extractChanges,$t as extractInsertId,Le as extractModelSchema,xe as extractTableDefinition,dt as familyOfDeclared,ft as familyOfSqlType,se as file,Pt as formatSchemaDrift,be as freshDatabase,dn as generateAccessPatterns,F as generateDiagram,_e as generateDiffOperations,Mt as generateDiffSql,hn as generateDiffSqlString,b as generateMigration,ze as generateModelSource,Ee as generateSql,mn as generateSqlString,qt as getAllModels,Jt as getBrowserConfig,Q as getConfig,Dn as getDatabase,f as getDialectDriver,jt as getModel,Wt as getModelRegistry,t as getPlaceholder,s as getPlaceholders,Ut as hasModel,ut as hashMigrationPlan,E as hashTableDefinition,te as importData,Ft as inflectSingular,_ as inspectTable,oe as introspect,v as introspectDatabase,zt as isBrowser,pt as isDefinitionEqual,lt as isGeneratedMigrationSql,At as isLosslessTypeChange,n as isMysqlLike,Zt as iterateAllPivots,at as lastCreatedMigrationFiles,u as loadModels,le as makeModel,ye as makeSeeder,ln as marshallObject,me as migrateGenerate,ge as migrateList,yt as migrateModels,he as migrateRollback,I as migrateStatus,ct as migrationBody,Be as modelNameForTable,L as modelShow,P as optimizeDatabase,Rt as parseStacksModels,pe as ping,K as queryExplainAll,l as quoteColumnForDialect,en as raw,Qt as registerBrowserModels,vt as registerModel,F as relationDiagram,Sn as releaseOrm,bn as resetConnection,C as resetDatabase,H as resolveDialect,rt as resolveKeyPattern,S as resolvePivot,Lt as resolveSqlitePragmas,J as runBenchmark,j as runSeeder,R as runSeeders,mt as satisfies,Ye as saveMigrationSnapshot,En as seedModel,qe as setConfig,Ge as setQueryCacheMaxSize,L as showModel,y as singularizerFor,Te as sql,Je as sqlTypeToAttr,fn as stacksModelToEntity,N as startConsole,Kt as stripTrailingS,ae as tableInfo,p as tableNameFor,kt as temporalLiteral,Z as tinker,Tn as toDialectPlaceholders,an as toDynamoDBItem,on as toModelInstance,Ue as toTableName,cn as unmarshallItem,we as unsafe,q as validateSchema,De as waitReady,O as wipeDatabase};
2
+ import{J,S,Zt,en,l,kt,Ct,i,Qe,Ge,z,Y,X,N,Z,ee,te,ne,B,re,P,O,ie,se,I,ae,oe,Je,Be,ze,v,le,a,ce,ue,de,fe,f,Ye,b,k,C,me,he,_,ge,L,pe,K,F,R,j,ye,be,Te,we,q,Se,De,T,m,tn,nn,rn,Xe,Ze,et,tt,nt,sn,rt,Rt,an,on,ln,cn,it,un,dn,fn,$e,u,st,at,ot,lt,ct,At,W,Ee,mn,hn,ut,Pe,g,Oe,Ie,Mt,gn,Nt,pn,dt,ft,mt,Bt,Pt}from"../chunk-1dv5caj0.js";import{ht,c,U,D,gt,_e,E,xe,Le,Ke,ve,pt,d,V,ke,Fe,yt,je,Ot,It}from"../chunk-kwpppy92.js";import{n,bt,e,H,t,s,Q,qe,yn,_t,Lt,G,bn,Ue,p,Kt,Ft,y,Tn,wt,St,Dt,$t,wn,Sn,Dn,Et,xt,$n,En,jt,qt,Wt,Ut,Vt,vt,Ht,Qt}from"../chunk-8pz2q01r.js";import{Gt,Jt,zt,h,Ve,He,Yt,Ne,Xt}from"../chunk-7xvyccgk.js";export{Et as BelongsToManyRelationBuilder,Ve as BrowserQueryBuilder,h as BrowserQueryError,_t as DEFAULT_SQLITE_PRAGMAS,U as DynamoDBClient,ht as DynamoDBDriverImpl,m as DynamoDBItemBuilder,ke as DynamoDBMigrationDriver,V as DynamoDBMigrationTracker,T as DynamoDBQueryBuilder,it as DynamoDBToolingAdapter,je as EntityQueryBuilder,ot as GENERATED_MARKER,d as MIGRATIONS_TABLE,_e as Model,a as MySQLDriver,ce as PostgresDriver,fe as SQLiteDriver,Nt as Seeder,ue as SingleStoreDriver,Xe as SingleTableManager,sn as SingleTablePatterns,et as SingleTableQueryBuilder,Ze as SingleTableRepository,g as UTC_CLOCK_DEFAULT,de as VitessDriver,G as applySqliteBootstrapPragmas,Bt as auditSchemaDrift,Xt as browserAuth,He as browserQuery,$e as buildDatabaseSchema,ve as buildDynamoDBMigrationPlan,W as buildMigrationPlan,st as buildSchemaMeta,z as cacheClear,X as cacheConfig,Y as cacheStats,Pe as canonicalStorageType,Oe as canonicalizeDefault,Se as checkSchema,St as clearLocalModels,Vt as clearModelRegistry,Qe as clearQueryCache,e as config,Gt as configureBrowser,gt as configureModels,wn as configureOrm,Ke as convertSchemaToDefinition,Yt as createBrowserDb,Ne as createBrowserModel,D as createClient,It as createDynamo,rn as createDynamoDBClient,c as createDynamoDBDriver,nn as createDynamoDBItemBuilder,tn as createDynamoDBQueryBuilder,un as createDynamoDBToolingAdapter,wt as createFakerCompatLayer,Fe as createMigrationDriver,xt as createModel,i as createQueryBuilder,nt as createRepository,tt as createSingleTableManager,$n as createTableFromModel,B as dbInfo,P as dbOptimize,re as dbStats,O as dbWipe,bt as defaultConfig,yn as defineConfig,Ht as defineModel,gn as defineModels,pn as defineSeeder,ne as dumpDatabase,Ot as dynamo,Ct as escapeStringLiteral,k as executeMigration,ie as explain,K as explainAllQueries,ee as exportData,Dt as extractChanges,$t as extractInsertId,Le as extractModelSchema,xe as extractTableDefinition,dt as familyOfDeclared,ft as familyOfSqlType,se as file,Pt as formatSchemaDrift,be as freshDatabase,dn as generateAccessPatterns,F as generateDiagram,Ie as generateDiffOperations,Mt as generateDiffSql,hn as generateDiffSqlString,b as generateMigration,ze as generateModelSource,Ee as generateSql,mn as generateSqlString,qt as getAllModels,Jt as getBrowserConfig,Q as getConfig,Dn as getDatabase,f as getDialectDriver,jt as getModel,Wt as getModelRegistry,t as getPlaceholder,s as getPlaceholders,Ut as hasModel,ut as hashMigrationPlan,E as hashTableDefinition,te as importData,Ft as inflectSingular,I as inspectTable,oe as introspect,v as introspectDatabase,zt as isBrowser,pt as isDefinitionEqual,lt as isGeneratedMigrationSql,At as isLosslessTypeChange,n as isMysqlLike,Zt as iterateAllPivots,at as lastCreatedMigrationFiles,u as loadModels,le as makeModel,ye as makeSeeder,ln as marshallObject,me as migrateGenerate,ge as migrateList,yt as migrateModels,he as migrateRollback,_ as migrateStatus,ct as migrationBody,Be as modelNameForTable,L as modelShow,P as optimizeDatabase,Rt as parseStacksModels,pe as ping,K as queryExplainAll,l as quoteColumnForDialect,en as raw,Qt as registerBrowserModels,vt as registerModel,F as relationDiagram,Sn as releaseOrm,bn as resetConnection,C as resetDatabase,H as resolveDialect,rt as resolveKeyPattern,S as resolvePivot,Lt as resolveSqlitePragmas,J as runBenchmark,j as runSeeder,R as runSeeders,mt as satisfies,Ye as saveMigrationSnapshot,En as seedModel,qe as setConfig,Ge as setQueryCacheMaxSize,L as showModel,y as singularizerFor,Te as sql,Je as sqlTypeToAttr,fn as stacksModelToEntity,N as startConsole,Kt as stripTrailingS,ae as tableInfo,p as tableNameFor,kt as temporalLiteral,Z as tinker,Tn as toDialectPlaceholders,an as toDynamoDBItem,on as toModelInstance,Ue as toTableName,cn as unmarshallItem,we as unsafe,q as validateSchema,De as waitReady,O as wipeDatabase};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bun-query-builder",
3
3
  "type": "module",
4
- "version": "0.2.67",
4
+ "version": "0.2.69",
5
5
  "description": "A simple yet performant query builder for TypeScript. Built with Bun.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Ye,b,k,C}from"./chunk-trp12g5x.js";import"./chunk-55jccfgb.js";import"./chunk-b4hmws4w.js";import"./chunk-7xvyccgk.js";export{k as executeMigration,b as generateMigration,C as resetDatabase,Ye as saveMigrationSnapshot};
File without changes