@earth-app/collegedb 1.1.3 → 1.2.0
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/README.md +373 -48
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -9
- package/dist/index.js.map +8 -7
- package/dist/providers-memory.d.ts +111 -0
- package/dist/providers-memory.d.ts.map +1 -0
- package/dist/router.d.ts +73 -0
- package/dist/router.d.ts.map +1 -1
- package/package.json +10 -9
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var $J=Object.defineProperty;var XJ=(G)=>G;function WJ(G,J){this[G]=XJ.bind(null,J)}var vG=(G,J)=>{for(var Y in J)$J(G,Y,{get:J[Y],enumerable:!0,configurable:!0,set:WJ.bind(J,Y)})};var $G=(G,J)=>()=>(G&&(J=G(G=0)),J);var F;var q=$G(()=>{F=class F extends Error{code;constructor(G,J){super(G);if(this.name="CollegeDBError",this.code=J,Error.captureStackTrace)Error.captureStackTrace(this,F)}}});var XG={};vG(XG,{KVShardMapper:()=>S});class S{kv;hashKeys;hashCache=new Map;mappingCache=new Map;knownShardsCache={shards:null,expiresAt:0};mappingCacheTtlMs;knownShardsCacheTtlMs;constructor(G,J={}){this.kv=G,this.hashKeys=J.hashShardMappings??!0,this.mappingCacheTtlMs=J.mappingCacheTtlMs??HJ,this.knownShardsCacheTtlMs=J.knownShardsCacheTtlMs??OJ}getCachedMapping(G){let J=this.mappingCache.get(G);if(!J)return;if(J.expiresAt<Date.now()){this.mappingCache.delete(G);return}return J.mapping}setCachedMapping(G,J){if(this.mappingCache.size>50000){let Y=this.mappingCache.keys().next().value;if(Y)this.mappingCache.delete(Y)}this.mappingCache.set(G,{mapping:J,expiresAt:Date.now()+this.mappingCacheTtlMs})}async cacheMappingForKeys(G,J){let Y=await Promise.all(G.map((Z)=>this.hashKey(Z)));for(let Z of Y)this.setCachedMapping(Z,J)}getCachedKnownShards(){if(this.knownShardsCache.shards&&this.knownShardsCache.expiresAt>=Date.now())return[...this.knownShardsCache.shards];return null}setCachedKnownShards(G){this.knownShardsCache.shards=[...G],this.knownShardsCache.expiresAt=Date.now()+this.knownShardsCacheTtlMs}async hashKey(G){if(!this.hashKeys)return G;let J=this.hashCache.get(G);if(J)return J;let Z=new TextEncoder().encode(G),$=await crypto.subtle.digest("SHA-256",Z),X=new Uint8Array($),W=Array.from(X).map((H)=>H.toString(16).padStart(2,"0")).join("");if(this.hashCache.size<1e4)this.hashCache.set(G,W);return W}async getShardMapping(G){let J=await this.hashKey(G),Y=this.getCachedMapping(J);if(Y!==void 0)return Y;let Z=`${M}${J}`,$=await this.kv.get(Z,"json");if($)return this.setCachedMapping(J,$),$;let X=await this.kv.get(`${N}${J}`,"json");if(X){let W={shard:X.shard,createdAt:X.createdAt,updatedAt:X.updatedAt,originalKey:this.hashKeys?void 0:G};if(this.setCachedMapping(J,W),this.hashKeys)for(let H of X.keys)this.setCachedMapping(H,W);return W}return this.setCachedMapping(J,null),null}async setShardMapping(G,J,Y=[]){let Z=[G,...Y],$=Date.now(),X={shard:J,createdAt:$,updatedAt:$,originalKey:this.hashKeys?void 0:G};if(Z.length===1){let W=await this.hashKey(G),H=`${M}${W}`;await this.kv.put(H,JSON.stringify(X)),this.setCachedMapping(W,X)}else{let W=await this.hashKey(G),H=`${N}${W}`,O=this.hashKeys?await Promise.all(Z.map((V)=>this.hashKey(V))):Z,U={shard:J,createdAt:$,updatedAt:$,keys:O};await this.kv.put(H,JSON.stringify(U));let _=Z.map(async(V)=>{let L=await this.hashKey(V),I=`${M}${L}`,P={shard:J,createdAt:$,updatedAt:$,originalKey:this.hashKeys?void 0:V};return this.kv.put(I,JSON.stringify(P))});await Promise.all(_),await this.cacheMappingForKeys(Z,X)}}async updateShardMapping(G,J){let Y=await this.getShardMapping(G);if(!Y)throw new F(`No existing mapping found for primary key: ${G}`,"MAPPING_NOT_FOUND");let Z=await this.hashKey(G),$=`${M}${Z}`,X=`${N}${Z}`,W=await this.kv.get(X,"json");if(W){let H=Date.now(),O={...W,shard:J,updatedAt:H};await this.kv.put(X,JSON.stringify(O));let U=W.keys.length>0?this.hashKeys?W.keys:W.keys:[await this.hashKey(G)],_=U.map(async(L)=>{let I=`${M}${L}`,P={...Y,shard:J,updatedAt:H};return this.kv.put(I,JSON.stringify(P))});await Promise.all(_);let V={...Y,shard:J,updatedAt:H};if(this.hashKeys)for(let L of U)this.setCachedMapping(L,V);this.setCachedMapping(Z,V)}else{let H={...Y,shard:J,updatedAt:Date.now()};await this.kv.put($,JSON.stringify(H)),this.setCachedMapping(Z,H)}}async deleteShardMapping(G){let J=await this.hashKey(G),Y=`${M}${J}`,Z=`${N}${J}`,$=await this.kv.get(Z,"json");if($){await this.kv.delete(Z);let X=$.keys.length>0?this.hashKeys?$.keys:$.keys:[await this.hashKey(G)],W=X.map(async(H)=>{let O=`${M}${H}`;return this.kv.delete(O)});if(await Promise.all(W),this.hashKeys)for(let H of X)this.setCachedMapping(H,null);this.setCachedMapping(J,null)}else await this.kv.delete(Y),this.setCachedMapping(J,null)}async getKnownShards(){let G=this.getCachedKnownShards();if(G)return G;let Y=await this.kv.get(zG,"json")||[];return this.setCachedKnownShards(Y),Y}async setKnownShards(G){if(!G||G.length===0)return;let J=[...new Set(G.filter(Boolean))];if(J.length===0)return;await this.kv.put(zG,JSON.stringify(J)),this.setCachedKnownShards(J)}async addKnownShard(G){if(!G)return;let J=await this.getKnownShards();if(!J.includes(G))J.push(G),await this.setKnownShards(J)}async getKeysForShard(G){let J=[],Y=await this.kv.list({prefix:M});for(let $ of Y.keys){let X=await this.kv.get($.name,"json");if(X?.shard===G){let W=$.name.replace(M,"");if(X.originalKey)J.push(X.originalKey);else if(!this.hashKeys)J.push(W)}}let Z=await this.kv.list({prefix:N});for(let $ of Z.keys){let X=await this.kv.get($.name,"json");if(X?.shard===G)J.push(...X.keys)}return[...new Set(J)]}async getShardKeyCounts(){let G={},J=await this.kv.list({prefix:M});for(let Z of J.keys){let $=await this.kv.get(Z.name,"json");if($)G[$.shard]=(G[$.shard]||0)+1}let Y=await this.kv.list({prefix:N});for(let Z of Y.keys){let $=await this.kv.get(Z.name,"json");if($)G[$.shard]=(G[$.shard]||0)+$.keys.length}return G}async clearAllMappings(){let J=(await this.kv.list({prefix:M})).keys.map(($)=>this.kv.delete($.name)),Z=(await this.kv.list({prefix:N})).keys.map(($)=>this.kv.delete($.name));await Promise.all([...J,...Z]),this.mappingCache.clear()}async addLookupKeys(G,J){let Y=await this.getShardMapping(G);if(!Y)throw new F(`No existing mapping found for primary key: ${G}`,"MAPPING_NOT_FOUND");let Z=await this.hashKey(G),$=`${N}${Z}`,X=await this.kv.get($,"json"),W=[G,...J],H=Date.now();if(!X){let _=this.hashKeys?await Promise.all(W.map((V)=>this.hashKey(V))):W;X={shard:Y.shard,createdAt:Y.createdAt,updatedAt:H,keys:_}}else{let _=this.hashKeys?await Promise.all(W.map((V)=>this.hashKey(V))):W;X={...X,updatedAt:H,keys:[...new Set([...X.keys,..._])]}}await this.kv.put($,JSON.stringify(X));let O=J.map(async(_)=>{let V=await this.hashKey(_),L=`${M}${V}`,I={shard:Y.shard,createdAt:Y.createdAt,updatedAt:H,originalKey:this.hashKeys?void 0:_};return this.kv.put(L,JSON.stringify(I))});await Promise.all(O);let U={shard:Y.shard,createdAt:Y.createdAt,updatedAt:H,originalKey:Y.originalKey};await this.cacheMappingForKeys([G,...J],U)}async setShardMappingsBatch(G,J={}){if(G.length===0)return;let Y=Math.max(1,J.concurrency??25),Z=0,$=Array(Math.min(Y,G.length)).fill(null).map(async()=>{while(Z<G.length){let X=Z++,W=G[X];if(!W)continue;await this.setShardMapping(W.primaryKey,W.shard,W.additionalKeys||[])}});await Promise.all($)}async getAllLookupKeys(G){let J=await this.hashKey(G),Y=`${N}${J}`,Z=await this.kv.get(Y,"json");if(Z)return Z.keys;let $=await this.getShardMapping(G);if($)return $.originalKey?[$.originalKey]:[G];throw new F(`No mapping found for key: ${G}`,"MAPPING_NOT_FOUND")}}var M="shard:",N="multikey:",zG="known_shards",HJ=30000,OJ=1e4;var u=$G(()=>{q()});var t={};vG(t,{validateTableForSharding:()=>s,schemaExists:()=>OG,migrateRecord:()=>NG,listTables:()=>h,integrateExistingDatabase:()=>kG,dropSchema:()=>wG,discoverExistingRecordsWithColumns:()=>i,discoverExistingPrimaryKeys:()=>l,createSchemaAcrossShards:()=>BG,createSchema:()=>HG,createMappingsForExistingKeys:()=>CG,clearShardMigrationCache:()=>fG,clearMigrationCache:()=>KG,checkMigrationNeeded:()=>SG,autoDetectAndMigrate:()=>qG});async function MG(G,J,Y){if(G.length===0)return;let Z=Math.max(1,Math.min(J,G.length)),$=0,X=Array(Z).fill(null).map(async()=>{while($<G.length){let W=$++,H=G[W];if(H===void 0)continue;await Y(H,W)}});await Promise.all(X)}function UJ(G,J,Y,Z){let $=Y.length;switch(Z){case"hash":{let X=0;for(let H=0;H<G.length;H++){let O=G.charCodeAt(H);X=(X<<5)-X+O,X=X&X}let W=Math.abs(X)%$;return Y[W]}case"random":return Y[Math.floor(Math.random()*$)];default:return Y[J%$]}}async function HG(G,J){let Y=J.split(";").map((Z)=>Z.trim()).filter((Z)=>Z.length>0&&!Z.startsWith("--"));for(let Z of Y)try{await G.prepare(Z).run()}catch($){throw console.error("Failed to execute schema statement:",Z,$),new F(`Schema migration failed: ${$}`,"SCHEMA_MIGRATION_FAILED")}}async function BG(G,J){let Y=Object.entries(G).map(([Z,$])=>{return HG($,J).catch((X)=>{throw new F(`Failed to create schema on shard ${Z}: ${X.message}`,"SCHEMA_CREATION_FAILED")})});await Promise.all(Y)}async function OG(G,J){try{return await G.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(J).first()!==null}catch{return!1}}async function wG(G,...J){for(let Y of J)try{await G.prepare(`DROP TABLE IF EXISTS ${Y}`).run()}catch(Z){console.error(`Failed to drop table ${Y}:`,Z)}}async function h(G){try{return(await G.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all()).results.map((Y)=>Y.name)}catch{return[]}}async function NG(G,J,Y,Z){let $=await G.prepare(`SELECT * FROM ${Z} WHERE id = ?`).bind(Y).first();if(!$)throw new F(`Record with primary key ${Y} not found in source database`,"RECORD_NOT_FOUND");if(!await OG(J,Z))await HG(J,Z);let X=Object.keys($),W=X.map(()=>"?").join(", "),H=X.map((U)=>$[U]),O=`INSERT OR REPLACE INTO ${Z} (${X.join(", ")}) VALUES (${W})`;await J.prepare(O).bind(...H).run(),await G.prepare(`DELETE FROM ${Z} WHERE id = ?`).bind(Y).run()}async function l(G,J,Y="id"){try{return(await G.prepare(`SELECT ${Y} FROM ${J}`).all()).results.map(($)=>String($[Y]))}catch(Z){throw new F(`Failed to discover primary keys in table ${J}: ${Z}`,"DISCOVERY_FAILED")}}async function i(G,J,Y="id"){try{let Z=`${J}_columns`,$;if(WG.has(Z))$=WG.get(Z).map((O)=>O.name);else{let U=(await G.prepare(`PRAGMA table_info(${J})`).all()).results.map((_)=>({name:_.name,type:_.type}));WG.set(Z,U),$=U.map((_)=>_.name)}let X=[Y];if($.includes("username"))X.push("username");if($.includes("email"))X.push("email");if($.includes("name"))X.push("name");let W=`SELECT ${X.join(", ")} FROM ${J}`;return(await G.prepare(W).all()).results}catch(Z){throw new F(`Failed to discover records with columns in table ${J}: ${Z}`,"DISCOVERY_FAILED")}}async function CG(G,J,Y,Z,$={}){if(G.length===0||J.length===0)return;let X=Math.max(1,$.concurrency??25),W=G.map((H,O)=>({primaryKey:H,shard:UJ(H,O,J,Y)}));await Z.setShardMappingsBatch(W,{concurrency:X})}async function s(G,J,Y){let Z=[],$=0;try{if(!await G.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(J).first())return Z.push(`Table '${J}' does not exist`),{isValid:!1,tableName:J,primaryKeyColumn:Y,recordCount:0,issues:Z};if(!(await G.prepare(`PRAGMA table_info(${J})`).all()).results.some((U)=>U.name===Y&&U.pk===1))Z.push(`Primary key column '${Y}' not found or not set as primary key`);if($=(await G.prepare(`SELECT COUNT(*) as count FROM ${J}`).first())?.count||0,$===0)Z.push(`Table '${J}' is empty`)}catch(X){Z.push(`Database validation error: ${X}`)}return{isValid:Z.length===0,tableName:J,primaryKeyColumn:Y,recordCount:$,issues:Z}}async function kG(G,J,Y,Z={}){let{tables:$,primaryKeyColumn:X="id",strategy:W="hash",addShardMappingsTable:H=!0,dryRun:O=!1,migrateOtherColumns:U=!1,concurrency:_=25}=Z,V=Math.max(1,_),L=[],I=0,P=0,x=0;try{let A=($||await h(G)).filter((j)=>j!=="shard_mappings");for(let j of A)try{let R=await s(G,j,X);if(!R.isValid){L.push(`Table ${j}: ${R.issues.join(", ")}`);continue}if(U){let D=await i(G,j,X);if(D.length===0){L.push(`Table ${j} has no records to process`);continue}if(!O){let E=D.map((Q)=>{let YG=String(Q[X]),b=[];if(Q.username&&typeof Q.username==="string")b.push(`username:${Q.username}`);if(Q.email&&typeof Q.email==="string")b.push(`email:${Q.email}`);if(Q.name&&typeof Q.name==="string")b.push(`name:${Q.name}`);return{primaryKey:YG,shard:J,additionalKeys:b}});await Y.setShardMappingsBatch(E,{concurrency:V}),x+=E.length}P+=D.length}else{let D=await l(G,j,X);if(D.length===0){L.push(`Table ${j} has no records to process`);continue}if(!O){let E=D.map((Q)=>({primaryKey:Q,shard:J}));await Y.setShardMappingsBatch(E,{concurrency:V}),x+=E.length}P+=D.length}I++}catch(R){L.push(`Failed to process table ${j}: ${R}`)}if(H&&!O){if(!(await h(G)).includes("shard_mappings"))await G.prepare(`
|
|
1
|
+
var jY=Object.defineProperty;var AY=(J)=>J;function VY(J,Y){this[J]=AY.bind(null,Y)}var xJ=(J,Y)=>{for(var Z in Y)jY(J,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:VY.bind(Y,Z)})};var UJ=(J,Y)=>()=>(J&&(Y=J(J=0)),Y);var j;var q=UJ(()=>{j=class j extends Error{code;constructor(J,Y){super(J);if(this.name="CollegeDBError",this.code=Y,Error.captureStackTrace)Error.captureStackTrace(this,j)}}});var HJ={};xJ(HJ,{KVShardMapper:()=>K});class K{kv;hashKeys;hashCache=new Map;mappingCache=new Map;knownShardsCache={shards:null,expiresAt:0};mappingCacheTtlMs;knownShardsCacheTtlMs;constructor(J,Y={}){this.kv=J,this.hashKeys=Y.hashShardMappings??!0,this.mappingCacheTtlMs=Y.mappingCacheTtlMs??LY,this.knownShardsCacheTtlMs=Y.knownShardsCacheTtlMs??EY}getCachedMapping(J){let Y=this.mappingCache.get(J);if(!Y)return;if(Y.expiresAt<Date.now()){this.mappingCache.delete(J);return}return Y.mapping}setCachedMapping(J,Y){if(this.mappingCache.size>50000){let Z=this.mappingCache.keys().next().value;if(Z)this.mappingCache.delete(Z)}this.mappingCache.set(J,{mapping:Y,expiresAt:Date.now()+this.mappingCacheTtlMs})}async cacheMappingForKeys(J,Y){let Z=await Promise.all(J.map(($)=>this.hashKey($)));for(let $ of Z)this.setCachedMapping($,Y)}getCachedKnownShards(){if(this.knownShardsCache.shards&&this.knownShardsCache.expiresAt>=Date.now())return[...this.knownShardsCache.shards];return null}setCachedKnownShards(J){this.knownShardsCache.shards=[...J],this.knownShardsCache.expiresAt=Date.now()+this.knownShardsCacheTtlMs}async hashKey(J){if(!this.hashKeys)return J;let Y=this.hashCache.get(J);if(Y)return Y;let $=new TextEncoder().encode(J),X=await crypto.subtle.digest("SHA-256",$),W=new Uint8Array(X),G=Array.from(W).map((U)=>U.toString(16).padStart(2,"0")).join("");if(this.hashCache.size<1e4)this.hashCache.set(J,G);return G}async getShardMapping(J){let Y=await this.hashKey(J),Z=this.getCachedMapping(Y);if(Z!==void 0)return Z;let $=`${N}${Y}`,X=await this.kv.get($,"json");if(X)return this.setCachedMapping(Y,X),X;let W=await this.kv.get(`${k}${Y}`,"json");if(W){let G={shard:W.shard,createdAt:W.createdAt,updatedAt:W.updatedAt,originalKey:this.hashKeys?void 0:J};if(this.setCachedMapping(Y,G),this.hashKeys)for(let U of W.keys)this.setCachedMapping(U,G);return G}return this.setCachedMapping(Y,null),null}async setShardMapping(J,Y,Z=[]){let $=[J,...Z],X=Date.now(),W={shard:Y,createdAt:X,updatedAt:X,originalKey:this.hashKeys?void 0:J};if($.length===1){let G=await this.hashKey(J),U=`${N}${G}`;await this.kv.put(U,JSON.stringify(W)),this.setCachedMapping(G,W)}else{let G=await this.hashKey(J),U=`${k}${G}`,H=this.hashKeys?await Promise.all($.map((F)=>this.hashKey(F))):$,_={shard:Y,createdAt:X,updatedAt:X,keys:H};await this.kv.put(U,JSON.stringify(_));let O=$.map(async(F)=>{let A=await this.hashKey(F),E=`${N}${A}`,I={shard:Y,createdAt:X,updatedAt:X,originalKey:this.hashKeys?void 0:F};return this.kv.put(E,JSON.stringify(I))});await Promise.all(O),await this.cacheMappingForKeys($,W)}}async updateShardMapping(J,Y){let Z=await this.getShardMapping(J);if(!Z)throw new j(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");let $=await this.hashKey(J),X=`${N}${$}`,W=`${k}${$}`,G=await this.kv.get(W,"json");if(G){let U=Date.now(),H={...G,shard:Y,updatedAt:U};await this.kv.put(W,JSON.stringify(H));let _=G.keys.length>0?this.hashKeys?G.keys:G.keys:[await this.hashKey(J)],O=_.map(async(A)=>{let E=`${N}${A}`,I={...Z,shard:Y,updatedAt:U};return this.kv.put(E,JSON.stringify(I))});await Promise.all(O);let F={...Z,shard:Y,updatedAt:U};if(this.hashKeys)for(let A of _)this.setCachedMapping(A,F);this.setCachedMapping($,F)}else{let U={...Z,shard:Y,updatedAt:Date.now()};await this.kv.put(X,JSON.stringify(U)),this.setCachedMapping($,U)}}async deleteShardMapping(J){let Y=await this.hashKey(J),Z=`${N}${Y}`,$=`${k}${Y}`,X=await this.kv.get($,"json");if(X){await this.kv.delete($);let W=X.keys.length>0?this.hashKeys?X.keys:X.keys:[await this.hashKey(J)],G=W.map(async(U)=>{let H=`${N}${U}`;return this.kv.delete(H)});if(await Promise.all(G),this.hashKeys)for(let U of W)this.setCachedMapping(U,null);this.setCachedMapping(Y,null)}else await this.kv.delete(Z),this.setCachedMapping(Y,null)}async getKnownShards(){let J=this.getCachedKnownShards();if(J)return J;let Z=await this.kv.get(vJ,"json")||[];return this.setCachedKnownShards(Z),Z}async setKnownShards(J){if(!J||J.length===0)return;let Y=[...new Set(J.filter(Boolean))];if(Y.length===0)return;await this.kv.put(vJ,JSON.stringify(Y)),this.setCachedKnownShards(Y)}async addKnownShard(J){if(!J)return;let Y=await this.getKnownShards();if(!Y.includes(J))Y.push(J),await this.setKnownShards(Y)}async getKeysForShard(J){let Y=[],Z=await this.kv.list({prefix:N});for(let X of Z.keys){let W=await this.kv.get(X.name,"json");if(W?.shard===J){let G=X.name.replace(N,"");if(W.originalKey)Y.push(W.originalKey);else if(!this.hashKeys)Y.push(G)}}let $=await this.kv.list({prefix:k});for(let X of $.keys){let W=await this.kv.get(X.name,"json");if(W?.shard===J)Y.push(...W.keys)}return[...new Set(Y)]}async getShardKeyCounts(){let J={},Y=await this.kv.list({prefix:N});for(let $ of Y.keys){let X=await this.kv.get($.name,"json");if(X)J[X.shard]=(J[X.shard]||0)+1}let Z=await this.kv.list({prefix:k});for(let $ of Z.keys){let X=await this.kv.get($.name,"json");if(X)J[X.shard]=(J[X.shard]||0)+X.keys.length}return J}async clearAllMappings(){let Y=(await this.kv.list({prefix:N})).keys.map((X)=>this.kv.delete(X.name)),$=(await this.kv.list({prefix:k})).keys.map((X)=>this.kv.delete(X.name));await Promise.all([...Y,...$]),this.mappingCache.clear()}async addLookupKeys(J,Y){let Z=await this.getShardMapping(J);if(!Z)throw new j(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");let $=await this.hashKey(J),X=`${k}${$}`,W=await this.kv.get(X,"json"),G=[J,...Y],U=Date.now();if(!W){let O=this.hashKeys?await Promise.all(G.map((F)=>this.hashKey(F))):G;W={shard:Z.shard,createdAt:Z.createdAt,updatedAt:U,keys:O}}else{let O=this.hashKeys?await Promise.all(G.map((F)=>this.hashKey(F))):G;W={...W,updatedAt:U,keys:[...new Set([...W.keys,...O])]}}await this.kv.put(X,JSON.stringify(W));let H=Y.map(async(O)=>{let F=await this.hashKey(O),A=`${N}${F}`,E={shard:Z.shard,createdAt:Z.createdAt,updatedAt:U,originalKey:this.hashKeys?void 0:O};return this.kv.put(A,JSON.stringify(E))});await Promise.all(H);let _={shard:Z.shard,createdAt:Z.createdAt,updatedAt:U,originalKey:Z.originalKey};await this.cacheMappingForKeys([J,...Y],_)}async setShardMappingsBatch(J,Y={}){if(J.length===0)return;let Z=Math.max(1,Y.concurrency??25),$=0,X=Array(Math.min(Z,J.length)).fill(null).map(async()=>{while($<J.length){let W=$++,G=J[W];if(!G)continue;await this.setShardMapping(G.primaryKey,G.shard,G.additionalKeys||[])}});await Promise.all(X)}async getAllLookupKeys(J){let Y=await this.hashKey(J),Z=`${k}${Y}`,$=await this.kv.get(Z,"json");if($)return $.keys;let X=await this.getShardMapping(J);if(X)return X.originalKey?[X.originalKey]:[J];throw new j(`No mapping found for key: ${J}`,"MAPPING_NOT_FOUND")}}var N="shard:",k="multikey:",vJ="known_shards",LY=30000,EY=1e4;var c=UJ(()=>{q()});var r={};xJ(r,{validateTableForSharding:()=>a,schemaExists:()=>FJ,migrateRecord:()=>SJ,listTables:()=>p,integrateExistingDatabase:()=>fJ,dropSchema:()=>qJ,discoverExistingRecordsWithColumns:()=>t,discoverExistingPrimaryKeys:()=>i,createSchemaAcrossShards:()=>kJ,createSchema:()=>OJ,createMappingsForExistingKeys:()=>KJ,clearShardMigrationCache:()=>yJ,clearMigrationCache:()=>pJ,checkMigrationNeeded:()=>hJ,autoDetectAndMigrate:()=>bJ});async function CJ(J,Y,Z){if(J.length===0)return;let $=Math.max(1,Math.min(Y,J.length)),X=0,W=Array($).fill(null).map(async()=>{while(X<J.length){let G=X++,U=J[G];if(U===void 0)continue;await Z(U,G)}});await Promise.all(W)}function IY(J,Y,Z,$){let X=Z.length;switch($){case"hash":{let W=0;for(let U=0;U<J.length;U++){let H=J.charCodeAt(U);W=(W<<5)-W+H,W=W&W}let G=Math.abs(W)%X;return Z[G]}case"random":return Z[Math.floor(Math.random()*X)];default:return Z[Y%X]}}async function OJ(J,Y){let Z=Y.split(";").map(($)=>$.trim()).filter(($)=>$.length>0&&!$.startsWith("--"));for(let $ of Z)try{await J.prepare($).run()}catch(X){throw console.error("Failed to execute schema statement:",$,X),new j(`Schema migration failed: ${X}`,"SCHEMA_MIGRATION_FAILED")}}async function kJ(J,Y){let Z=Object.entries(J).map(([$,X])=>{return OJ(X,Y).catch((W)=>{throw new j(`Failed to create schema on shard ${$}: ${W.message}`,"SCHEMA_CREATION_FAILED")})});await Promise.all(Z)}async function FJ(J,Y){try{return await J.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(Y).first()!==null}catch{return!1}}async function qJ(J,...Y){for(let Z of Y)try{await J.prepare(`DROP TABLE IF EXISTS ${Z}`).run()}catch($){console.error(`Failed to drop table ${Z}:`,$)}}async function p(J){try{return(await J.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all()).results.map((Z)=>Z.name)}catch{return[]}}async function SJ(J,Y,Z,$){let X=await J.prepare(`SELECT * FROM ${$} WHERE id = ?`).bind(Z).first();if(!X)throw new j(`Record with primary key ${Z} not found in source database`,"RECORD_NOT_FOUND");if(!await FJ(Y,$))await OJ(Y,$);let W=Object.keys(X),G=W.map(()=>"?").join(", "),U=W.map((_)=>X[_]),H=`INSERT OR REPLACE INTO ${$} (${W.join(", ")}) VALUES (${G})`;await Y.prepare(H).bind(...U).run(),await J.prepare(`DELETE FROM ${$} WHERE id = ?`).bind(Z).run()}async function i(J,Y,Z="id"){try{return(await J.prepare(`SELECT ${Z} FROM ${Y}`).all()).results.map((X)=>String(X[Z]))}catch($){throw new j(`Failed to discover primary keys in table ${Y}: ${$}`,"DISCOVERY_FAILED")}}async function t(J,Y,Z="id"){try{let $=`${Y}_columns`,X;if(_J.has($))X=_J.get($).map((H)=>H.name);else{let _=(await J.prepare(`PRAGMA table_info(${Y})`).all()).results.map((O)=>({name:O.name,type:O.type}));_J.set($,_),X=_.map((O)=>O.name)}let W=[Z];if(X.includes("username"))W.push("username");if(X.includes("email"))W.push("email");if(X.includes("name"))W.push("name");let G=`SELECT ${W.join(", ")} FROM ${Y}`;return(await J.prepare(G).all()).results}catch($){throw new j(`Failed to discover records with columns in table ${Y}: ${$}`,"DISCOVERY_FAILED")}}async function KJ(J,Y,Z,$,X={}){if(J.length===0||Y.length===0)return;let W=Math.max(1,X.concurrency??25),G=J.map((U,H)=>({primaryKey:U,shard:IY(U,H,Y,Z)}));await $.setShardMappingsBatch(G,{concurrency:W})}async function a(J,Y,Z){let $=[],X=0;try{if(!await J.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(Y).first())return $.push(`Table '${Y}' does not exist`),{isValid:!1,tableName:Y,primaryKeyColumn:Z,recordCount:0,issues:$};if(!(await J.prepare(`PRAGMA table_info(${Y})`).all()).results.some((_)=>_.name===Z&&_.pk===1))$.push(`Primary key column '${Z}' not found or not set as primary key`);if(X=(await J.prepare(`SELECT COUNT(*) as count FROM ${Y}`).first())?.count||0,X===0)$.push(`Table '${Y}' is empty`)}catch(W){$.push(`Database validation error: ${W}`)}return{isValid:$.length===0,tableName:Y,primaryKeyColumn:Z,recordCount:X,issues:$}}async function fJ(J,Y,Z,$={}){let{tables:X,primaryKeyColumn:W="id",strategy:G="hash",addShardMappingsTable:U=!0,dryRun:H=!1,migrateOtherColumns:_=!1,concurrency:O=25}=$,F=Math.max(1,O),A=[],E=0,I=0,M=0;try{let V=(X||await p(J)).filter((L)=>L!=="shard_mappings");for(let L of V)try{let z=await a(J,L,W);if(!z.isValid){A.push(`Table ${L}: ${z.issues.join(", ")}`);continue}if(_){let R=await t(J,L,W);if(R.length===0){A.push(`Table ${L} has no records to process`);continue}if(!H){let P=R.map((Q)=>{let WJ=String(Q[W]),h=[];if(Q.username&&typeof Q.username==="string")h.push(`username:${Q.username}`);if(Q.email&&typeof Q.email==="string")h.push(`email:${Q.email}`);if(Q.name&&typeof Q.name==="string")h.push(`name:${Q.name}`);return{primaryKey:WJ,shard:Y,additionalKeys:h}});await Z.setShardMappingsBatch(P,{concurrency:F}),M+=P.length}I+=R.length}else{let R=await i(J,L,W);if(R.length===0){A.push(`Table ${L} has no records to process`);continue}if(!H){let P=R.map((Q)=>({primaryKey:Q,shard:Y}));await Z.setShardMappingsBatch(P,{concurrency:F}),M+=P.length}I+=R.length}E++}catch(z){A.push(`Failed to process table ${L}: ${z}`)}if(U&&!H){if(!(await p(J)).includes("shard_mappings"))await J.prepare(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS shard_mappings (
|
|
3
3
|
primary_key TEXT PRIMARY KEY,
|
|
4
4
|
shard_name TEXT NOT NULL,
|
|
5
5
|
created_at INTEGER NOT NULL,
|
|
6
6
|
updated_at INTEGER NOT NULL
|
|
7
|
-
);`.trim()).run()}if(!
|
|
8
|
-
SELECT ${
|
|
9
|
-
ORDER BY ${
|
|
10
|
-
LIMIT ?`.trim()).bind(
|
|
7
|
+
);`.trim()).run()}if(!H)await Z.addKnownShard(Y)}catch(C){A.push(`Integration failed: ${C}`)}return{success:A.length===0||A.length>0&&E>0,shardName:Y,tablesProcessed:E,totalRecords:I,mappingsCreated:M,issues:A}}async function bJ(J,Y,Z,$={}){let{primaryKeyColumn:X="id",tablesToCheck:W,skipCache:G=!1,maxRecordsToCheck:U=1000,migrateOtherColumns:H=!1,concurrency:_=Z.migrationConcurrency??25}=$,O=Math.max(1,_),F=`${Y}_migration_check`;if(!G&&f.has(F))return{migrationNeeded:!1,migrationPerformed:!1,recordsMigrated:0,tablesProcessed:0,issues:[]};let A=[],E=0,I=0,M=!1,C=!1;try{let{KVShardMapper:V}=await Promise.resolve().then(() => (c(),HJ)),L=new V(Z.kv,{hashShardMappings:Z.hashShardMappings,mappingCacheTtlMs:Z.mappingCacheTtlMs,knownShardsCacheTtlMs:Z.knownShardsCacheTtlMs}),z=await p(J),R=W||z.filter((P)=>P!=="shard_mappings"&&!P.startsWith("sqlite_")&&P!=="sqlite_sequence");if(R.length===0)return f.set(F,!0),{migrationNeeded:!1,migrationPerformed:!1,recordsMigrated:0,tablesProcessed:0,issues:[]};for(let P of R)try{let Q=await a(J,P,X);if(!Q.isValid||Q.recordCount===0)continue;let WJ=Math.min(U,Q.recordCount),h=await J.prepare(`
|
|
8
|
+
SELECT ${X} FROM ${P}
|
|
9
|
+
ORDER BY ${X}
|
|
10
|
+
LIMIT ?`.trim()).bind(WJ).all(),NJ=0,OY=h.results.slice(0,10).map(async(S)=>{let w=String(S[X]);return{key:w,mapping:await L.getShardMapping(w)}}),FY=await Promise.all(OY);for(let S of FY)if(!S.mapping)NJ++,M=!0;if(NJ>0){if(Z.debug)console.log(`Auto-migrating table ${P} in shard ${Y} (${Q.recordCount} records)`);if(H){let S=await t(J,P,X),w=[];if(await CJ(S,O,async(B)=>{let GJ=String(B[X]);if(await L.getShardMapping(GJ))return;let s=[];if(B.username&&typeof B.username==="string")s.push(`username:${B.username}`);if(B.email&&typeof B.email==="string")s.push(`email:${B.email}`);if(B.name&&typeof B.name==="string")s.push(`name:${B.name}`);w.push({primaryKey:GJ,shard:Y,additionalKeys:s})}),w.length>0)await L.setShardMappingsBatch(w,{concurrency:O});E+=w.length}else{let S=await i(J,P,X),w=[];if(await CJ(S,O,async(B)=>{if(!await L.getShardMapping(B))w.push({primaryKey:B,shard:Y})}),w.length>0)await L.setShardMappingsBatch(w,{concurrency:O});E+=w.length}if(I++,C=!0,Z.debug)console.log(`Auto-migrated ${E} records from table ${P}`)}}catch(Q){A.push(`Auto-migration failed for table ${P}: ${Q}`)}if(C){if(await L.addKnownShard(Y),!z.includes("shard_mappings"))await J.prepare(`CREATE TABLE IF NOT EXISTS shard_mappings (
|
|
11
11
|
primary_key TEXT PRIMARY KEY,
|
|
12
12
|
shard_name TEXT NOT NULL,
|
|
13
13
|
created_at INTEGER NOT NULL,
|
|
14
14
|
updated_at INTEGER NOT NULL
|
|
15
15
|
);
|
|
16
|
-
`).run()}if(K.set(V,!0),w&&Y.debug)console.log(`Auto-migration completed for shard ${J}: ${I} records from ${P} tables`)}catch(A){L.push(`Auto-migration error: ${A}`)}return{migrationNeeded:x,migrationPerformed:w,recordsMigrated:I,tablesProcessed:P,issues:L}}async function SG(G,J,Y){let Z=`${J}_migration_check`;if(K.has(Z))return!1;try{let $=await h(G);if($.includes("shard_mappings"))return K.set(Z,!0),!1;let{KVShardMapper:W}=await Promise.resolve().then(() => (u(),XG)),H=new W(Y.kv,{hashShardMappings:Y.hashShardMappings,mappingCacheTtlMs:Y.mappingCacheTtlMs,knownShardsCacheTtlMs:Y.knownShardsCacheTtlMs}),O=$.filter((U)=>U!=="shard_mappings"&&!U.startsWith("sqlite_")&&U!=="sqlite_sequence");for(let U of O.slice(0,3))try{if(((await G.prepare(`SELECT COUNT(*) as count FROM ${U} LIMIT 1`).first())?.count||0)>0){let L=await G.prepare(`SELECT id FROM ${U} LIMIT 1`).first();if(L){let I=String(L.id);if(!await H.getShardMapping(I))return!0}}}catch{continue}return!1}catch{return!1}}function KG(){K.clear()}function fG(G){let J=`${G}_migration_check`;K.delete(J)}var K,WG;var g=$G(()=>{q();K=new Map,WG=new Map});q();u();var c=null,p=null,y=new Map;function C(G){if(!p)p=new S(G.kv,{hashShardMappings:G.hashShardMappings,mappingCacheTtlMs:G.mappingCacheTtlMs,knownShardsCacheTtlMs:G.knownShardsCacheTtlMs});return p}function _J(G){c=G,p=new S(G.kv,{hashShardMappings:G.hashShardMappings,mappingCacheTtlMs:G.mappingCacheTtlMs,knownShardsCacheTtlMs:G.knownShardsCacheTtlMs}),y.clear();try{let J=C(G);Promise.resolve().then(async()=>{let Y=await J.getKnownShards(),Z=Array.from(new Set([...Y,...Object.keys(G.shards)]));await J.setKnownShards(Z)}).catch(()=>{return})}catch{}if(G.shards&&Object.keys(G.shards).length>0&&!G.disableAutoMigration)yG(G).catch((J)=>{console.warn("Background auto-migration failed:",J)})}async function pG(G){c=G,p=new S(G.kv,{hashShardMappings:G.hashShardMappings,mappingCacheTtlMs:G.mappingCacheTtlMs,knownShardsCacheTtlMs:G.knownShardsCacheTtlMs}),y.clear();try{let J=C(G),Y=await J.getKnownShards(),Z=Array.from(new Set([...Y,...Object.keys(G.shards)]));await J.setKnownShards(Z)}catch{}if(G.shards&&Object.keys(G.shards).length>0&&!G.disableAutoMigration)try{await yG(G)}catch(J){console.warn("Auto migration failed:",J)}}async function VJ(G,J){return await pG(G),await J()}async function yG(G){try{let{autoDetectAndMigrate:J}=await Promise.resolve().then(() => (g(),t)),Y=Object.keys(G.shards);if(G.debug)console.log(`\uD83D\uDD0D Checking ${Y.length} shards for existing data...`);let Z=Y.map(async(W)=>{let H=G.shards[W];if(!H)return null;try{let O=await J(H,W,G,{maxRecordsToCheck:1000});return{shardName:W,...O}}catch(O){return console.warn(`Auto-migration failed for shard ${W}:`,O),null}}),X=(await Promise.all(Z)).filter((W)=>W?.migrationPerformed);if(G.debug)if(X.length>0){let W=X.reduce((H,O)=>H+(O?.recordsMigrated||0),0);console.log(`\uD83C\uDF89 Auto-migration completed! Migrated ${W} records across ${X.length} shards`),X.forEach((H)=>{if(H)console.log(` ✅ ${H.shardName}: ${H.recordsMigrated} records from ${H.tablesProcessed} tables`)})}else console.log("✅ All shards ready - no migration needed")}catch(J){console.warn("Background auto-migration setup failed:",J)}}function FJ(){c=null,p=null,y.clear()}function T(){if(!c)throw new F("CollegeDB not initialized. Call initialize() first.","NOT_INITIALIZED");return c}function LJ(G){let J=G.trim().toUpperCase();if(J.startsWith("SELECT")||J.startsWith("VALUES")||J.startsWith("TABLE")||J.startsWith("PRAGMA")||J.startsWith("EXPLAIN")||J.startsWith("WITH")||J.startsWith("SHOW"))return"read";return"write"}function AJ(G,J){let Y=G.strategy||"hash";if(typeof Y==="string")return Y;let Z=Y;return Z[J]||Z.write||Z.read||"hash"}function jJ(G,J){if(G===J)return 0;let Y={wnam:{lat:37.7749,lon:-122.4194},enam:{lat:40.7128,lon:-74.006},weur:{lat:51.5074,lon:-0.1278},eeur:{lat:52.52,lon:13.405},apac:{lat:35.6762,lon:139.6503},oc:{lat:-33.8688,lon:151.2093},me:{lat:25.2048,lon:55.2708},af:{lat:-26.2041,lon:28.0473}},Z=Y[G],$=Y[J],X=Z.lat-$.lat,W=Z.lon-$.lon;return Math.sqrt(X*X+W*W)}function IJ(G){let J=G.cf;if(!J||!J.country)return"wnam";let{country:Y,continent:Z}=J;if(["US","CA","MX"].includes(Y)){let $=J.region||J.regionCode||"",X=J.timezone||"";if($.includes("CA")||$.includes("WA")||$.includes("OR")||$.includes("NV")||$.includes("AZ")||$.includes("UT")||X.includes("Pacific")||X.includes("America/Los_Angeles"))return"wnam";return"enam"}if(["GL","PM","BM"].includes(Y))return"enam";if(["GB","IE","FR","ES","PT","NL","BE","LU","CH","AT","IT"].includes(Y))return"weur";if(["DE","PL","CZ","SK","HU","SI","HR","BA","RS","ME","MK","AL","BG","RO","MD","UA","BY","LT","LV","EE","FI","SE","NO","DK","IS"].includes(Y))return"eeur";if(Y==="RU")return"eeur";if(["JP","KR","CN","HK","TW","MO","MN","KP"].includes(Y))return"apac";if(["TH","VN","SG","MY","ID","PH","BN","KH","LA","MM","TL","IN","PK","BD","LK","NP","BT","MV","AF"].includes(Y))return"apac";if(["AU","NZ","PG","FJ","NC","VU","SB","WS","TO","KI","NR","PW","FM","MH","TV"].includes(Y))return"oc";if(["AE","SA","QA","KW","BH","OM","YE","IQ","IR","SY","LB","JO","IL","PS","TR","CY"].includes(Y))return"me";if(Z==="AF"||["EG","LY","TN","DZ","MA","SD","SS","ET","ER","DJ","SO"].includes(Y))return"af";if(["KZ","UZ","TM","TJ","KG"].includes(Y))return"eeur";if(Z==="SA"||["BR","AR","CL","PE","CO","VE","EC","BO","PY","UY","GY","SR","GF"].includes(Y))return"enam";if(["GT","BZ","SV","HN","NI","CR","PA","CU","JM","HT","DO","PR","TT","BB","GD","VC","LC","DM","AG","KN"].includes(Y))return"enam";return"wnam"}function PJ(G){if(typeof G==="string")return G;return G.region||"wnam"}async function a(G){try{let[J,Y]=await Promise.all([G.prepare("PRAGMA page_count").first(),G.prepare("PRAGMA page_size").first()]);if(!J?.page_count||!Y?.page_size)throw new F("Failed to retrieve database size information","SIZE_QUERY_FAILED");return J.page_count*Y.page_size}catch(J){throw new F(`Failed to get database size: ${J instanceof Error?J.message:"Unknown error"}`,"SIZE_QUERY_FAILED")}}async function QJ(G,J){let Y=Math.max(0,J.sizeCacheTtlMs??30000),Z=y.get(G);if(Z&&Z.expiresAt>=Date.now())return Z.size;let $=J.shards[G];if(!$)throw new F(`Shard ${G} not found in configuration`,"SHARD_NOT_FOUND");let X=await a($);if(Y>0)y.set(G,{size:X,expiresAt:Date.now()+Y});return X}async function EJ(G,J){if(typeof J.maxDatabaseSize!=="number"||!Number.isFinite(J.maxDatabaseSize)||J.maxDatabaseSize<=0)return G;let Y=J.maxDatabaseSize,$=(await Promise.allSettled(G.map(async(X)=>{let W=await QJ(X,J);return{shard:X,size:W,withinLimit:W<Y}}))).filter((X)=>X.status==="fulfilled"&&X.value.withinLimit).map((X)=>X.value.shard);if($.length===0){if(J.debug)console.warn("All shards exceed maxDatabaseSize limit. Allowing allocation to prevent failure.");return G}if(J.debug&&$.length<G.length){let X=G.filter((W)=>!$.includes(W));console.log(`Excluded ${X.length} shards due to size limits: ${X.join(", ")}`)}return $}function TJ(G,J,Y,Z){let $=J.filter((_)=>Y[_]);if($.length===0){let _=0;for(let L=0;L<Z.length;L++){let I=Z.charCodeAt(L);_=(_<<5)-_+I,_=_&_}let V=Math.abs(_)%J.length;return J[V]}let X=$.map((_)=>{let V=Y[_],L=jJ(G,PJ(V)),I=typeof V==="object"?V.priority||1:1,P=L-I*0.1;return{shard:_,score:P,distance:L,priority:I}});X.sort((_,V)=>_.score-V.score);let W=X[0].score,H=X.filter((_)=>Math.abs(_.score-W)<0.01);if(H.length===1)return H[0].shard;let O=0;for(let _=0;_<Z.length;_++){let V=Z.charCodeAt(_);O=(O<<5)-O+V,O=O&O}let U=Math.abs(O)%H.length;return H[U].shard}function m(G,J,Y,Z){switch(G){case"hash":{let $=0;for(let W=0;W<J.length;W++){let H=J.charCodeAt(W);$=($<<5)-$+H,$=$&$}let X=Math.abs($)%Y.length;return Y[X]||Y[0]}case"location":{if(!Z.targetRegion)return m("hash",J,Y,Z);return TJ(Z.targetRegion,Y,Z.shardLocations||{},J)}case"random":return Y[Math.floor(Math.random()*Y.length)]||Y[0];default:return m("hash",J,Y,Z)}}async function uG(G,J="write"){let Y=T(),Z=C(Y),$=await Z.getShardMapping(G);if($)return $.shard;let X=Object.keys(Y.shards);if(X.length===0)throw new F("No shards configured","NO_SHARDS");let W=await EJ(X,Y),H,O=AJ(Y,J);if(Y.coordinator)try{let U=Y.coordinator.idFromName("default"),V=await Y.coordinator.get(U).fetch("http://coordinator/allocate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primaryKey:G,strategy:O,operationType:J,targetRegion:Y.targetRegion,shardLocations:Y.shardLocations,availableShards:W})});if(V.ok)H=(await V.json()).shard;else H=m(O,G,W,Y)}catch(U){console.warn("Coordinator allocation failed, falling back to local strategy:",U),H=m(O,G,W,Y)}else H=m(O,G,W,Y);return await Z.setShardMapping(G,H),H}async function DJ(G,J="write"){let Y=T(),Z=await uG(G,J),$=Y.shards[Z];if(!$)throw new F(`Shard ${Z} not found in configuration`,"SHARD_NOT_FOUND");return $}async function RJ(G,J){let{createSchema:Y}=await Promise.resolve().then(() => (g(),t));await Y(G,J)}async function r(G,J){let Y=LJ(J);return(await DJ(G,Y)).prepare(J)}async function gG(G,J,Y=[]){let $=await(await r(G,J)).bind(...Y).run();if(!$.success)throw new F(`Query failed: ${$.error||"Unknown error"}`,"QUERY_FAILED");return $}async function mG(G,J,Y=[]){let $=await(await r(G,J)).bind(...Y).all();if(!$.success)throw new F(`Query failed: ${$.error||"Unknown error"}`,"QUERY_FAILED");return $}async function cG(G,J,Y=[]){return await(await r(G,J)).bind(...Y).first()}async function xJ(G,J,Y=[],Z=50){let $=T(),W=await C($).getShardMapping(G);if(W){if($.shards[W.shard]){let U=await UG(W.shard,J,Y);if(U.success&&U.results.length>0)return U}}let H=await e(J,Y,Z);return oG(H)}async function vJ(G,J,Y=[],Z=50){let $=T(),W=await C($).getShardMapping(G);if(W){if($.shards[W.shard]){let U=await _G(W.shard,J,Y);if(U!==null)return U}}return(await iG(J,Y,Z)).find((O)=>O!==null)??null}async function zJ(G,J,Y){let Z=T();if(!Z.shards[J])throw new F(`Shard ${J} not found in configuration`,"SHARD_NOT_FOUND");let $=C(Z),X=await $.getShardMapping(G);if(!X)throw new F(`No existing mapping found for primary key: ${G}`,"MAPPING_NOT_FOUND");if(X.shard!==J){let{migrateRecord:W}=await Promise.resolve().then(() => (g(),t)),H=Z.shards[X.shard],O=Z.shards[J];if(!H||!O)throw new F("Source or target shard not available","SHARD_UNAVAILABLE");await W(H,O,G,Y)}await $.updateShardMapping(G,J)}async function MJ(){let G=T();if(G.coordinator)try{let J=G.coordinator.idFromName("default"),Z=await G.coordinator.get(J).fetch("http://coordinator/shards");if(Z.ok)return await Z.json()}catch(J){console.warn("Failed to get shards from coordinator:",J)}try{let Y=await C(G).getKnownShards(),Z=new Set([...Object.keys(G.shards),...Y]);return Array.from(Z)}catch{return Object.keys(G.shards)}}async function BJ(){let G=T();if(G.coordinator)try{let $=G.coordinator.idFromName("default"),W=await G.coordinator.get($).fetch("http://coordinator/stats");if(W.ok)return await W.json()}catch($){console.warn("Failed to get stats from coordinator:",$)}let J=C(G),Y=await J.getShardKeyCounts(),Z=Object.keys(G.shards);try{let $=await J.getKnownShards();Z=Array.from(new Set([...Z,...$]))}catch{}return Z.map(($)=>({binding:$,count:Y[$]||0}))}async function dG(G,J,Y=[]){let $=T().shards[G];if(!$)throw new F(`Shard ${G} not found`,"SHARD_NOT_FOUND");let X=await $.prepare(J).bind(...Y).run();if(!X.success)throw new F(`Query failed: ${X.error||"Unknown error"}`,"QUERY_FAILED");return X}async function UG(G,J,Y=[]){let $=T().shards[G];if(!$)throw new F(`Shard ${G} not found`,"SHARD_NOT_FOUND");return await $.prepare(J).bind(...Y).all()}async function _G(G,J,Y=[]){let $=T().shards[G];if(!$)throw new F(`Shard ${G} not found`,"SHARD_NOT_FOUND");return await $.prepare(J).bind(...Y).first()}async function nG(G,J=[],Y=50){let Z=T(),$=[];for(let[W,H]of Object.entries(Z.shards)){if(!W||!H){console.error(`Shard ${W??"<null>"} not found, skipping`);continue}$.push(()=>H.prepare(G).bind(...J).run().catch((O)=>{return console.error(`Error executing query on shard ${W}:`,O),{success:!1,results:[],error:O instanceof Error?O.message:String(O),meta:{duration:0}}}))}let X=[];for(let W=0;W<$.length;W+=Y){let H=$.slice(W,W+Y).map((O)=>O());X.push(...await Promise.all(H))}return X}async function e(G,J=[],Y=50){let Z=T(),$=[];for(let[W,H]of Object.entries(Z.shards)){if(!W||!H){console.error(`Shard ${W??"<null>"} not found, skipping`);continue}$.push(()=>H.prepare(G).bind(...J).all().catch((O)=>{return console.error(`Error executing query on shard ${W}:`,O),{success:!1,results:[],error:O instanceof Error?O.message:String(O),meta:{duration:0}}}))}let X=[];for(let W=0;W<$.length;W+=Y){let H=$.slice(W,W+Y).map((O)=>O());X.push(...await Promise.all(H))}return X}function d(G,J=50){if(!Number.isFinite(G??J))return J;return Math.max(1,Math.floor(G??J))}function wJ(G){if(!Number.isFinite(G??0))return 0;return Math.max(0,Math.floor(G??0))}function NJ(G){if(G===void 0)return;if(!Number.isFinite(G))return;return Math.max(0,Math.floor(G))}function bG(G,J){if(typeof J==="function")return J(G);if(!J||typeof G!=="object"||G===null)return;return G[String(J)]}function CJ(G,J){if(G===J)return 0;if(G===null||G===void 0)return 1;if(J===null||J===void 0)return-1;if(typeof G==="number"&&typeof J==="number")return G-J;if(typeof G==="bigint"&&typeof J==="bigint")return G<J?-1:1;if(G instanceof Date&&J instanceof Date)return G.getTime()-J.getTime();if(typeof G==="boolean"&&typeof J==="boolean")return Number(G)-Number(J);return String(G).localeCompare(String(J),void 0,{numeric:!0,sensitivity:"base"})}function oG(G){let J=G.flatMap((X)=>X.results||[]),Y=G.filter((X)=>!X.success),Z=G.reduce((X,W)=>X+(W.meta?.duration||0),0);if(Y.length===0)return{success:!0,results:J,meta:{duration:Z}};let $=Y.map((X)=>X.error||"Unknown shard query error").filter(Boolean).join("; ");return{success:!1,results:J,error:$||"One or more shard queries failed",meta:{duration:Z}}}async function lG(G,J=[],Y={}){let Z=d(Y.batchSize),$=wJ(Y.offset),X=NJ(Y.limit),W=oG(await e(G,J,Z)),H=W.results;if(Y.filter)H=H.filter((_)=>Y.filter?.(_));if(Y.comparator)H=[...H].sort(Y.comparator);else if(Y.sortBy){let _=Y.sortDirection==="desc"?-1:1;H=[...H].sort((V,L)=>{let I=bG(V,Y.sortBy),P=bG(L,Y.sortBy);return CJ(I,P)*_})}let O=X===void 0?void 0:$+X,U=H.slice($,O);return{...W,results:U}}async function iG(G,J=[],Y=50){let Z=T(),$=[];for(let[W,H]of Object.entries(Z.shards)){if(!W||!H){console.error(`Shard ${W??"<null>"} not found, skipping`);continue}$.push(()=>H.prepare(G).bind(...J).first().catch((O)=>{return console.error(`Error executing query on shard ${W}:`,O),null}))}let X=[];for(let W=0;W<$.length;W+=Y){let H=$.slice(W,W+Y).map((O)=>O());X.push(...await Promise.all(H))}return X}async function kJ(G,J=[],Y={}){return(await lG(G,J,{...Y,limit:1})).results[0]??null}async function qJ(){let G=T();if(await C(G).clearAllMappings(),y.clear(),G.coordinator)try{let Y=G.coordinator.idFromName("default");await G.coordinator.get(Y).fetch("http://coordinator/flush",{method:"POST"})}catch(Y){console.warn("Failed to flush coordinator:",Y)}}async function SJ(G){let Y=T().shards[G];if(!Y)throw new F(`Shard ${G} not found`,"SHARD_NOT_FOUND");return await a(Y)}var KJ=/^[A-Za-z_][A-Za-z0-9_]*$/;function f(G){let J=G.trim();if(!J)throw new F("Identifier cannot be empty","INVALID_IDENTIFIER");let Y=J.split(".").map((Z)=>Z.trim());if(Y.some((Z)=>!Z||!KJ.test(Z)))throw new F(`Invalid SQL identifier: ${G}`,"INVALID_IDENTIFIER");return Y.map((Z)=>`"${Z}"`).join(".")}function hG(G){return G.toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")}function fJ(G){if(typeof G==="string")return[{name:G}];if(!Array.isArray(G)||G.length===0)throw new F("At least one index column is required","INVALID_INDEX_COLUMNS");return G.map((J)=>{if(typeof J==="string")return{name:J};if(!J?.name)throw new F("Index column name is required","INVALID_INDEX_COLUMNS");return{name:J.name,order:J.order,collate:J.collate}})}function VG(G,J,Y={}){let Z=fJ(J),$=f(G),X=Y.indexName?Y.indexName:["idx",hG(G),...Z.map((V)=>hG(V.name))].filter(Boolean).join("_").slice(0,120),W=f(X||"idx_auto"),H=Z.map((V)=>{let L=f(V.name),I=V.order?` ${V.order}`:"",P=V.collate?` COLLATE ${f(V.collate).replace(/"/g,"")}`:"";return`${L}${P}${I}`}).join(", "),O=Y.ifNotExists===!1?"":" IF NOT EXISTS",U=Y.unique?"UNIQUE ":"",_=Y.where?.trim()?` WHERE ${Y.where.trim()}`:"";return`CREATE ${U}INDEX${O} ${W} ON ${$} (${H})${_}`}async function bJ(G,J,Y,Z={}){let $=VG(J,Y,Z);return gG(G,$)}async function hJ(G,J,Y,Z={}){let $=VG(J,Y,Z);return dG(G,$)}async function pJ(G,J,Y={}){let Z=VG(G,J,Y);return nG(Z,[],d(Y.batchSize))}function FG(G,J="query-plan"){switch(J){case"raw":return`EXPLAIN ${G}`;case"analyze":return`EXPLAIN ANALYZE ${G}`;case"query-plan":default:return`EXPLAIN QUERY PLAN ${G}`}}async function yJ(G,J,Y=[],Z={}){return mG(G,FG(J,Z.mode),Y)}async function uJ(G,J,Y=[],Z={}){return UG(G,FG(J,Z.mode),Y)}async function gJ(G,J=[],Y={}){return e(FG(G,Y.mode),J,d(Y.batchSize))}async function mJ(G,J){let Y=f(J),Z=await cG(G,`SELECT COUNT(*) AS row_count FROM ${Y}`);if(!Z||Z.row_count===void 0||Z.row_count===null)return 0;return Number(Z.row_count)||0}async function cJ(G,J){let Y=f(J),Z=await _G(G,`SELECT COUNT(*) AS row_count FROM ${Y}`);if(!Z||Z.row_count===void 0||Z.row_count===null)return 0;return Number(Z.row_count)||0}async function dJ(G,J=50){let Y=T(),Z=d(J),X=`SELECT COUNT(*) AS row_count FROM ${f(G)}`,W=[];for(let[U,_]of Object.entries(Y.shards)){if(!U||!_)continue;W.push(async()=>{try{let V=await _.prepare(X).first(),L=Number(V?.row_count??0);return{shard:U,count:Number.isFinite(L)?L:0,success:!0}}catch(V){return{shard:U,count:null,success:!1,error:V instanceof Error?V.message:String(V)}}})}let H=[];for(let U=0;U<W.length;U+=Z){let _=W.slice(U,U+Z).map((V)=>V());H.push(...await Promise.all(_))}return{total:H.reduce((U,_)=>U+(_.count??0),0),shards:H}}async function nJ(G){let J=T(),Y=await uG(G,"read"),Z=J.shards[Y];if(!Z)throw new F(`Shard ${Y} not found in configuration`,"SHARD_NOT_FOUND");return a(Z)}async function sG(G=50){let J=T(),Y=d(G),Z=[];for(let[X,W]of Object.entries(J.shards)){if(!X||!W)continue;Z.push(async()=>{try{return{shard:X,size:await a(W),success:!0}}catch(H){return{shard:X,size:null,success:!1,error:H instanceof Error?H.message:String(H)}}})}let $=[];for(let X=0;X<Z.length;X+=Y){let W=Z.slice(X,X+Y).map((H)=>H());$.push(...await Promise.all(W))}return $}async function oJ(G=50){return(await sG(G)).reduce((Y,Z)=>Y+(Z.size??0),0)}q();class LG{state;constructor(G){this.state=G}async getState(){return await this.state.storage.get("coordinator_state")||{knownShards:[],shardStats:{},strategy:"round-robin",roundRobinIndex:0}}async saveState(G){await this.state.storage.put("coordinator_state",G)}async fetch(G){let Y=new URL(G.url).pathname,Z=G.method;try{switch(`${Z} ${Y}`){case"GET /shards":return this.handleListShards();case"POST /shards":return this.handleAddShard(G);case"DELETE /shards":return this.handleRemoveShard(G);case"GET /stats":return this.handleGetStats();case"POST /stats":return this.handleUpdateStats(G);case"POST /allocate":return this.handleAllocateShard(G);case"POST /flush":return this.handleFlush();case"GET /health":return new Response("OK",{status:200});default:return new Response("Not Found",{status:404})}}catch($){return console.error("ShardCoordinator error:",$),new Response("Internal Server Error",{status:500})}}async handleListShards(){let G=await this.getState();return new Response(JSON.stringify(G.knownShards),{headers:{"Content-Type":"application/json"}})}async handleAddShard(G){let{shard:J}=await G.json();if(!J||typeof J!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let Y=await this.getState();if(!Y.knownShards.includes(J))Y.knownShards.push(J),Y.shardStats[J]={binding:J,count:0,lastUpdated:Date.now()},await this.saveState(Y);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleRemoveShard(G){let{shard:J}=await G.json();if(!J||typeof J!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let Y=await this.getState(),Z=Y.knownShards.indexOf(J);if(Z>-1){if(Y.knownShards.splice(Z,1),delete Y.shardStats[J],Y.roundRobinIndex>=Y.knownShards.length)Y.roundRobinIndex=0;await this.saveState(Y)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleGetStats(){let G=await this.getState(),J=Object.values(G.shardStats);return new Response(JSON.stringify(J),{headers:{"Content-Type":"application/json"}})}async handleUpdateStats(G){let{shard:J,count:Y}=await G.json();if(!J||typeof J!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if(Y===void 0||typeof Y!=="number")return new Response(JSON.stringify({error:"Missing or invalid count parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let Z=await this.getState();if(Z.shardStats[J])Z.shardStats[J].count=Y,Z.shardStats[J].lastUpdated=Date.now(),await this.saveState(Z);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleAllocateShard(G){let{primaryKey:J,strategy:Y,operationType:Z,availableShards:$}=await G.json();if(!J||typeof J!=="string")return new Response(JSON.stringify({error:"Missing or invalid primaryKey parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let X=await this.getState(),W=$||X.knownShards;if(W.length===0)return new Response(JSON.stringify({error:"No shards available"}),{status:400,headers:{"Content-Type":"application/json"}});let H=this.resolveStrategy(X.strategy,Y,Z||"write"),O=this.selectShard(J,X,H,W);if(H==="round-robin")X.roundRobinIndex=(X.roundRobinIndex+1)%W.length,await this.saveState(X);return new Response(JSON.stringify({shard:O}),{headers:{"Content-Type":"application/json"}})}async handleFlush(){return await this.state.storage.deleteAll(),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}resolveStrategy(G,J,Y="write"){if(J)return J;if(typeof G==="string")return G;return G[Y]}selectShard(G,J,Y,Z){let $=Z||J.knownShards;if($.length===0)throw new F("No shards available","NO_SHARDS");switch(Y){case"round-robin":return $[J.roundRobinIndex]??$[0];case"random":return $[Math.floor(Math.random()*$.length)];case"hash":{let X=0;for(let H=0;H<G.length;H++){let O=G.charCodeAt(H);X=(X<<5)-X+O,X=X&X}let W=Math.abs(X)%$.length;return $[W]}case"location":{let X=J.targetRegion,W=J.shardLocations||{},H=$.filter((A)=>W[A]);if(!X||H.length===0){let A=0;for(let R=0;R<G.length;R++){let D=G.charCodeAt(R);A=(A<<5)-A+D,A=A&A}let j=Math.abs(A)%$.length;return $[j]}let O={wnam:{lat:37.7749,lon:-122.4194},enam:{lat:40.7357,lon:-74.1724},weur:{lat:51.5074,lon:-0.1278},eeur:{lat:52.2297,lon:21.0122},apac:{lat:35.6762,lon:139.6503},oc:{lat:-33.8688,lon:151.2093},me:{lat:25.2048,lon:55.2708},af:{lat:-26.2041,lon:28.0473}},U=(A,j)=>(j in A),_=(A)=>U(O,A)?A:"wnam",V=(A,j)=>{let R=O[_(A)],D=O[_(j)],E=R.lat-D.lat,Q=R.lon-D.lon;return Math.sqrt(E*E+Q*Q)},L=H.map((A)=>{let j=W[A],R=V(X,j.region),D=j.priority||1;return{shard:A,score:R-D*0.1}});L.sort((A,j)=>A.score-j.score);let I=L[0].score,P=L.filter((A)=>Math.abs(A.score-I)<0.01);if(P.length===1)return P[0].shard;let x=0;for(let A=0;A<G.length;A++){let j=G.charCodeAt(A);x=(x<<5)-x+j,x=x&x}let w=Math.abs(x)%P.length;return P[w].shard}default:return $[0]}}async incrementShardCount(G){let J=await this.getState();if(J.shardStats[G])J.shardStats[G].count++,J.shardStats[G].lastUpdated=Date.now(),await this.saveState(J)}async decrementShardCount(G){let J=await this.getState();if(J.shardStats[G]&&J.shardStats[G].count>0)J.shardStats[G].count--,J.shardStats[G].lastUpdated=Date.now(),await this.saveState(J)}}if(typeof global<"u"){class G{data=new Map;async get(Z){return this.data.get(Z)}async put(Z,$){this.data.set(Z,$)}async delete(Z){return this.data.delete(Z)}async deleteAll(){this.data.clear()}async list(Z){if(!Z?.prefix)return new Map(this.data);let $=new Map;for(let[X,W]of this.data.entries())if(X.startsWith(Z.prefix))$.set(X,W);return $}}class J{storage;constructor(){this.storage=new G}}class Y{coordinator;mockState;constructor(){this.mockState=new J,this.coordinator=new LG(this.mockState)}async testShardAllocation(){await this.coordinator.fetch(new Request("http://test/shards",{method:"POST",body:JSON.stringify({shard:"db-east"})})),await this.coordinator.fetch(new Request("http://test/shards",{method:"POST",body:JSON.stringify({shard:"db-west"})}));let $=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"user-1",strategy:"round-robin"})}))).json(),W=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"user-2",strategy:"round-robin"})}))).json();console.assert($.shard!==W.shard,"Round-robin should alternate shards");let O=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"consistent-key",strategy:"hash"})}))).json(),_=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"consistent-key",strategy:"hash"})}))).json();console.assert(O.shard===_.shard,"Hash allocation should be consistent"),console.log("✅ Shard allocation tests passed")}async testShardStats(){await this.coordinator.fetch(new Request("http://test/flush",{method:"POST"})),await this.coordinator.fetch(new Request("http://test/shards",{method:"POST",body:JSON.stringify({shard:"db-stats-test"})})),await this.coordinator.fetch(new Request("http://test/stats",{method:"POST",body:JSON.stringify({shard:"db-stats-test",count:42})}));let $=await(await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"}))).json();console.assert($.length===1,"Should have one shard stat"),console.assert($[0]?.binding==="db-stats-test","Should have correct binding name"),console.assert($[0]?.count===42,"Should have correct count"),console.log("✅ Shard stats tests passed")}async testErrorHandling(){await this.coordinator.fetch(new Request("http://test/flush",{method:"POST"}));let Z=await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"test-key"})}));console.assert(Z.status===400,"Should return 400 for no shards available");let $=await this.coordinator.fetch(new Request("http://test/invalid",{method:"GET"}));console.assert($.status===404,"Should return 404 for invalid endpoint"),console.log("✅ Error handling tests passed")}async testCountManagement(){await this.coordinator.fetch(new Request("http://test/shards",{method:"POST",body:JSON.stringify({shard:"db-count-test"})})),await this.coordinator.incrementShardCount("db-count-test"),await this.coordinator.incrementShardCount("db-count-test");let Z=await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"})),$=await Z.json(),X=$.find((H)=>H.binding==="db-count-test");console.assert(X?.count===2,"Count should be 2 after two increments"),await this.coordinator.decrementShardCount("db-count-test"),Z=await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"})),$=await Z.json();let W=$.find((H)=>H.binding==="db-count-test");console.assert(W?.count===1,"Count should be 1 after decrement"),console.log("✅ Count management tests passed")}async runAllTests(){console.log("\uD83E\uDDEA Running ShardCoordinator tests...");try{return await this.testShardAllocation(),await this.testShardStats(),await this.testErrorHandling(),await this.testCountManagement(),console.log("\uD83C\uDF89 All ShardCoordinator tests passed!"),!0}catch(Z){return console.error("❌ ShardCoordinator tests failed:",Z),!1}}}globalThis.testShardCoordinator=()=>new Y}q();u();q();var lJ=500;function rG(G,J={}){let Y=J.scanCount??lJ;return{async get(Z,$="text"){let X=await G.get(Z);if(X===null)return null;if($!=="json")return X;try{return JSON.parse(X)}catch(W){throw new F(`Failed to parse JSON from Redis for key ${Z}: ${W instanceof Error?W.message:String(W)}`,"KV_JSON_PARSE_FAILED")}},async put(Z,$){await G.set(Z,$)},async delete(Z){await G.del(Z)},async list(Z){let $=Z?.prefix??"",X=`${$}*`,W=Z?.cursor??"0",H=Z?.limit,O=[];do{let U=await JY(G,W,X,Y);W=U.cursor;for(let _ of U.keys){if(!$||_.startsWith($))O.push(_);if(H&&O.length>=H)break}if(H&&O.length>=H)break}while(W!=="0");return{keys:O.map((U)=>({name:U})),cursor:W,list_complete:W==="0"}}}}function iJ(G,J={}){return rG(G,J)}function eG(G,J){if(J)return JG(G,J);return{prepare(Y){return new EG(G,Y)}}}function GJ(G,J){if(J)return JG(G,J);return{prepare(Y){return new TG(G,Y)}}}function sJ(G,J){if(J)return JG(G,J);return{prepare(Y){return new DG(G,Y)}}}function JG(G,J){return{prepare(Y){return new RG(G,J,Y)}}}function tJ(G){return{async get(J,Y="text"){let Z=await XY(G,J);if(Z===null||Z===void 0)return null;if(Y==="json"){if(typeof Z==="string")try{return JSON.parse(Z)}catch($){throw new F(`Failed to parse JSON from NuxtHub KV for key ${J}: ${$ instanceof Error?$.message:String($)}`,"KV_JSON_PARSE_FAILED")}return Z}return typeof Z==="string"?Z:JSON.stringify(Z)},async put(J,Y){await WY(G,J,Y)},async delete(J){await HY(G,J)},async list(J){let Y=J?.prefix??"",Z=await OY(G,Y);return{keys:(typeof J?.limit==="number"?Z.slice(0,J.limit):Z).map((X)=>({name:X})),list_complete:!0}}}}function aJ(G,J){return eG({query:async(Z,$=[])=>{let X=J(G.connectionString);if(typeof X.connect==="function")await X.connect();try{return await X.query(Z,$)}finally{if(typeof X.release==="function")X.release();else if(typeof X.end==="function")await X.end()}}})}function rJ(G,J){return GJ({execute:async(Z,$=[])=>{let X=J(G.connectionString);try{if(typeof X.execute==="function")return await X.execute(Z,$);if(typeof X.query==="function")return await X.query(Z,$);throw new F("Hyperdrive MySQL client is missing execute/query methods","MYSQL_CLIENT_INVALID")}finally{if(typeof X.end==="function")await X.end();else if(typeof X.close==="function")await X.close();else if(typeof X.destroy==="function")X.destroy()}}})}function eJ(G){if(!G||typeof G!=="object")return!1;return typeof G.prepare==="function"}function GY(G){if(!G||typeof G!=="object")return!1;let J=G;return typeof J.get==="function"&&typeof J.put==="function"&&typeof J.delete==="function"&&typeof J.list==="function"}class EG{client;sql;bindings;constructor(G,J,Y=[]){this.client=G,this.sql=J,this.bindings=Y}bind(...G){return new EG(this.client,this.sql,G)}async run(){let G=Date.now(),J=QG(this.sql),Y=await this.client.query(J,this.bindings);return{success:!0,results:Y.rows??[],meta:B(G,{changes:typeof Y.rowCount==="number"?Y.rowCount:void 0,command:Y.command})}}async all(){let G=Date.now(),J=QG(this.sql),Y=await this.client.query(J,this.bindings);return{success:!0,results:Y.rows??[],meta:B(G,{changes:typeof Y.rowCount==="number"?Y.rowCount:void 0,command:Y.command})}}async first(){let G=QG(this.sql);return(await this.client.query(G,this.bindings)).rows?.[0]??null}}class TG{client;sql;bindings;constructor(G,J,Y=[]){this.client=G,this.sql=J,this.bindings=Y}bind(...G){return new TG(this.client,this.sql,G)}async run(){let G=Date.now(),J=await AG(this.client,this.sql,this.bindings);if(Array.isArray(J))return{success:!0,results:J,meta:B(G)};let Y=J;return{success:!0,results:[],meta:B(G,{changes:Y.affectedRows,last_row_id:Y.insertId,warningStatus:Y.warningStatus})}}async all(){let G=Date.now(),J=await AG(this.client,this.sql,this.bindings);return{success:!0,results:Array.isArray(J)?J:[],meta:B(G,{changes:!Array.isArray(J)?J.affectedRows:void 0})}}async first(){let G=await AG(this.client,this.sql,this.bindings);if(!Array.isArray(G)||G.length===0)return null;return G[0]}}class DG{client;sql;bindings;constructor(G,J,Y=[]){this.client=G,this.sql=J,this.bindings=Y}bind(...G){return new DG(this.client,this.sql,G)}async run(){let G=Date.now();if(typeof this.client.execute==="function"){let $=await this.client.execute(this.sql,this.bindings);return{success:!0,results:PG($),meta:B(G)}}let J=this.client.prepare?.(this.sql);if(!J||typeof J.run!=="function")throw new F("SQLite client must expose execute() or prepare().run()","SQLITE_CLIENT_INVALID");let Z=await J.run(...this.bindings)??{};return{success:!0,results:[],meta:B(G,{changes:GG(Z.changes),last_row_id:Z.lastInsertRowid??Z.lastID})}}async all(){let G=Date.now();if(typeof this.client.execute==="function"){let Z=await this.client.execute(this.sql,this.bindings);return{success:!0,results:PG(Z),meta:B(G)}}let J=this.client.prepare?.(this.sql);if(!J||typeof J.all!=="function")throw new F("SQLite client must expose execute() or prepare().all()","SQLITE_CLIENT_INVALID");let Y=await J.all(...this.bindings);return{success:!0,results:Array.isArray(Y)?Y:[],meta:B(G)}}async first(){if(typeof this.client.execute==="function"){let J=await this.client.execute(this.sql,this.bindings);return PG(J)[0]??null}let G=this.client.prepare?.(this.sql);if(!G)throw new F("SQLite client must expose execute() or prepare().get()","SQLITE_CLIENT_INVALID");if(typeof G.get==="function"){let J=await G.get(...this.bindings);return J===void 0||J===null?null:J}if(typeof G.all==="function"){let J=await G.all(...this.bindings);if(!Array.isArray(J)||J.length===0)return null;let Y=J[0];return Y===void 0||Y===null?null:Y}throw new F("SQLite prepare() result must expose get() or all()","SQLITE_CLIENT_INVALID")}}class RG{client;sqlTag;sqlText;bindings;constructor(G,J,Y,Z=[]){this.client=G,this.sqlTag=J,this.sqlText=Y,this.bindings=Z}bind(...G){return new RG(this.client,this.sqlTag,this.sqlText,G)}async run(){let G=Date.now(),J=jG(this.sqlTag,this.sqlText,this.bindings),Y=await YY(this.client,J);return{success:!0,results:IG(Y),meta:B(G,aG(Y))}}async all(){let G=Date.now(),J=jG(this.sqlTag,this.sqlText,this.bindings),Y=await JJ(this.client,J);return{success:!0,results:IG(Y),meta:B(G,aG(Y))}}async first(){let G=jG(this.sqlTag,this.sqlText,this.bindings),J=await ZY(this.client,G),Y=IG(J);if(Y.length>0)return Y[0]??null;if(J&&typeof J==="object"&&"row"in J){let Z=J.row;return Z===void 0||Z===null?null:Z}if(J&&typeof J==="object"&&!Array.isArray(J)&&!("rows"in J)&&!("results"in J)&&!("data"in J))return J;return null}}async function JY(G,J,Y,Z){try{let $=await G.scan(J,{MATCH:Y,COUNT:Z});return tG($)}catch{let $=await G.scan(J,"MATCH",Y,"COUNT",String(Z));return tG($)}}function tG(G){if(Array.isArray(G))return{cursor:String(G[0]??"0"),keys:Array.isArray(G[1])?G[1]:[]};return{cursor:String(G.cursor??"0"),keys:Array.isArray(G.keys)?G.keys:[]}}async function AG(G,J,Y){if(typeof G.execute==="function"){let Z=await G.execute(J,Y);if(Array.isArray(Z))return Z[0];return Z}if(typeof G.query==="function"){let Z=await G.query(J,Y);if(Array.isArray(Z))return Z[0];return Z}throw new F("MySQL client must expose execute() or query()","MYSQL_CLIENT_INVALID")}async function YY(G,J){if(typeof G.run==="function")return await G.run(J);if(typeof G.execute==="function")return await G.execute(J);if(typeof G.all==="function")return await G.all(J);throw new F("Drizzle client must expose run(), execute(), or all()","DRIZZLE_CLIENT_INVALID")}async function JJ(G,J){if(typeof G.all==="function")return await G.all(J);if(typeof G.execute==="function")return await G.execute(J);if(typeof G.run==="function")return await G.run(J);throw new F("Drizzle client must expose all(), execute(), or run()","DRIZZLE_CLIENT_INVALID")}async function ZY(G,J){if(typeof G.get==="function")return await G.get(J);return await JJ(G,J)}function jG(G,J,Y){let Z=$Y(J),$=Z.length-1;if($!==Y.length)throw new F(`Drizzle binding mismatch: expected ${$} bindings, received ${Y.length}`,"DRIZZLE_BINDINGS_MISMATCH");if($===0)return G.raw(J);let X=typeof G.empty==="function"?G.empty():G.raw("");for(let W=0;W<Z.length;W++){let H=Z[W];if(H)X.append(G.raw(H));if(W<$)X.append(G`${Y[W]}`)}return X}function $Y(G){let J=[],Y=0,Z=!1,$=!1,X=!1,W=!1;for(let H=0;H<G.length;H++){let O=G[H],U=H+1<G.length?G[H+1]:"";if(X){if(O===`
|
|
17
|
-
`)
|
|
18
|
-
`)
|
|
16
|
+
`).run()}if(f.set(F,!0),C&&Z.debug)console.log(`Auto-migration completed for shard ${Y}: ${E} records from ${I} tables`)}catch(V){A.push(`Auto-migration error: ${V}`)}return{migrationNeeded:M,migrationPerformed:C,recordsMigrated:E,tablesProcessed:I,issues:A}}async function hJ(J,Y,Z){let $=`${Y}_migration_check`;if(f.has($))return!1;try{let X=await p(J);if(X.includes("shard_mappings"))return f.set($,!0),!1;let{KVShardMapper:G}=await Promise.resolve().then(() => (c(),HJ)),U=new G(Z.kv,{hashShardMappings:Z.hashShardMappings,mappingCacheTtlMs:Z.mappingCacheTtlMs,knownShardsCacheTtlMs:Z.knownShardsCacheTtlMs}),H=X.filter((_)=>_!=="shard_mappings"&&!_.startsWith("sqlite_")&&_!=="sqlite_sequence");for(let _ of H.slice(0,3))try{if(((await J.prepare(`SELECT COUNT(*) as count FROM ${_} LIMIT 1`).first())?.count||0)>0){let A=await J.prepare(`SELECT id FROM ${_} LIMIT 1`).first();if(A){let E=String(A.id);if(!await U.getShardMapping(E))return!0}}}catch{continue}return!1}catch{return!1}}function pJ(){f.clear()}function yJ(J){let Y=`${J}_migration_check`;f.delete(Y)}var f,_J;var d=UJ(()=>{q();f=new Map,_J=new Map});q();c();var o=null,y=null,m=new Map,u=0;function v(J){if(!y)y=new K(J.kv,{hashShardMappings:J.hashShardMappings,mappingCacheTtlMs:J.mappingCacheTtlMs,knownShardsCacheTtlMs:J.knownShardsCacheTtlMs});return y}function QY(J){o=J,y=new K(J.kv,{hashShardMappings:J.hashShardMappings,mappingCacheTtlMs:J.mappingCacheTtlMs,knownShardsCacheTtlMs:J.knownShardsCacheTtlMs}),m.clear(),u=0;try{let Y=v(J);Promise.resolve().then(async()=>{let Z=await Y.getKnownShards(),$=Array.from(new Set([...Z,...Object.keys(J.shards)]));await Y.setKnownShards($)}).catch(()=>{return})}catch{}if(J.shards&&Object.keys(J.shards).length>0&&!J.disableAutoMigration)cJ(J).catch((Y)=>{console.warn("Background auto-migration failed:",Y)})}async function mJ(J){o=J,y=new K(J.kv,{hashShardMappings:J.hashShardMappings,mappingCacheTtlMs:J.mappingCacheTtlMs,knownShardsCacheTtlMs:J.knownShardsCacheTtlMs}),m.clear(),u=0;try{let Y=v(J),Z=await Y.getKnownShards(),$=Array.from(new Set([...Z,...Object.keys(J.shards)]));await Y.setKnownShards($)}catch{}if(J.shards&&Object.keys(J.shards).length>0&&!J.disableAutoMigration)try{await cJ(J)}catch(Y){console.warn("Auto migration failed:",Y)}}async function PY(J,Y){return await mJ(J),await Y()}async function cJ(J){try{let{autoDetectAndMigrate:Y}=await Promise.resolve().then(() => (d(),r)),Z=Object.keys(J.shards);if(J.debug)console.log(`\uD83D\uDD0D Checking ${Z.length} shards for existing data...`);let $=Z.map(async(G)=>{let U=J.shards[G];if(!U)return null;try{let H=await Y(U,G,J,{maxRecordsToCheck:1000});return{shardName:G,...H}}catch(H){return console.warn(`Auto-migration failed for shard ${G}:`,H),null}}),W=(await Promise.all($)).filter((G)=>G?.migrationPerformed);if(J.debug)if(W.length>0){let G=W.reduce((U,H)=>U+(H?.recordsMigrated||0),0);console.log(`\uD83C\uDF89 Auto-migration completed! Migrated ${G} records across ${W.length} shards`),W.forEach((U)=>{if(U)console.log(` ✅ ${U.shardName}: ${U.recordsMigrated} records from ${U.tablesProcessed} tables`)})}else console.log("✅ All shards ready - no migration needed")}catch(Y){console.warn("Background auto-migration setup failed:",Y)}}function TY(){o=null,y=null,m.clear(),u=0}function T(){if(!o)throw new j("CollegeDB not initialized. Call initialize() first.","NOT_INITIALIZED");return o}function DY(J){let Y=J.trim().toUpperCase();if(Y.startsWith("SELECT")||Y.startsWith("VALUES")||Y.startsWith("TABLE")||Y.startsWith("PRAGMA")||Y.startsWith("EXPLAIN")||Y.startsWith("WITH")||Y.startsWith("SHOW"))return"read";return"write"}function dJ(J,Y){let Z=J.strategy||"hash";if(typeof Z==="string")return Z;let $=Z;return $[Y]||$.write||$.read||"hash"}function RY(J,Y){if(J===Y)return 0;let Z={wnam:{lat:37.7749,lon:-122.4194},enam:{lat:40.7128,lon:-74.006},weur:{lat:51.5074,lon:-0.1278},eeur:{lat:52.52,lon:13.405},apac:{lat:35.6762,lon:139.6503},oc:{lat:-33.8688,lon:151.2093},me:{lat:25.2048,lon:55.2708},af:{lat:-26.2041,lon:28.0473}},$=Z[J],X=Z[Y],W=$.lat-X.lat,G=$.lon-X.lon;return Math.sqrt(W*W+G*G)}function zY(J){let Y=J.cf;if(!Y||!Y.country)return"wnam";let{country:Z,continent:$}=Y;if(["US","CA","MX"].includes(Z)){let X=Y.region||Y.regionCode||"",W=Y.timezone||"";if(X.includes("CA")||X.includes("WA")||X.includes("OR")||X.includes("NV")||X.includes("AZ")||X.includes("UT")||W.includes("Pacific")||W.includes("America/Los_Angeles"))return"wnam";return"enam"}if(["GL","PM","BM"].includes(Z))return"enam";if(["GB","IE","FR","ES","PT","NL","BE","LU","CH","AT","IT"].includes(Z))return"weur";if(["DE","PL","CZ","SK","HU","SI","HR","BA","RS","ME","MK","AL","BG","RO","MD","UA","BY","LT","LV","EE","FI","SE","NO","DK","IS"].includes(Z))return"eeur";if(Z==="RU")return"eeur";if(["JP","KR","CN","HK","TW","MO","MN","KP"].includes(Z))return"apac";if(["TH","VN","SG","MY","ID","PH","BN","KH","LA","MM","TL","IN","PK","BD","LK","NP","BT","MV","AF"].includes(Z))return"apac";if(["AU","NZ","PG","FJ","NC","VU","SB","WS","TO","KI","NR","PW","FM","MH","TV"].includes(Z))return"oc";if(["AE","SA","QA","KW","BH","OM","YE","IQ","IR","SY","LB","JO","IL","PS","TR","CY"].includes(Z))return"me";if($==="AF"||["EG","LY","TN","DZ","MA","SD","SS","ET","ER","DJ","SO"].includes(Z))return"af";if(["KZ","UZ","TM","TJ","KG"].includes(Z))return"eeur";if($==="SA"||["BR","AR","CL","PE","CO","VE","EC","BO","PY","UY","GY","SR","GF"].includes(Z))return"enam";if(["GT","BZ","SV","HN","NI","CR","PA","CU","JM","HT","DO","PR","TT","BB","GD","VC","LC","DM","AG","KN"].includes(Z))return"enam";return"wnam"}function MY(J){if(typeof J==="string")return J;return J.region||"wnam"}async function e(J){try{let[Y,Z]=await Promise.all([J.prepare("PRAGMA page_count").first(),J.prepare("PRAGMA page_size").first()]);if(!Y?.page_count||!Z?.page_size)throw new j("Failed to retrieve database size information","SIZE_QUERY_FAILED");return Y.page_count*Z.page_size}catch(Y){throw new j(`Failed to get database size: ${Y instanceof Error?Y.message:"Unknown error"}`,"SIZE_QUERY_FAILED")}}async function BY(J,Y){let Z=Math.max(0,Y.sizeCacheTtlMs??30000),$=m.get(J);if($&&$.expiresAt>=Date.now())return $.size;let X=Y.shards[J];if(!X)throw new j(`Shard ${J} not found in configuration`,"SHARD_NOT_FOUND");let W=await e(X);if(Z>0)m.set(J,{size:W,expiresAt:Date.now()+Z});return W}async function oJ(J,Y){if(typeof Y.maxDatabaseSize!=="number"||!Number.isFinite(Y.maxDatabaseSize)||Y.maxDatabaseSize<=0)return J;let Z=Y.maxDatabaseSize,X=(await Promise.allSettled(J.map(async(W)=>{let G=await BY(W,Y);return{shard:W,size:G,withinLimit:G<Z}}))).filter((W)=>W.status==="fulfilled"&&W.value.withinLimit).map((W)=>W.value.shard);if(X.length===0){if(Y.debug)console.warn("All shards exceed maxDatabaseSize limit. Allowing allocation to prevent failure.");return J}if(Y.debug&&X.length<J.length){let W=J.filter((G)=>!X.includes(G));console.log(`Excluded ${W.length} shards due to size limits: ${W.join(", ")}`)}return X}function wY(J,Y,Z,$){let X=Y.filter((O)=>Z[O]);if(X.length===0){let O=0;for(let A=0;A<$.length;A++){let E=$.charCodeAt(A);O=(O<<5)-O+E,O=O&O}let F=Math.abs(O)%Y.length;return Y[F]}let W=X.map((O)=>{let F=Z[O],A=RY(J,MY(F)),E=typeof F==="object"?F.priority||1:1,I=A-E*0.1;return{shard:O,score:I,distance:A,priority:E}});W.sort((O,F)=>O.score-F.score);let G=W[0].score,U=W.filter((O)=>Math.abs(O.score-G)<0.01);if(U.length===1)return U[0].shard;let H=0;for(let O=0;O<$.length;O++){let F=$.charCodeAt(O);H=(H<<5)-H+F,H=H&H}let _=Math.abs(H)%U.length;return U[_].shard}function g(J,Y,Z,$){switch(J){case"hash":{let X=0;for(let G=0;G<Y.length;G++){let U=Y.charCodeAt(G);X=(X<<5)-X+U,X=X&X}let W=Math.abs(X)%Z.length;return Z[W]||Z[0]}case"location":{if(!$.targetRegion)return g("hash",Y,Z,$);return wY($.targetRegion,Z,$.shardLocations||{},Y)}case"random":return Z[Math.floor(Math.random()*Z.length)]||Z[0];default:return g("hash",Y,Z,$)}}async function nJ(J,Y="write"){let Z=T(),$=v(Z),X=await $.getShardMapping(J);if(X)return X.shard;let W=Object.keys(Z.shards);if(W.length===0)throw new j("No shards configured","NO_SHARDS");let G=await oJ(W,Z),U,H=dJ(Z,Y);if(Z.coordinator)try{let _=Z.coordinator.idFromName("default"),F=await Z.coordinator.get(_).fetch("http://coordinator/allocate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primaryKey:J,strategy:H,operationType:Y,targetRegion:Z.targetRegion,shardLocations:Z.shardLocations,availableShards:G})});if(F.ok)U=(await F.json()).shard;else U=g(H,J,G,Z)}catch(_){console.warn("Coordinator allocation failed, falling back to local strategy:",_),U=g(H,J,G,Z)}else U=g(H,J,G,Z);return await $.setShardMapping(J,U),U}async function NY(J,Y="write"){let Z=T(),$=await nJ(J,Y),X=Z.shards[$];if(!X)throw new j(`Shard ${$} not found in configuration`,"SHARD_NOT_FOUND");return X}async function xY(J,Y){let{createSchema:Z}=await Promise.resolve().then(() => (d(),r));await Z(J,Y)}async function JJ(J,Y){let Z=DY(Y);return(await NY(J,Z)).prepare(Y)}async function lJ(J,Y,Z=[]){let X=await(await JJ(J,Y)).bind(...Z).run();if(!X.success)throw new j(`Query failed: ${X.error||"Unknown error"}`,"QUERY_FAILED");return X}function vY(J){let Y=J.results[0];if(Y&&typeof Y==="object"){for(let $ of["id","ID","Id","rowid","ROWID","RowId","last_row_id","lastInsertId","insertId"]){let X=Y[$];if(X!==void 0&&X!==null)return X}for(let[$,X]of Object.entries(Y)){let W=$.toLowerCase();if((W==="id"||W==="rowid")&&(typeof X==="number"||typeof X==="string"))return X}for(let $ of Object.values(Y))if(typeof $==="number"||typeof $==="string")return $}let Z=J.meta.last_row_id;if(Z!==void 0&&Z!==null)return Z;return}function CY(){return`insert:${Date.now()}:${Math.random().toString(36).slice(2)}`}async function kY(){let J=T(),Y=Object.keys(J.shards);if(Y.length===0)throw new j("No shards configured","NO_SHARDS");let Z=await oJ(Y,J);if(Z.length===0)throw new j("No shards available for insert","NO_SHARDS");let $=dJ(J,"write"),X=CY();if(J.coordinator)try{let W=J.coordinator.idFromName("default"),U=await J.coordinator.get(W).fetch("http://coordinator/allocate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primaryKey:X,strategy:$,operationType:"write",targetRegion:J.targetRegion,shardLocations:J.shardLocations,availableShards:Z})});if(U.ok)return(await U.json()).shard}catch(W){console.warn("Coordinator allocation for insert failed, falling back to local strategy:",W)}if($==="round-robin"){let W=Z[u%Z.length];return u=(u+1)%Z.length,W}return g($,X,Z,J)}async function sJ(J,Y,Z=[]){let $=T();if(!$.shards[J])throw new j(`Shard ${J} not found`,"SHARD_NOT_FOUND");let W=/\breturning\b/i.test(Y)?await YJ(J,Y,Z):await jJ(J,Y,Z),G=vY(W);if(G===void 0)throw new j("Insert did not return a generated primary key","GENERATED_KEY_UNAVAILABLE");return await v($).setShardMapping(String(G),J),{...W,generatedId:G}}async function qY(J,Y=[]){let Z=await kY();return await sJ(Z,J,Y)}async function SY(J,Y,Z=[]){return await sJ(J,Y,Z)}async function iJ(J,Y,Z=[]){let X=await(await JJ(J,Y)).bind(...Z).all();if(!X.success)throw new j(`Query failed: ${X.error||"Unknown error"}`,"QUERY_FAILED");return X}async function tJ(J,Y,Z=[]){return await(await JJ(J,Y)).bind(...Z).first()}async function KY(J,Y,Z=[],$=50){let X=T(),G=await v(X).getShardMapping(J);if(G){if(X.shards[G.shard]){let _=await YJ(G.shard,Y,Z);if(_.success&&_.results.length>0)return _}}let U=await ZJ(Y,Z,$);return rJ(U)}async function fY(J,Y,Z=[],$=50){let X=T(),G=await v(X).getShardMapping(J);if(G){if(X.shards[G.shard]){let _=await AJ(G.shard,Y,Z);if(_!==null)return _}}return(await JY(Y,Z,$)).find((H)=>H!==null)??null}async function bY(J,Y,Z){let $=T();if(!$.shards[Y])throw new j(`Shard ${Y} not found in configuration`,"SHARD_NOT_FOUND");let X=v($),W=await X.getShardMapping(J);if(!W)throw new j(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");if(W.shard!==Y){let{migrateRecord:G}=await Promise.resolve().then(() => (d(),r)),U=$.shards[W.shard],H=$.shards[Y];if(!U||!H)throw new j("Source or target shard not available","SHARD_UNAVAILABLE");await G(U,H,J,Z)}await X.updateShardMapping(J,Y)}async function hY(){let J=T();if(J.coordinator)try{let Y=J.coordinator.idFromName("default"),$=await J.coordinator.get(Y).fetch("http://coordinator/shards");if($.ok)return await $.json()}catch(Y){console.warn("Failed to get shards from coordinator:",Y)}try{let Z=await v(J).getKnownShards(),$=new Set([...Object.keys(J.shards),...Z]);return Array.from($)}catch{return Object.keys(J.shards)}}async function pY(){let J=T();if(J.coordinator)try{let X=J.coordinator.idFromName("default"),G=await J.coordinator.get(X).fetch("http://coordinator/stats");if(G.ok)return await G.json()}catch(X){console.warn("Failed to get stats from coordinator:",X)}let Y=v(J),Z=await Y.getShardKeyCounts(),$=Object.keys(J.shards);try{let X=await Y.getKnownShards();$=Array.from(new Set([...$,...X]))}catch{}return $.map((X)=>({binding:X,count:Z[X]||0}))}async function jJ(J,Y,Z=[]){let X=T().shards[J];if(!X)throw new j(`Shard ${J} not found`,"SHARD_NOT_FOUND");let W=await X.prepare(Y).bind(...Z).run();if(!W.success)throw new j(`Query failed: ${W.error||"Unknown error"}`,"QUERY_FAILED");return W}async function YJ(J,Y,Z=[]){let X=T().shards[J];if(!X)throw new j(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await X.prepare(Y).bind(...Z).all()}async function AJ(J,Y,Z=[]){let X=T().shards[J];if(!X)throw new j(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await X.prepare(Y).bind(...Z).first()}async function aJ(J,Y=[],Z=50){let $=T(),X=[];for(let[G,U]of Object.entries($.shards)){if(!G||!U){console.error(`Shard ${G??"<null>"} not found, skipping`);continue}X.push(()=>U.prepare(J).bind(...Y).run().catch((H)=>{return console.error(`Error executing query on shard ${G}:`,H),{success:!1,results:[],error:H instanceof Error?H.message:String(H),meta:{duration:0}}}))}let W=[];for(let G=0;G<X.length;G+=Z){let U=X.slice(G,G+Z).map((H)=>H());W.push(...await Promise.all(U))}return W}async function ZJ(J,Y=[],Z=50){let $=T(),X=[];for(let[G,U]of Object.entries($.shards)){if(!G||!U){console.error(`Shard ${G??"<null>"} not found, skipping`);continue}X.push(()=>U.prepare(J).bind(...Y).all().catch((H)=>{return console.error(`Error executing query on shard ${G}:`,H),{success:!1,results:[],error:H instanceof Error?H.message:String(H),meta:{duration:0}}}))}let W=[];for(let G=0;G<X.length;G+=Z){let U=X.slice(G,G+Z).map((H)=>H());W.push(...await Promise.all(U))}return W}function n(J,Y=50){if(!Number.isFinite(J??Y))return Y;return Math.max(1,Math.floor(J??Y))}function yY(J){if(!Number.isFinite(J??0))return 0;return Math.max(0,Math.floor(J??0))}function uY(J){if(J===void 0)return;if(!Number.isFinite(J))return;return Math.max(0,Math.floor(J))}function uJ(J,Y){if(typeof Y==="function")return Y(J);if(!Y||typeof J!=="object"||J===null)return;return J[String(Y)]}function gY(J,Y){if(J===Y)return 0;if(J===null||J===void 0)return 1;if(Y===null||Y===void 0)return-1;if(typeof J==="number"&&typeof Y==="number")return J-Y;if(typeof J==="bigint"&&typeof Y==="bigint")return J<Y?-1:1;if(J instanceof Date&&Y instanceof Date)return J.getTime()-Y.getTime();if(typeof J==="boolean"&&typeof Y==="boolean")return Number(J)-Number(Y);return String(J).localeCompare(String(Y),void 0,{numeric:!0,sensitivity:"base"})}function rJ(J){let Y=J.flatMap((W)=>W.results||[]),Z=J.filter((W)=>!W.success),$=J.reduce((W,G)=>W+(G.meta?.duration||0),0);if(Z.length===0)return{success:!0,results:Y,meta:{duration:$}};let X=Z.map((W)=>W.error||"Unknown shard query error").filter(Boolean).join("; ");return{success:!1,results:Y,error:X||"One or more shard queries failed",meta:{duration:$}}}async function eJ(J,Y=[],Z={}){let $=n(Z.batchSize),X=yY(Z.offset),W=uY(Z.limit),G=rJ(await ZJ(J,Y,$)),U=G.results;if(Z.filter)U=U.filter((O)=>Z.filter?.(O));if(Z.comparator)U=[...U].sort(Z.comparator);else if(Z.sortBy){let O=Z.sortDirection==="desc"?-1:1;U=[...U].sort((F,A)=>{let E=uJ(F,Z.sortBy),I=uJ(A,Z.sortBy);return gY(E,I)*O})}let H=W===void 0?void 0:X+W,_=U.slice(X,H);return{...G,results:_}}async function JY(J,Y=[],Z=50){let $=T(),X=[];for(let[G,U]of Object.entries($.shards)){if(!G||!U){console.error(`Shard ${G??"<null>"} not found, skipping`);continue}X.push(()=>U.prepare(J).bind(...Y).first().catch((H)=>{return console.error(`Error executing query on shard ${G}:`,H),null}))}let W=[];for(let G=0;G<X.length;G+=Z){let U=X.slice(G,G+Z).map((H)=>H());W.push(...await Promise.all(U))}return W}async function mY(J,Y=[],Z={}){return(await eJ(J,Y,{...Z,limit:1})).results[0]??null}async function cY(){let J=T();if(await v(J).clearAllMappings(),m.clear(),J.coordinator)try{let Z=J.coordinator.idFromName("default");await J.coordinator.get(Z).fetch("http://coordinator/flush",{method:"POST"})}catch(Z){console.warn("Failed to flush coordinator:",Z)}}async function dY(J){let Z=T().shards[J];if(!Z)throw new j(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await e(Z)}var oY=/^[A-Za-z_][A-Za-z0-9_]*$/;function b(J){let Y=J.trim();if(!Y)throw new j("Identifier cannot be empty","INVALID_IDENTIFIER");let Z=Y.split(".").map(($)=>$.trim());if(Z.some(($)=>!$||!oY.test($)))throw new j(`Invalid SQL identifier: ${J}`,"INVALID_IDENTIFIER");return Z.map(($)=>`"${$}"`).join(".")}function gJ(J){return J.toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")}function nY(J){if(typeof J==="string")return[{name:J}];if(!Array.isArray(J)||J.length===0)throw new j("At least one index column is required","INVALID_INDEX_COLUMNS");return J.map((Y)=>{if(typeof Y==="string")return{name:Y};if(!Y?.name)throw new j("Index column name is required","INVALID_INDEX_COLUMNS");return{name:Y.name,order:Y.order,collate:Y.collate}})}function VJ(J,Y,Z={}){let $=nY(Y),X=b(J),W=Z.indexName?Z.indexName:["idx",gJ(J),...$.map((F)=>gJ(F.name))].filter(Boolean).join("_").slice(0,120),G=b(W||"idx_auto"),U=$.map((F)=>{let A=b(F.name),E=F.order?` ${F.order}`:"",I=F.collate?` COLLATE ${b(F.collate).replace(/"/g,"")}`:"";return`${A}${I}${E}`}).join(", "),H=Z.ifNotExists===!1?"":" IF NOT EXISTS",_=Z.unique?"UNIQUE ":"",O=Z.where?.trim()?` WHERE ${Z.where.trim()}`:"";return`CREATE ${_}INDEX${H} ${G} ON ${X} (${U})${O}`}async function lY(J,Y,Z,$={}){let X=VJ(Y,Z,$);return lJ(J,X)}async function sY(J,Y,Z,$={}){let X=VJ(Y,Z,$);return jJ(J,X)}async function iY(J,Y,Z={}){let $=VJ(J,Y,Z);return aJ($,[],n(Z.batchSize))}function LJ(J,Y="query-plan"){switch(Y){case"raw":return`EXPLAIN ${J}`;case"analyze":return`EXPLAIN ANALYZE ${J}`;case"query-plan":default:return`EXPLAIN QUERY PLAN ${J}`}}async function tY(J,Y,Z=[],$={}){return iJ(J,LJ(Y,$.mode),Z)}async function aY(J,Y,Z=[],$={}){return YJ(J,LJ(Y,$.mode),Z)}async function rY(J,Y=[],Z={}){return ZJ(LJ(J,Z.mode),Y,n(Z.batchSize))}async function eY(J,Y){let Z=b(Y),$=await tJ(J,`SELECT COUNT(*) AS row_count FROM ${Z}`);if(!$||$.row_count===void 0||$.row_count===null)return 0;return Number($.row_count)||0}async function JZ(J,Y){let Z=b(Y),$=await AJ(J,`SELECT COUNT(*) AS row_count FROM ${Z}`);if(!$||$.row_count===void 0||$.row_count===null)return 0;return Number($.row_count)||0}async function YZ(J,Y=50){let Z=T(),$=n(Y),W=`SELECT COUNT(*) AS row_count FROM ${b(J)}`,G=[];for(let[_,O]of Object.entries(Z.shards)){if(!_||!O)continue;G.push(async()=>{try{let F=await O.prepare(W).first(),A=Number(F?.row_count??0);return{shard:_,count:Number.isFinite(A)?A:0,success:!0}}catch(F){return{shard:_,count:null,success:!1,error:F instanceof Error?F.message:String(F)}}})}let U=[];for(let _=0;_<G.length;_+=$){let O=G.slice(_,_+$).map((F)=>F());U.push(...await Promise.all(O))}return{total:U.reduce((_,O)=>_+(O.count??0),0),shards:U}}async function ZZ(J){let Y=T(),Z=await nJ(J,"read"),$=Y.shards[Z];if(!$)throw new j(`Shard ${Z} not found in configuration`,"SHARD_NOT_FOUND");return e($)}async function YY(J=50){let Y=T(),Z=n(J),$=[];for(let[W,G]of Object.entries(Y.shards)){if(!W||!G)continue;$.push(async()=>{try{return{shard:W,size:await e(G),success:!0}}catch(U){return{shard:W,size:null,success:!1,error:U instanceof Error?U.message:String(U)}}})}let X=[];for(let W=0;W<$.length;W+=Z){let G=$.slice(W,W+Z).map((U)=>U());X.push(...await Promise.all(G))}return X}async function $Z(J=50){return(await YY(J)).reduce((Z,$)=>Z+($.size??0),0)}q();class ZY{state;constructor(J){this.state=J}async getState(){return await this.state.storage.get("coordinator_state")||{knownShards:[],shardStats:{},strategy:"round-robin",roundRobinIndex:0}}async saveState(J){await this.state.storage.put("coordinator_state",J)}async fetch(J){let Z=new URL(J.url).pathname,$=J.method;try{switch(`${$} ${Z}`){case"GET /shards":return this.handleListShards();case"POST /shards":return this.handleAddShard(J);case"DELETE /shards":return this.handleRemoveShard(J);case"GET /stats":return this.handleGetStats();case"POST /stats":return this.handleUpdateStats(J);case"POST /allocate":return this.handleAllocateShard(J);case"POST /flush":return this.handleFlush();case"GET /health":return new Response("OK",{status:200});default:return new Response("Not Found",{status:404})}}catch(X){return console.error("ShardCoordinator error:",X),new Response("Internal Server Error",{status:500})}}async handleListShards(){let J=await this.getState();return new Response(JSON.stringify(J.knownShards),{headers:{"Content-Type":"application/json"}})}async handleAddShard(J){let{shard:Y}=await J.json();if(!Y||typeof Y!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let Z=await this.getState();if(!Z.knownShards.includes(Y))Z.knownShards.push(Y),Z.shardStats[Y]={binding:Y,count:0,lastUpdated:Date.now()},await this.saveState(Z);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleRemoveShard(J){let{shard:Y}=await J.json();if(!Y||typeof Y!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let Z=await this.getState(),$=Z.knownShards.indexOf(Y);if($>-1){if(Z.knownShards.splice($,1),delete Z.shardStats[Y],Z.roundRobinIndex>=Z.knownShards.length)Z.roundRobinIndex=0;await this.saveState(Z)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleGetStats(){let J=await this.getState(),Y=Object.values(J.shardStats);return new Response(JSON.stringify(Y),{headers:{"Content-Type":"application/json"}})}async handleUpdateStats(J){let{shard:Y,count:Z}=await J.json();if(!Y||typeof Y!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if(Z===void 0||typeof Z!=="number")return new Response(JSON.stringify({error:"Missing or invalid count parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let $=await this.getState();if($.shardStats[Y])$.shardStats[Y].count=Z,$.shardStats[Y].lastUpdated=Date.now(),await this.saveState($);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleAllocateShard(J){let{primaryKey:Y,strategy:Z,operationType:$,availableShards:X}=await J.json();if(!Y||typeof Y!=="string")return new Response(JSON.stringify({error:"Missing or invalid primaryKey parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let W=await this.getState(),G=X||W.knownShards;if(G.length===0)return new Response(JSON.stringify({error:"No shards available"}),{status:400,headers:{"Content-Type":"application/json"}});let U=this.resolveStrategy(W.strategy,Z,$||"write"),H=this.selectShard(Y,W,U,G);if(U==="round-robin")W.roundRobinIndex=(W.roundRobinIndex+1)%G.length,await this.saveState(W);return new Response(JSON.stringify({shard:H}),{headers:{"Content-Type":"application/json"}})}async handleFlush(){return await this.state.storage.deleteAll(),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}resolveStrategy(J,Y,Z="write"){if(Y)return Y;if(typeof J==="string")return J;return J[Z]}selectShard(J,Y,Z,$){let X=$||Y.knownShards;if(X.length===0)throw new j("No shards available","NO_SHARDS");switch(Z){case"round-robin":return X[Y.roundRobinIndex]??X[0];case"random":return X[Math.floor(Math.random()*X.length)];case"hash":{let W=0;for(let U=0;U<J.length;U++){let H=J.charCodeAt(U);W=(W<<5)-W+H,W=W&W}let G=Math.abs(W)%X.length;return X[G]}case"location":{let W=Y.targetRegion,G=Y.shardLocations||{},U=X.filter((V)=>G[V]);if(!W||U.length===0){let V=0;for(let z=0;z<J.length;z++){let R=J.charCodeAt(z);V=(V<<5)-V+R,V=V&V}let L=Math.abs(V)%X.length;return X[L]}let H={wnam:{lat:37.7749,lon:-122.4194},enam:{lat:40.7357,lon:-74.1724},weur:{lat:51.5074,lon:-0.1278},eeur:{lat:52.2297,lon:21.0122},apac:{lat:35.6762,lon:139.6503},oc:{lat:-33.8688,lon:151.2093},me:{lat:25.2048,lon:55.2708},af:{lat:-26.2041,lon:28.0473}},_=(V,L)=>(L in V),O=(V)=>_(H,V)?V:"wnam",F=(V,L)=>{let z=H[O(V)],R=H[O(L)],P=z.lat-R.lat,Q=z.lon-R.lon;return Math.sqrt(P*P+Q*Q)},A=U.map((V)=>{let L=G[V],z=F(W,L.region),R=L.priority||1;return{shard:V,score:z-R*0.1}});A.sort((V,L)=>V.score-L.score);let E=A[0].score,I=A.filter((V)=>Math.abs(V.score-E)<0.01);if(I.length===1)return I[0].shard;let M=0;for(let V=0;V<J.length;V++){let L=J.charCodeAt(V);M=(M<<5)-M+L,M=M&M}let C=Math.abs(M)%I.length;return I[C].shard}default:return X[0]}}async incrementShardCount(J){let Y=await this.getState();if(Y.shardStats[J])Y.shardStats[J].count++,Y.shardStats[J].lastUpdated=Date.now(),await this.saveState(Y)}async decrementShardCount(J){let Y=await this.getState();if(Y.shardStats[J]&&Y.shardStats[J].count>0)Y.shardStats[J].count--,Y.shardStats[J].lastUpdated=Date.now(),await this.saveState(Y)}}q();c();q();var XZ=500;function WY(J,Y={}){let Z=Y.scanCount??XZ;return{async get($,X="text"){let W=await J.get($);if(W===null)return null;if(X!=="json")return W;try{return JSON.parse(W)}catch(G){throw new j(`Failed to parse JSON from Redis for key ${$}: ${G instanceof Error?G.message:String(G)}`,"KV_JSON_PARSE_FAILED")}},async put($,X){await J.set($,X)},async delete($){await J.del($)},async list($){let X=$?.prefix??"",W=`${X}*`,G=$?.cursor??"0",U=$?.limit,H=[];do{let _=await jZ(J,G,W,Z);G=_.cursor;for(let O of _.keys){if(!X||O.startsWith(X))H.push(O);if(U&&H.length>=U)break}if(U&&H.length>=U)break}while(G!=="0");return{keys:H.map((_)=>({name:_})),cursor:G,list_complete:G==="0"}}}}function WZ(J,Y={}){return WY(J,Y)}function GY(J,Y){if(Y)return XJ(J,Y);return{prepare(Z){return new DJ(J,Z)}}}function UY(J,Y){if(Y)return XJ(J,Y);return{prepare(Z){return new RJ(J,Z)}}}function GZ(J,Y){if(Y)return XJ(J,Y);return{prepare(Z){return new zJ(J,Z)}}}function XJ(J,Y){return{prepare(Z){return new MJ(J,Y,Z)}}}function UZ(J){return{async get(Y,Z="text"){let $=await EZ(J,Y);if($===null||$===void 0)return null;if(Z==="json"){if(typeof $==="string")try{return JSON.parse($)}catch(X){throw new j(`Failed to parse JSON from NuxtHub KV for key ${Y}: ${X instanceof Error?X.message:String(X)}`,"KV_JSON_PARSE_FAILED")}return $}return typeof $==="string"?$:JSON.stringify($)},async put(Y,Z){await IZ(J,Y,Z)},async delete(Y){await QZ(J,Y)},async list(Y){let Z=Y?.prefix??"",$=await PZ(J,Z);return{keys:(typeof Y?.limit==="number"?$.slice(0,Y.limit):$).map((W)=>({name:W})),list_complete:!0}}}}function HZ(J,Y){return GY({query:async($,X=[])=>{let W=Y(J.connectionString);if(typeof W.connect==="function")await W.connect();try{return await W.query($,X)}finally{if(typeof W.release==="function")W.release();else if(typeof W.end==="function")await W.end()}}})}function _Z(J,Y){return UY({execute:async($,X=[])=>{let W=Y(J.connectionString);try{if(typeof W.execute==="function")return await W.execute($,X);if(typeof W.query==="function")return await W.query($,X);throw new j("Hyperdrive MySQL client is missing execute/query methods","MYSQL_CLIENT_INVALID")}finally{if(typeof W.end==="function")await W.end();else if(typeof W.close==="function")await W.close();else if(typeof W.destroy==="function")W.destroy()}}})}function OZ(J){if(!J||typeof J!=="object")return!1;return typeof J.prepare==="function"}function FZ(J){if(!J||typeof J!=="object")return!1;let Y=J;return typeof Y.get==="function"&&typeof Y.put==="function"&&typeof Y.delete==="function"&&typeof Y.list==="function"}class DJ{client;sql;bindings;constructor(J,Y,Z=[]){this.client=J,this.sql=Y,this.bindings=Z}bind(...J){return new DJ(this.client,this.sql,J)}async run(){let J=Date.now(),Y=TJ(this.sql),Z=await this.client.query(Y,this.bindings);return{success:!0,results:Z.rows??[],meta:x(J,{changes:typeof Z.rowCount==="number"?Z.rowCount:void 0,command:Z.command})}}async all(){let J=Date.now(),Y=TJ(this.sql),Z=await this.client.query(Y,this.bindings);return{success:!0,results:Z.rows??[],meta:x(J,{changes:typeof Z.rowCount==="number"?Z.rowCount:void 0,command:Z.command})}}async first(){let J=TJ(this.sql);return(await this.client.query(J,this.bindings)).rows?.[0]??null}}class RJ{client;sql;bindings;constructor(J,Y,Z=[]){this.client=J,this.sql=Y,this.bindings=Z}bind(...J){return new RJ(this.client,this.sql,J)}async run(){let J=Date.now(),Y=await EJ(this.client,this.sql,this.bindings);if(Array.isArray(Y))return{success:!0,results:Y,meta:x(J)};let Z=Y;return{success:!0,results:[],meta:x(J,{changes:Z.affectedRows,last_row_id:Z.insertId,warningStatus:Z.warningStatus})}}async all(){let J=Date.now(),Y=await EJ(this.client,this.sql,this.bindings);return{success:!0,results:Array.isArray(Y)?Y:[],meta:x(J,{changes:!Array.isArray(Y)?Y.affectedRows:void 0})}}async first(){let J=await EJ(this.client,this.sql,this.bindings);if(!Array.isArray(J)||J.length===0)return null;return J[0]}}class zJ{client;sql;bindings;constructor(J,Y,Z=[]){this.client=J,this.sql=Y,this.bindings=Z}bind(...J){return new zJ(this.client,this.sql,J)}async run(){let J=Date.now();if(typeof this.client.execute==="function"){let X=await this.client.execute(this.sql,this.bindings);return{success:!0,results:PJ(X),meta:x(J)}}let Y=this.client.prepare?.(this.sql);if(!Y||typeof Y.run!=="function")throw new j("SQLite client must expose execute() or prepare().run()","SQLITE_CLIENT_INVALID");let $=await Y.run(...this.bindings)??{};return{success:!0,results:[],meta:x(J,{changes:$J($.changes),last_row_id:$.lastInsertRowid??$.lastID})}}async all(){let J=Date.now();if(typeof this.client.execute==="function"){let $=await this.client.execute(this.sql,this.bindings);return{success:!0,results:PJ($),meta:x(J)}}let Y=this.client.prepare?.(this.sql);if(!Y||typeof Y.all!=="function")throw new j("SQLite client must expose execute() or prepare().all()","SQLITE_CLIENT_INVALID");let Z=await Y.all(...this.bindings);return{success:!0,results:Array.isArray(Z)?Z:[],meta:x(J)}}async first(){if(typeof this.client.execute==="function"){let Y=await this.client.execute(this.sql,this.bindings);return PJ(Y)[0]??null}let J=this.client.prepare?.(this.sql);if(!J)throw new j("SQLite client must expose execute() or prepare().get()","SQLITE_CLIENT_INVALID");if(typeof J.get==="function"){let Y=await J.get(...this.bindings);return Y===void 0||Y===null?null:Y}if(typeof J.all==="function"){let Y=await J.all(...this.bindings);if(!Array.isArray(Y)||Y.length===0)return null;let Z=Y[0];return Z===void 0||Z===null?null:Z}throw new j("SQLite prepare() result must expose get() or all()","SQLITE_CLIENT_INVALID")}}class MJ{client;sqlTag;sqlText;bindings;constructor(J,Y,Z,$=[]){this.client=J,this.sqlTag=Y,this.sqlText=Z,this.bindings=$}bind(...J){return new MJ(this.client,this.sqlTag,this.sqlText,J)}async run(){let J=Date.now(),Y=IJ(this.sqlTag,this.sqlText,this.bindings),Z=await AZ(this.client,Y);return{success:!0,results:QJ(Z),meta:x(J,XY(Z))}}async all(){let J=Date.now(),Y=IJ(this.sqlTag,this.sqlText,this.bindings),Z=await HY(this.client,Y);return{success:!0,results:QJ(Z),meta:x(J,XY(Z))}}async first(){let J=IJ(this.sqlTag,this.sqlText,this.bindings),Y=await VZ(this.client,J),Z=QJ(Y);if(Z.length>0)return Z[0]??null;if(Y&&typeof Y==="object"&&"row"in Y){let $=Y.row;return $===void 0||$===null?null:$}if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&!("rows"in Y)&&!("results"in Y)&&!("data"in Y))return Y;return null}}async function jZ(J,Y,Z,$){try{let X=await J.scan(Y,{MATCH:Z,COUNT:$});return $Y(X)}catch{let X=await J.scan(Y,"MATCH",Z,"COUNT",String($));return $Y(X)}}function $Y(J){if(Array.isArray(J))return{cursor:String(J[0]??"0"),keys:Array.isArray(J[1])?J[1]:[]};return{cursor:String(J.cursor??"0"),keys:Array.isArray(J.keys)?J.keys:[]}}async function EJ(J,Y,Z){if(typeof J.execute==="function"){let $=await J.execute(Y,Z);if(Array.isArray($))return $[0];return $}if(typeof J.query==="function"){let $=await J.query(Y,Z);if(Array.isArray($))return $[0];return $}throw new j("MySQL client must expose execute() or query()","MYSQL_CLIENT_INVALID")}async function AZ(J,Y){if(typeof J.run==="function")return await J.run(Y);if(typeof J.execute==="function")return await J.execute(Y);if(typeof J.all==="function")return await J.all(Y);throw new j("Drizzle client must expose run(), execute(), or all()","DRIZZLE_CLIENT_INVALID")}async function HY(J,Y){if(typeof J.all==="function")return await J.all(Y);if(typeof J.execute==="function")return await J.execute(Y);if(typeof J.run==="function")return await J.run(Y);throw new j("Drizzle client must expose all(), execute(), or run()","DRIZZLE_CLIENT_INVALID")}async function VZ(J,Y){if(typeof J.get==="function")return await J.get(Y);return await HY(J,Y)}function IJ(J,Y,Z){let $=LZ(Y),X=$.length-1;if(X!==Z.length)throw new j(`Drizzle binding mismatch: expected ${X} bindings, received ${Z.length}`,"DRIZZLE_BINDINGS_MISMATCH");if(X===0)return J.raw(Y);let W=typeof J.empty==="function"?J.empty():J.raw("");for(let G=0;G<$.length;G++){let U=$[G];if(U)W.append(J.raw(U));if(G<X)W.append(J`${Z[G]}`)}return W}function LZ(J){let Y=[],Z=0,$=!1,X=!1,W=!1,G=!1;for(let U=0;U<J.length;U++){let H=J[U],_=U+1<J.length?J[U+1]:"";if(W){if(H===`
|
|
17
|
+
`)W=!1;continue}if(G){if(H==="*"&&_==="/")U++,G=!1;continue}if(!$&&!X){if(H==="-"&&_==="-"){U++,W=!0;continue}if(H==="/"&&_==="*"){U++,G=!0;continue}}if(H==="'"&&!X){if($&&_==="'"){U++;continue}$=!$;continue}if(H==='"'&&!$){if(X&&_==='"'){U++;continue}X=!X;continue}if(H==="?"&&!$&&!X)Y.push(J.slice(Z,U)),Z=U+1}return Y.push(J.slice(Z)),Y}function QJ(J){let Y=($)=>{if(!$||typeof $!=="object"||Array.isArray($))return;let X=$;if(Array.isArray(X.rows))return X.rows;if(Array.isArray(X.results))return X.results;if(Array.isArray(X.data))return X.data;return},Z=($)=>{if(!$||typeof $!=="object"||Array.isArray($))return!1;return Object.keys($).length>0};if(Array.isArray(J)){if(J.length===2){let $=Y(J[0]);if($)return $;let X=Y(J[1]);if(X)return X;if(!Array.isArray(J[0])&&!Array.isArray(J[1])){if(Z(J[0]))return[J[0]];if(Z(J[1]))return[J[1]]}if(Array.isArray(J[0]))return J[0];if(Array.isArray(J[1]))return J[1]}return J}if(J&&typeof J==="object"){let $=Y(J);if($)return $}return[]}function XY(J){if(!J)return{};let Y;if(Array.isArray(J)){if(J.length===2){if(J[0]&&typeof J[0]==="object"&&!Array.isArray(J[0]))Y=J[0];else if(J[1]&&typeof J[1]==="object"&&!Array.isArray(J[1]))Y=J[1]}}else if(typeof J==="object"&&!Array.isArray(J))Y=J;if(!Y)return{};let Z={},$=$J(Y.rowCount)??$J(Y.changes)??$J(Y.affectedRows);if($!==void 0)Z.changes=$;let X=Y.lastInsertRowid??Y.lastInsertId??Y.lastID??Y.lastRowID??Y.insertId??Y.insertID;if(typeof X==="number"||typeof X==="string")Z.last_row_id=X;if(Y.meta&&typeof Y.meta==="object")Object.assign(Z,Y.meta);return Z}async function EZ(J,Y){if(typeof J.get==="function")return await J.get(Y);if(typeof J.getItem==="function")return await J.getItem(Y);throw new j("NuxtHub KV client must expose get() or getItem()","NUXTHUB_KV_CLIENT_INVALID")}async function IZ(J,Y,Z){if(typeof J.set==="function"){await J.set(Y,Z);return}if(typeof J.setItem==="function"){await J.setItem(Y,Z);return}throw new j("NuxtHub KV client must expose set() or setItem()","NUXTHUB_KV_CLIENT_INVALID")}async function QZ(J,Y){if(typeof J.del==="function"){await J.del(Y);return}if(typeof J.removeItem==="function"){await J.removeItem(Y);return}throw new j("NuxtHub KV client must expose del() or removeItem()","NUXTHUB_KV_CLIENT_INVALID")}async function PZ(J,Y){let Z;if(typeof J.keys==="function")Z=await J.keys(Y);else if(typeof J.getKeys==="function")Z=await J.getKeys(Y);else throw new j("NuxtHub KV client must expose keys() or getKeys()","NUXTHUB_KV_CLIENT_INVALID");if(!Array.isArray(Z))return[];if(!Y)return[...Z];return Z.filter(($)=>$.startsWith(Y))}function PJ(J){if(Array.isArray(J))return J;if(J&&typeof J==="object"){let Y=J;if(Array.isArray(Y.rows))return Y.rows;if(Array.isArray(Y.results))return Y.results}return[]}function x(J,Y={}){return{duration:Date.now()-J,...Y}}function $J(J){if(typeof J==="number"&&Number.isFinite(J))return J;return}var l=new Map;function TJ(J){let Y=l.get(J);if(Y)return Y;let Z="",$=0,X=!1,W=!1,G=!1,U=!1;for(let H=0;H<J.length;H++){let _=J[H],O=H+1<J.length?J[H+1]:"";if(G){if(Z+=_,_===`
|
|
18
|
+
`)G=!1;continue}if(U){if(Z+=_,_==="*"&&O==="/")Z+="/",H++,U=!1;continue}if(!X&&!W){if(_==="-"&&O==="-"){Z+="--",H++,G=!0;continue}if(_==="/"&&O==="*"){Z+="/*",H++,U=!0;continue}}if(_==="'"&&!W){X=!X,Z+=_;continue}if(_==='"'&&!X){W=!W,Z+=_;continue}if(_==="?"&&!X&&!W){$++,Z+=`$${$}`;continue}Z+=_}if(l.set(J,Z),l.size>5000){let H=l.keys().next().value;if(H)l.delete(H)}return Z}q();class D{static tokenize(J){return J.trim().split(/\s+/).map((Y)=>Y.toLowerCase())}static extractTableName(J){let Y=this.tokenize(J);if(Y[0]==="create"&&Y[1]==="table"){let W=2;if(Y[W]==="if")W+=3;return Y[W]??null}if(Y[0]==="drop"&&Y[1]==="table"){let W=2;if(Y[W]==="if")W+=2;return Y[W]??null}let Z=Y.indexOf("from"),$=Y.indexOf("into"),X=Y.indexOf("update");if(Z>=0&&Z+1<Y.length)return Y[Z+1]??null;if($>=0&&$+1<Y.length)return Y[$+1]??null;if(X>=0&&X+1<Y.length)return Y[X+1]??null;return null}static isSelect(J){return this.tokenize(J)[0]==="select"}static isInsert(J){return this.tokenize(J)[0]==="insert"}static isCreateTable(J){let Y=this.tokenize(J);return Y[0]==="create"&&Y[1]==="table"}static isDropTable(J){let Y=this.tokenize(J);return Y[0]==="drop"&&Y[1]==="table"}static isDelete(J){return this.tokenize(J)[0]==="delete"}static isUpdate(J){return this.tokenize(J)[0]==="update"}static hasIdWhereClause(J){return J.includes("WHERE")&&J.includes("id")}static hasAutoIncrement(J){return J.includes("AUTOINCREMENT")||J.includes("AUTO_INCREMENT")||J.includes("GENERATED BY DEFAULT AS IDENTITY")}static hasReturning(J){return J.includes("RETURNING")}}class BJ{tables=new Map;schemas=new Map;autoIncrementCounters=new Map;lastInsertRowId=null;prepare(J){return new _Y(this,J)}async executeStatement(J,Y){let Z=Date.now();try{if(D.isCreateTable(J))return await this.handleCreateTable(J,Y);if(D.isDropTable(J))return await this.handleDropTable(J,Y);if(D.isInsert(J))return await this.handleInsert(J,Y);if(D.isUpdate(J))return await this.handleUpdate(J,Y);if(D.isDelete(J))return await this.handleDelete(J,Y);if(D.isSelect(J))return await this.handleSelect(J,Y);return{success:!0,results:[],meta:{duration:Date.now()-Z}}}catch($){let X=$ instanceof Error?$.message:String($);return{success:!1,results:[],meta:{duration:Date.now()-Z},error:X}}}async executeQuery(J,Y){let Z=Date.now();try{if(D.isSelect(J))return await this.handleSelect(J,Y);return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Use executeStatement for non-SELECT queries"}}catch($){let X=$ instanceof Error?$.message:String($);return{success:!1,results:[],meta:{duration:Date.now()-Z},error:X}}}async handleCreateTable(J,Y){let Z=Date.now(),$=D.extractTableName(J);if(!$)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Could not extract table name"};let X=new Map,W=J.match(/\((.*)\)/s);if(!W||!W[1])return this.tables.set($,new Map),this.schemas.set($,X),{success:!0,results:[],meta:{duration:Date.now()-Z}};let G=W[1],U=/(\w+)\s+([A-Z_]+)(\s+[^,)]*)?/gi,H;while((H=U.exec(G))!==null){let _=H[1]||"",O=H[2]||"",F=H[3]||"";X.set(_,{name:_,type:O,isPrimaryKey:F.includes("PRIMARY KEY"),isAutoIncrement:F.includes("AUTOINCREMENT")||F.includes("AUTO_INCREMENT")||F.includes("GENERATED BY DEFAULT AS IDENTITY")})}if(this.tables.set($,new Map),this.schemas.set($,X),D.hasAutoIncrement(J))this.autoIncrementCounters.set($,0);return{success:!0,results:[],meta:{duration:Date.now()-Z}}}async handleDropTable(J,Y){let Z=Date.now(),$=D.extractTableName(J);if(!$)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Could not extract table name"};return this.tables.delete($),this.schemas.delete($),this.autoIncrementCounters.delete($),{success:!0,results:[],meta:{duration:Date.now()-Z}}}async handleInsert(J,Y){let Z=Date.now(),$=D.extractTableName(J);if(!$)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Could not extract table name"};if(!this.tables.has($))this.tables.set($,new Map);let X=this.tables.get($),W=this.schemas.get($),G=Y[0];if(!G)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"No primary key value provided"};let U={};if(W){let O=0;for(let[F,A]of W)if(O<Y.length)U[F]=Y[O],O++}else for(let O=0;O<Y.length;O++)if(O===0)U.id=Y[O];else U[`column_${O}`]=Y[O];return X.set(String(G),U),this.lastInsertRowId=G,{success:!0,results:D.hasReturning(J)?[U]:[],meta:{duration:Date.now()-Z,last_row_id:G,changes:1}}}async handleUpdate(J,Y){let Z=Date.now(),$=D.extractTableName(J);if(!$)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Could not extract table name"};if(!this.tables.has($))return{success:!1,results:[],meta:{duration:Date.now()-Z},error:`Table ${$} not found`};let X=this.tables.get($);if(!D.hasIdWhereClause(J))return{success:!0,results:[],meta:{duration:Date.now()-Z,changes:0}};let W=Y[Y.length-1],G=X.get(String(W));if(!G)return{success:!0,results:[],meta:{duration:Date.now()-Z,changes:0}};for(let U=0;U<Y.length-1;U++){let H=this.extractSetColumnName(J,U);if(H)G[H]=Y[U]}return{success:!0,results:[],meta:{duration:Date.now()-Z,changes:1}}}extractSetColumnName(J,Y){let Z=J.match(/SET\s+([^W]+?)(?:WHERE|$)/i);if(!Z||!Z[1])return null;return Z[1].split(",").map((W)=>{let G=W.match(/(\w+)\s*=/);return G&&G[1]?G[1]:null})[Y]??null}async handleDelete(J,Y){let Z=Date.now(),$=D.extractTableName(J);if(!$)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Could not extract table name"};if(!this.tables.has($))return{success:!0,results:[],meta:{duration:Date.now()-Z,changes:0}};let X=this.tables.get($);if(!D.hasIdWhereClause(J)){let U=X.size;return X.clear(),{success:!0,results:[],meta:{duration:Date.now()-Z,changes:U}}}let W=Y[0],G=X.has(String(W));if(G)X.delete(String(W));return{success:!0,results:[],meta:{duration:Date.now()-Z,changes:G?1:0}}}async handleSelect(J,Y){let Z=Date.now(),$=D.extractTableName(J);if(!$)return{success:!1,results:[],meta:{duration:Date.now()-Z},error:"Could not extract table name"};if(!this.tables.has($))return{success:!0,results:[],meta:{duration:Date.now()-Z}};let X=this.tables.get($);if(J.includes("COUNT(*)")){let U=J.match(/COUNT\(\*\)\s+as\s+(\w+)/i)?.[1]??"COUNT(*)",H={};return H[U]=X.size,{success:!0,results:[H],meta:{duration:Date.now()-Z}}}let W=Array.from(X.values());if(D.hasIdWhereClause(J)&&Y.length>0){let G=Y[0],U=X.get(String(G));W=U?[U]:[]}return{success:!0,results:W,meta:{duration:Date.now()-Z}}}}class _Y{database;sql;bindings=[];constructor(J,Y){this.database=J;this.sql=Y}bind(...J){return this.bindings=J,this}async run(){return await this.database.executeStatement(this.sql,this.bindings)}async all(){return await this.database.executeQuery(this.sql,this.bindings)}async first(){return(await this.database.executeQuery(this.sql,this.bindings)).results[0]||null}}class wJ{store=new Map;expirations=new Map;async get(J,Y="text"){let Z=this.expirations.get(J);if(Z&&Z<Date.now())return this.store.delete(J),this.expirations.delete(J),null;let $=this.store.get(J);if($===void 0)return null;if(Y==="json")try{return JSON.parse($)}catch(X){throw new j(`Failed to parse JSON from KV for key ${J}: ${X instanceof Error?X.message:String(X)}`,"KV_JSON_PARSE_FAILED")}return $}async put(J,Y,Z){if(this.store.set(J,Y),Z?.expirationTtl)this.expirations.set(J,Date.now()+Z.expirationTtl*1000);else this.expirations.delete(J)}async delete(J){this.store.delete(J),this.expirations.delete(J)}async list(J){let Y=J?.prefix??"",Z=J?.limit??1000,$=J?.cursor?parseInt(J.cursor,10):0,X=Date.now();for(let[_,O]of this.expirations)if(O<X)this.store.delete(_),this.expirations.delete(_);let W=Array.from(this.store.keys()).filter((_)=>_.startsWith(Y)),G=W.slice($,$+Z).map((_)=>({name:_})),U=$+Z,H=U>=W.length;return{keys:G,cursor:H?void 0:String(U),list_complete:H}}clear(){this.store.clear(),this.expirations.clear()}size(){return this.store.size}}function TZ(){return new BJ}function DZ(){return new wJ}d();export{a as validateTableForSharding,FJ as schemaExists,jJ as runShard,aJ as runAllShards,lJ as run,TY as resetConfig,bY as reassignShard,JJ as prepare,SJ as migrateRecord,p as listTables,hY as listKnownShards,OZ as isSQLDatabase,FZ as isKVStorage,fJ as integrateExistingDatabase,SY as insertShard,qY as insert,mJ as initializeAsync,QY as initialize,sY as indexShard,iY as indexAllShards,lY as index,$Z as getTotalDatabaseSize,pY as getShardStats,YY as getDatabaseSizesAllShards,dY as getDatabaseSizeForShard,ZZ as getDatabaseSizeForKey,zY as getClosestRegionFromIP,cY as flush,AJ as firstShard,fY as firstByLookupKey,mY as firstAllShardsGlobal,JY as firstAllShards,tJ as first,aY as explainShard,rY as explainAllShards,tY as explain,qJ as dropSchema,t as discoverExistingRecordsWithColumns,i as discoverExistingPrimaryKeys,WZ as createValkeyKVProvider,kJ as createSchemaAcrossShards,xY as createSchema,GZ as createSQLiteProvider,WY as createRedisKVProvider,GY as createPostgreSQLProvider,UZ as createNuxtHubKVProvider,UY as createMySQLProvider,KJ as createMappingsForExistingKeys,TZ as createInMemorySQLProvider,DZ as createInMemoryKVProvider,HZ as createHyperdrivePostgresProvider,_Z as createHyperdriveMySQLProvider,XJ as createDrizzleSQLProvider,JZ as countShard,YZ as countAllShards,eY as count,PY as collegedb,yJ as clearShardMigrationCache,pJ as clearMigrationCache,hJ as checkMigrationNeeded,bJ as autoDetectAndMigrate,YJ as allShard,KY as allByLookupKey,eJ as allAllShardsGlobal,ZJ as allAllShards,iJ as all,ZY as ShardCoordinator,K as KVShardMapper,BJ as InMemorySQLDatabase,wJ as InMemoryKVStorage,j as CollegeDBError};
|
|
19
19
|
|
|
20
|
-
//# debugId=
|
|
20
|
+
//# debugId=C7AC24BF7882481C64756E2164756E21
|
|
21
21
|
//# sourceMappingURL=index.js.map
|