@earth-app/collegedb 1.0.8 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/durable.d.ts CHANGED
@@ -7,10 +7,14 @@
7
7
  *
8
8
  * @example
9
9
  * ```typescript
10
- * // In wrangler.toml:
11
- * [[durable_objects.bindings]]
12
- * name = "ShardCoordinator"
13
- * class_name = "ShardCoordinator"
10
+ * // In wrangler.jsonc:
11
+ * // {
12
+ * // "durable_objects": {
13
+ * // "bindings": [
14
+ * // { "name": "ShardCoordinator", "class_name": "ShardCoordinator" }
15
+ * // ]
16
+ * // }
17
+ * // }
14
18
  *
15
19
  * // Usage in a Worker:
16
20
  * const coordinatorId = env.ShardCoordinator.idFromName('default');
@@ -1 +1 @@
1
- {"version":3,"file":"durable.d.ts","sourceRoot":"","sources":["../src/durable.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAIpE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,gBAAgB;IAC5B;;;OAGG;IACH,OAAO,CAAC,KAAK,CAAqB;IAElC;;;OAGG;gBACS,KAAK,EAAE,kBAAkB;IAIrC;;;;;;;;;;OAUG;YACW,QAAQ;IAYtB;;;;;;;;;;OAUG;YACW,SAAS;IAIvB;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACG,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgChD;;;;;;OAMG;YACW,gBAAgB;IAO9B;;;;;;;;;OASG;YACW,cAAc;IA4B5B;;;;;;;;;OASG;YACW,iBAAiB;IA6B/B;;;;;;OAMG;YACW,cAAc;IAQ5B;;;;;;;;OAQG;YACW,iBAAiB;IA+B/B;;;;;;;;;;;;;;;OAeG;YACW,mBAAmB;IAsCjC;;;;;;;;;;OAUG;YACW,WAAW;IAOzB;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAmBvB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,OAAO,CAAC,WAAW;IAgGnB;;;;;;;;;;;OAWG;IACG,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASvD;;;;;;;;;;;OAWG;IACG,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAQvD"}
1
+ {"version":3,"file":"durable.d.ts","sourceRoot":"","sources":["../src/durable.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAIpE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,gBAAgB;IAC5B;;;OAGG;IACH,OAAO,CAAC,KAAK,CAAqB;IAElC;;;OAGG;gBACS,KAAK,EAAE,kBAAkB;IAIrC;;;;;;;;;;OAUG;YACW,QAAQ;IAYtB;;;;;;;;;;OAUG;YACW,SAAS;IAIvB;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACG,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgChD;;;;;;OAMG;YACW,gBAAgB;IAO9B;;;;;;;;;OASG;YACW,cAAc;IA4B5B;;;;;;;;;OASG;YACW,iBAAiB;IA6B/B;;;;;;OAMG;YACW,cAAc;IAQ5B;;;;;;;;OAQG;YACW,iBAAiB;IA+B/B;;;;;;;;;;;;;;;OAeG;YACW,mBAAmB;IAsCjC;;;;;;;;;;OAUG;YACW,WAAW;IAOzB;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAmBvB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,OAAO,CAAC,WAAW;IAgGnB;;;;;;;;;;;OAWG;IACG,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASvD;;;;;;;;;;;OAWG;IACG,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAQvD"}
package/dist/errors.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @example
9
9
  * ```typescript
10
- * import { CollegeDBError } from './errors.js';
10
+ * import { CollegeDBError } from './errors';
11
11
  *
12
12
  * throw new CollegeDBError('Failed to allocate shard', 'SHARD_ALLOCATION_ERROR');
13
13
  * ```
package/dist/index.d.ts CHANGED
@@ -8,10 +8,11 @@
8
8
  * @author Gregory Mitchell
9
9
  * @license MIT
10
10
  */
11
- export { all, allAllShards, allShard, collegedb, createSchema, first, firstAllShards, firstShard, flush, getClosestRegionFromIP, getDatabaseSizeForShard, getShardStats, initialize, initializeAsync, listKnownShards, prepare, reassignShard, resetConfig, run, runAllShards, runShard } from './router.js';
12
- export { ShardCoordinator } from './durable.js';
13
- export { CollegeDBError } from './errors.js';
14
- export { KVShardMapper } from './kvmap.js';
15
- export { autoDetectAndMigrate, checkMigrationNeeded, clearMigrationCache, clearShardMigrationCache, createMappingsForExistingKeys, createSchemaAcrossShards, discoverExistingPrimaryKeys, discoverExistingRecordsWithColumns, dropSchema, integrateExistingDatabase, listTables, migrateRecord, schemaExists, validateTableForSharding, type IntegrationOptions, type IntegrationResult, type ValidationResult } from './migrations.js';
16
- export type { CollegeDBConfig, D1Region, Env, MixedShardingStrategy, OperationType, ShardCoordinatorState, ShardLocation, ShardMapping, ShardStats, ShardingStrategy } from './types.js';
11
+ export { all, allAllShards, allShard, collegedb, createSchema, first, firstAllShards, firstShard, flush, getClosestRegionFromIP, getDatabaseSizeForShard, getShardStats, initialize, initializeAsync, listKnownShards, prepare, reassignShard, resetConfig, run, runAllShards, runShard } from './router';
12
+ export { ShardCoordinator } from './durable';
13
+ export { CollegeDBError } from './errors';
14
+ export { KVShardMapper } from './kvmap';
15
+ export { createDrizzleSQLProvider, createHyperdriveMySQLProvider, createHyperdrivePostgresProvider, createMySQLProvider, createNuxtHubKVProvider, createPostgreSQLProvider, createRedisKVProvider, createSQLiteProvider, createValkeyKVProvider, isKVStorage, isSQLDatabase, type DrizzleClientLike, type DrizzleSqlChunkLike, type DrizzleSqlTagLike, type HyperdriveBindingLike, type HyperdriveMySQLClientFactory, type HyperdrivePostgresClientFactory, type MySQLClientLike, type NuxtHubKVLike, type PostgresClientLike, type RedisLikeClient, type SQLiteClientLike } from './providers';
16
+ export { autoDetectAndMigrate, checkMigrationNeeded, clearMigrationCache, clearShardMigrationCache, createMappingsForExistingKeys, createSchemaAcrossShards, discoverExistingPrimaryKeys, discoverExistingRecordsWithColumns, dropSchema, integrateExistingDatabase, listTables, migrateRecord, schemaExists, validateTableForSharding, type IntegrationOptions, type IntegrationResult, type ValidationResult } from './migrations';
17
+ export type { CollegeDBConfig, D1Region, Env, KVListResult, KVStorage, MixedShardingStrategy, OperationType, PreparedStatement, QueryResult, QueryResultMeta, SQLDatabase, ShardCoordinatorState, ShardLocation, ShardMapping, ShardStats, ShardingStrategy } from './types';
17
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EACN,GAAG,EACH,YAAY,EACZ,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,KAAK,EACL,cAAc,EACd,UAAU,EACV,KAAK,EACL,sBAAsB,EACtB,uBAAuB,EACvB,aAAa,EACb,UAAU,EACV,eAAe,EACf,eAAe,EACf,OAAO,EACP,aAAa,EACb,WAAW,EACX,GAAG,EACH,YAAY,EACZ,QAAQ,EACR,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAG3C,OAAO,EACN,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,wBAAwB,EACxB,6BAA6B,EAC7B,wBAAwB,EACxB,2BAA2B,EAC3B,kCAAkC,EAClC,UAAU,EACV,yBAAyB,EACzB,UAAU,EACV,aAAa,EACb,YAAY,EACZ,wBAAwB,EACxB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACX,eAAe,EACf,QAAQ,EACR,GAAG,EACH,qBAAqB,EACrB,aAAa,EACb,qBAAqB,EACrB,aAAa,EACb,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EACN,GAAG,EACH,YAAY,EACZ,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,KAAK,EACL,cAAc,EACd,UAAU,EACV,KAAK,EACL,sBAAsB,EACtB,uBAAuB,EACvB,aAAa,EACb,UAAU,EACV,eAAe,EACf,eAAe,EACf,OAAO,EACP,aAAa,EACb,WAAW,EACX,GAAG,EACH,YAAY,EACZ,QAAQ,EACR,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGxC,OAAO,EACN,wBAAwB,EACxB,6BAA6B,EAC7B,gCAAgC,EAChC,mBAAmB,EACnB,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,EACrB,oBAAoB,EACpB,sBAAsB,EACtB,WAAW,EACX,aAAa,EACb,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAC1B,KAAK,4BAA4B,EACjC,KAAK,+BAA+B,EACpC,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACN,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,wBAAwB,EACxB,6BAA6B,EAC7B,wBAAwB,EACxB,2BAA2B,EAC3B,kCAAkC,EAClC,UAAU,EACV,yBAAyB,EACzB,UAAU,EACV,aAAa,EACb,YAAY,EACZ,wBAAwB,EACxB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,MAAM,cAAc,CAAC;AAGtB,YAAY,EACX,eAAe,EACf,QAAQ,EACR,GAAG,EACH,YAAY,EACZ,SAAS,EACT,qBAAqB,EACrB,aAAa,EACb,iBAAiB,EACjB,WAAW,EACX,eAAe,EACf,WAAW,EACX,qBAAqB,EACrB,aAAa,EACb,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,MAAM,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -1,19 +1,21 @@
1
- var GJ=Object.defineProperty;var a=(J,Z)=>{for(var $ in Z)GJ(J,$,{get:Z[$],enumerable:!0,configurable:!0,set:(W)=>Z[$]=()=>W})};var d=(J,Z)=>()=>(J&&(Z=J(J=0)),Z);var G;var k=d(()=>{G=class G extends Error{code;constructor(J,Z){super(J);if(this.name="CollegeDBError",this.code=Z,Error.captureStackTrace)Error.captureStackTrace(this,G)}}});var n={};a(n,{KVShardMapper:()=>I});class I{kv;hashKeys;hashCache=new Map;constructor(J,Z={}){this.kv=J,this.hashKeys=Z.hashShardMappings??!0}async hashKey(J){if(!this.hashKeys)return J;let Z=this.hashCache.get(J);if(Z)return Z;let W=new TextEncoder().encode(J),Q=await crypto.subtle.digest("SHA-256",W),V=new Uint8Array(Q),O=Array.from(V).map((U)=>U.toString(16).padStart(2,"0")).join("");if(this.hashCache.size<1e4)this.hashCache.set(J,O);return O}async getShardMapping(J){let Z=await this.hashKey(J),$=`${R}${Z}`,W=await this.kv.get($,"json");if(W)return W;let Q=await this.kv.get(`${v}${Z}`,"json");if(Q)return{shard:Q.shard,createdAt:Q.createdAt,updatedAt:Q.updatedAt,originalKey:this.hashKeys?void 0:J};return null}async setShardMapping(J,Z,$=[]){let W=[J,...$],Q=Date.now();if(W.length===1){let V=await this.hashKey(J),O=`${R}${V}`,U={shard:Z,createdAt:Q,updatedAt:Q,originalKey:this.hashKeys?void 0:J};await this.kv.put(O,JSON.stringify(U))}else{let V=await this.hashKey(J),O=`${v}${V}`,U=this.hashKeys?await Promise.all(W.map((j)=>this.hashKey(j))):W,Y={shard:Z,createdAt:Q,updatedAt:Q,keys:U};await this.kv.put(O,JSON.stringify(Y));let H=W.map(async(j)=>{let X=await this.hashKey(j),x=`${R}${X}`,T={shard:Z,createdAt:Q,updatedAt:Q,originalKey:this.hashKeys?void 0:j};return this.kv.put(x,JSON.stringify(T))});await Promise.all(H)}}async updateShardMapping(J,Z){let $=await this.getShardMapping(J);if(!$)throw new G(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");let W=await this.hashKey(J),Q=`${R}${W}`,V=`${v}${W}`,O=await this.kv.get(V,"json");if(O){let U=Date.now(),Y={...O,shard:Z,updatedAt:U};await this.kv.put(V,JSON.stringify(Y));let j=(O.keys.length>0?this.hashKeys?O.keys:O.keys:[await this.hashKey(J)]).map(async(X)=>{let x=`${R}${X}`,T={...$,shard:Z,updatedAt:U};return this.kv.put(x,JSON.stringify(T))});await Promise.all(j)}else{let U={...$,shard:Z,updatedAt:Date.now()};await this.kv.put(Q,JSON.stringify(U))}}async deleteShardMapping(J){let Z=await this.hashKey(J),$=`${R}${Z}`,W=`${v}${Z}`,Q=await this.kv.get(W,"json");if(Q){await this.kv.delete(W);let O=(Q.keys.length>0?this.hashKeys?Q.keys:Q.keys:[await this.hashKey(J)]).map(async(U)=>{let Y=`${R}${U}`;return this.kv.delete(Y)});await Promise.all(O)}else await this.kv.delete($)}async getKnownShards(){return await this.kv.get(e,"json")||[]}async setKnownShards(J){if(!J||J.length===0)return;await this.kv.put(e,JSON.stringify(J))}async addKnownShard(J){if(!J)return;let Z=await this.getKnownShards();if(!Z.includes(J))Z.push(J),await this.setKnownShards(Z)}async getKeysForShard(J){let Z=[],$=await this.kv.list({prefix:R});for(let Q of $.keys){let V=await this.kv.get(Q.name,"json");if(V?.shard===J){let O=Q.name.replace(R,"");if(V.originalKey)Z.push(V.originalKey);else if(!this.hashKeys)Z.push(O)}}let W=await this.kv.list({prefix:v});for(let Q of W.keys){let V=await this.kv.get(Q.name,"json");if(V?.shard===J)Z.push(...V.keys)}return[...new Set(Z)]}async getShardKeyCounts(){let J={},Z=await this.kv.list({prefix:R});for(let W of Z.keys){let Q=await this.kv.get(W.name,"json");if(Q)J[Q.shard]=(J[Q.shard]||0)+1}let $=await this.kv.list({prefix:v});for(let W of $.keys){let Q=await this.kv.get(W.name,"json");if(Q)J[Q.shard]=(J[Q.shard]||0)+Q.keys.length}return J}async clearAllMappings(){let Z=(await this.kv.list({prefix:R})).keys.map((Q)=>this.kv.delete(Q.name)),W=(await this.kv.list({prefix:v})).keys.map((Q)=>this.kv.delete(Q.name));await Promise.all([...Z,...W])}async addLookupKeys(J,Z){let $=await this.getShardMapping(J);if(!$)throw new G(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");let W=await this.hashKey(J),Q=`${v}${W}`,V=await this.kv.get(Q,"json"),O=[J,...Z],U=Date.now();if(!V){let H=this.hashKeys?await Promise.all(O.map((j)=>this.hashKey(j))):O;V={shard:$.shard,createdAt:$.createdAt,updatedAt:U,keys:H}}else{let H=this.hashKeys?await Promise.all(O.map((j)=>this.hashKey(j))):O;V={...V,updatedAt:U,keys:[...new Set([...V.keys,...H])]}}await this.kv.put(Q,JSON.stringify(V));let Y=Z.map(async(H)=>{let j=await this.hashKey(H),X=`${R}${j}`,x={shard:$.shard,createdAt:$.createdAt,updatedAt:U,originalKey:this.hashKeys?void 0:H};return this.kv.put(X,JSON.stringify(x))});await Promise.all(Y)}async getAllLookupKeys(J){let Z=await this.hashKey(J),$=`${v}${Z}`,W=await this.kv.get($,"json");if(W)return W.keys;let Q=await this.getShardMapping(J);if(Q)return Q.originalKey?[Q.originalKey]:[J];throw new G(`No mapping found for key: ${J}`,"MAPPING_NOT_FOUND")}}var R="shard:",v="multikey:",e="known_shards";var S=d(()=>{k()});var m={};a(m,{validateTableForSharding:()=>p,schemaExists:()=>i,migrateRecord:()=>$J,listTables:()=>N,integrateExistingDatabase:()=>WJ,dropSchema:()=>ZJ,discoverExistingRecordsWithColumns:()=>g,discoverExistingPrimaryKeys:()=>h,createSchemaAcrossShards:()=>JJ,createSchema:()=>t,createMappingsForExistingKeys:()=>QJ,clearShardMigrationCache:()=>YJ,clearMigrationCache:()=>UJ,checkMigrationNeeded:()=>OJ,autoDetectAndMigrate:()=>VJ});async function t(J,Z){let $=Z.split(";").map((W)=>W.trim()).filter((W)=>W.length>0&&!W.startsWith("--"));for(let W of $)try{await J.prepare(W).run()}catch(Q){throw console.error("Failed to execute schema statement:",W,Q),new G(`Schema migration failed: ${Q}`,"SCHEMA_MIGRATION_FAILED")}}async function JJ(J,Z){let $=Object.entries(J).map(([W,Q])=>{return t(Q,Z).catch((V)=>{throw new G(`Failed to create schema on shard ${W}: ${V.message}`,"SCHEMA_CREATION_FAILED")})});await Promise.all($)}async function i(J,Z){try{return await J.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(Z).first()!==null}catch{return!1}}async function ZJ(J,...Z){for(let $ of Z)try{await J.prepare(`DROP TABLE IF EXISTS ${$}`).run()}catch(W){console.error(`Failed to drop table ${$}:`,W)}}async function N(J){try{return(await J.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all()).results.map(($)=>$.name)}catch{return[]}}async function $J(J,Z,$,W){let Q=await J.prepare(`SELECT * FROM ${W} WHERE id = ?`).bind($).first();if(!Q)throw new G(`Record with primary key ${$} not found in source database`,"RECORD_NOT_FOUND");if(!await i(Z,W))await t(Z,W);let V=Object.keys(Q),O=V.map(()=>"?").join(", "),U=V.map((H)=>Q[H]),Y=`INSERT OR REPLACE INTO ${W} (${V.join(", ")}) VALUES (${O})`;await Z.prepare(Y).bind(...U).run(),await J.prepare(`DELETE FROM ${W} WHERE id = ?`).bind($).run()}async function h(J,Z,$="id"){try{return(await J.prepare(`SELECT ${$} FROM ${Z}`).all()).results.map((Q)=>String(Q[$]))}catch(W){throw new G(`Failed to discover primary keys in table ${Z}: ${W}`,"DISCOVERY_FAILED")}}async function g(J,Z,$="id"){try{let W=`${Z}_columns`,Q;if(o.has(W))Q=o.get(W).map((Y)=>Y.name);else{let H=(await J.prepare(`PRAGMA table_info(${Z})`).all()).results.map((j)=>({name:j.name,type:j.type}));o.set(W,H),Q=H.map((j)=>j.name)}let V=[$];if(Q.includes("username"))V.push("username");if(Q.includes("email"))V.push("email");if(Q.includes("name"))V.push("name");let O=`SELECT ${V.join(", ")} FROM ${Z}`;return(await J.prepare(O).all()).results}catch(W){throw new G(`Failed to discover records with columns in table ${Z}: ${W}`,"DISCOVERY_FAILED")}}async function QJ(J,Z,$,W){let Q=Z.length;for(let V=0;V<J.length;V++){let O=J[V],U;switch($){case"hash":let Y=0;for(let j=0;j<O.length;j++){let X=O.charCodeAt(j);Y=(Y<<5)-Y+X,Y=Y&Y}let H=Math.abs(Y)%Q;U=Z[H];break;case"random":U=Z[Math.floor(Math.random()*Q)];break;default:U=Z[V%Q];break}await W.setShardMapping(O,U)}}async function p(J,Z,$){let W=[],Q=0;try{if(!await J.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(Z).first())return W.push(`Table '${Z}' does not exist`),{isValid:!1,tableName:Z,primaryKeyColumn:$,recordCount:0,issues:W};if(!(await J.prepare(`PRAGMA table_info(${Z})`).all()).results.some((H)=>H.name===$&&H.pk===1))W.push(`Primary key column '${$}' not found or not set as primary key`);if(Q=(await J.prepare(`SELECT COUNT(*) as count FROM ${Z}`).first())?.count||0,Q===0)W.push(`Table '${Z}' is empty`)}catch(V){W.push(`Database validation error: ${V}`)}return{isValid:W.length===0,tableName:Z,primaryKeyColumn:$,recordCount:Q,issues:W}}async function WJ(J,Z,$,W={}){let{tables:Q,primaryKeyColumn:V="id",strategy:O="hash",addShardMappingsTable:U=!0,dryRun:Y=!1,migrateOtherColumns:H=!1}=W,j=[],X=0,x=0,T=0;try{let _=(Q||await N(J)).filter((w)=>w!=="shard_mappings");for(let w of _)try{let F=await p(J,w,V);if(!F.isValid){j.push(`Table ${w}: ${F.issues.join(", ")}`);continue}if(H){let z=await g(J,w,V);if(z.length===0){j.push(`Table ${w} has no records to process`);continue}if(!Y)for(let L of z){let D=String(L[V]),B=[];if(L.username&&typeof L.username==="string")B.push(`username:${L.username}`);if(L.email&&typeof L.email==="string")B.push(`email:${L.email}`);if(L.name&&typeof L.name==="string")B.push(`name:${L.name}`);await $.setShardMapping(D,Z,B),T++}x+=z.length}else{let z=await h(J,w,V);if(z.length===0){j.push(`Table ${w} has no records to process`);continue}if(!Y)for(let L of z)await $.setShardMapping(L,Z),T++;x+=z.length}X++}catch(F){j.push(`Failed to process table ${w}: ${F}`)}if(U&&!Y){if(!(await N(J)).includes("shard_mappings"))await J.prepare(`
1
+ var pJ=Object.defineProperty;var mJ=(J)=>J;function gJ(J,X){this[J]=mJ.bind(null,X)}var jJ=(J,X)=>{for(var Y in X)pJ(J,Y,{get:X[Y],enumerable:!0,configurable:!0,set:gJ.bind(X,Y)})};var JJ=(J,X)=>()=>(J&&(X=J(J=0)),X);var _;var q=JJ(()=>{_=class _ extends Error{code;constructor(J,X){super(J);if(this.name="CollegeDBError",this.code=X,Error.captureStackTrace)Error.captureStackTrace(this,_)}}});var XJ={};jJ(XJ,{KVShardMapper:()=>k});class k{kv;hashKeys;hashCache=new Map;mappingCache=new Map;knownShardsCache={shards:null,expiresAt:0};mappingCacheTtlMs;knownShardsCacheTtlMs;constructor(J,X={}){this.kv=J,this.hashKeys=X.hashShardMappings??!0,this.mappingCacheTtlMs=X.mappingCacheTtlMs??yJ,this.knownShardsCacheTtlMs=X.knownShardsCacheTtlMs??cJ}getCachedMapping(J){let X=this.mappingCache.get(J);if(!X)return;if(X.expiresAt<Date.now()){this.mappingCache.delete(J);return}return X.mapping}setCachedMapping(J,X){if(this.mappingCache.size>50000){let Y=this.mappingCache.keys().next().value;if(Y)this.mappingCache.delete(Y)}this.mappingCache.set(J,{mapping:X,expiresAt:Date.now()+this.mappingCacheTtlMs})}async cacheMappingForKeys(J,X){let Y=await Promise.all(J.map((Z)=>this.hashKey(Z)));for(let Z of Y)this.setCachedMapping(Z,X)}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 X=this.hashCache.get(J);if(X)return X;let Z=new TextEncoder().encode(J),G=await crypto.subtle.digest("SHA-256",Z),$=new Uint8Array(G),W=Array.from($).map((H)=>H.toString(16).padStart(2,"0")).join("");if(this.hashCache.size<1e4)this.hashCache.set(J,W);return W}async getShardMapping(J){let X=await this.hashKey(J),Y=this.getCachedMapping(X);if(Y!==void 0)return Y;let Z=`${x}${X}`,G=await this.kv.get(Z,"json");if(G)return this.setCachedMapping(X,G),G;let $=await this.kv.get(`${N}${X}`,"json");if($){let W={shard:$.shard,createdAt:$.createdAt,updatedAt:$.updatedAt,originalKey:this.hashKeys?void 0:J};if(this.setCachedMapping(X,W),this.hashKeys)for(let H of $.keys)this.setCachedMapping(H,W);return W}return this.setCachedMapping(X,null),null}async setShardMapping(J,X,Y=[]){let Z=[J,...Y],G=Date.now(),$={shard:X,createdAt:G,updatedAt:G,originalKey:this.hashKeys?void 0:J};if(Z.length===1){let W=await this.hashKey(J),H=`${x}${W}`;await this.kv.put(H,JSON.stringify($)),this.setCachedMapping(W,$)}else{let W=await this.hashKey(J),H=`${N}${W}`,V=this.hashKeys?await Promise.all(Z.map((F)=>this.hashKey(F))):Z,U={shard:X,createdAt:G,updatedAt:G,keys:V};await this.kv.put(H,JSON.stringify(U));let O=Z.map(async(F)=>{let L=await this.hashKey(F),j=`${x}${L}`,E={shard:X,createdAt:G,updatedAt:G,originalKey:this.hashKeys?void 0:F};return this.kv.put(j,JSON.stringify(E))});await Promise.all(O),await this.cacheMappingForKeys(Z,$)}}async updateShardMapping(J,X){let Y=await this.getShardMapping(J);if(!Y)throw new _(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");let Z=await this.hashKey(J),G=`${x}${Z}`,$=`${N}${Z}`,W=await this.kv.get($,"json");if(W){let H=Date.now(),V={...W,shard:X,updatedAt:H};await this.kv.put($,JSON.stringify(V));let U=W.keys.length>0?this.hashKeys?W.keys:W.keys:[await this.hashKey(J)],O=U.map(async(L)=>{let j=`${x}${L}`,E={...Y,shard:X,updatedAt:H};return this.kv.put(j,JSON.stringify(E))});await Promise.all(O);let F={...Y,shard:X,updatedAt:H};if(this.hashKeys)for(let L of U)this.setCachedMapping(L,F);this.setCachedMapping(Z,F)}else{let H={...Y,shard:X,updatedAt:Date.now()};await this.kv.put(G,JSON.stringify(H)),this.setCachedMapping(Z,H)}}async deleteShardMapping(J){let X=await this.hashKey(J),Y=`${x}${X}`,Z=`${N}${X}`,G=await this.kv.get(Z,"json");if(G){await this.kv.delete(Z);let $=G.keys.length>0?this.hashKeys?G.keys:G.keys:[await this.hashKey(J)],W=$.map(async(H)=>{let V=`${x}${H}`;return this.kv.delete(V)});if(await Promise.all(W),this.hashKeys)for(let H of $)this.setCachedMapping(H,null);this.setCachedMapping(X,null)}else await this.kv.delete(Y),this.setCachedMapping(X,null)}async getKnownShards(){let J=this.getCachedKnownShards();if(J)return J;let Y=await this.kv.get(QJ,"json")||[];return this.setCachedKnownShards(Y),Y}async setKnownShards(J){if(!J||J.length===0)return;let X=[...new Set(J.filter(Boolean))];if(X.length===0)return;await this.kv.put(QJ,JSON.stringify(X)),this.setCachedKnownShards(X)}async addKnownShard(J){if(!J)return;let X=await this.getKnownShards();if(!X.includes(J))X.push(J),await this.setKnownShards(X)}async getKeysForShard(J){let X=[],Y=await this.kv.list({prefix:x});for(let G of Y.keys){let $=await this.kv.get(G.name,"json");if($?.shard===J){let W=G.name.replace(x,"");if($.originalKey)X.push($.originalKey);else if(!this.hashKeys)X.push(W)}}let Z=await this.kv.list({prefix:N});for(let G of Z.keys){let $=await this.kv.get(G.name,"json");if($?.shard===J)X.push(...$.keys)}return[...new Set(X)]}async getShardKeyCounts(){let J={},X=await this.kv.list({prefix:x});for(let Z of X.keys){let G=await this.kv.get(Z.name,"json");if(G)J[G.shard]=(J[G.shard]||0)+1}let Y=await this.kv.list({prefix:N});for(let Z of Y.keys){let G=await this.kv.get(Z.name,"json");if(G)J[G.shard]=(J[G.shard]||0)+G.keys.length}return J}async clearAllMappings(){let X=(await this.kv.list({prefix:x})).keys.map((G)=>this.kv.delete(G.name)),Z=(await this.kv.list({prefix:N})).keys.map((G)=>this.kv.delete(G.name));await Promise.all([...X,...Z]),this.mappingCache.clear()}async addLookupKeys(J,X){let Y=await this.getShardMapping(J);if(!Y)throw new _(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");let Z=await this.hashKey(J),G=`${N}${Z}`,$=await this.kv.get(G,"json"),W=[J,...X],H=Date.now();if(!$){let O=this.hashKeys?await Promise.all(W.map((F)=>this.hashKey(F))):W;$={shard:Y.shard,createdAt:Y.createdAt,updatedAt:H,keys:O}}else{let O=this.hashKeys?await Promise.all(W.map((F)=>this.hashKey(F))):W;$={...$,updatedAt:H,keys:[...new Set([...$.keys,...O])]}}await this.kv.put(G,JSON.stringify($));let V=X.map(async(O)=>{let F=await this.hashKey(O),L=`${x}${F}`,j={shard:Y.shard,createdAt:Y.createdAt,updatedAt:H,originalKey:this.hashKeys?void 0:O};return this.kv.put(L,JSON.stringify(j))});await Promise.all(V);let U={shard:Y.shard,createdAt:Y.createdAt,updatedAt:H,originalKey:Y.originalKey};await this.cacheMappingForKeys([J,...X],U)}async setShardMappingsBatch(J,X={}){if(J.length===0)return;let Y=Math.max(1,X.concurrency??25),Z=0,G=Array(Math.min(Y,J.length)).fill(null).map(async()=>{while(Z<J.length){let $=Z++,W=J[$];if(!W)continue;await this.setShardMapping(W.primaryKey,W.shard,W.additionalKeys||[])}});await Promise.all(G)}async getAllLookupKeys(J){let X=await this.hashKey(J),Y=`${N}${X}`,Z=await this.kv.get(Y,"json");if(Z)return Z.keys;let G=await this.getShardMapping(J);if(G)return G.originalKey?[G.originalKey]:[J];throw new _(`No mapping found for key: ${J}`,"MAPPING_NOT_FOUND")}}var x="shard:",N="multikey:",QJ="known_shards",yJ=30000,cJ=1e4;var p=JJ(()=>{q()});var i={};jJ(i,{validateTableForSharding:()=>n,schemaExists:()=>GJ,migrateRecord:()=>RJ,listTables:()=>b,integrateExistingDatabase:()=>DJ,dropSchema:()=>TJ,discoverExistingRecordsWithColumns:()=>l,discoverExistingPrimaryKeys:()=>o,createSchemaAcrossShards:()=>EJ,createSchema:()=>ZJ,createMappingsForExistingKeys:()=>zJ,clearShardMigrationCache:()=>vJ,clearMigrationCache:()=>xJ,checkMigrationNeeded:()=>BJ,autoDetectAndMigrate:()=>wJ});async function PJ(J,X,Y){if(J.length===0)return;let Z=Math.max(1,Math.min(X,J.length)),G=0,$=Array(Z).fill(null).map(async()=>{while(G<J.length){let W=G++,H=J[W];if(H===void 0)continue;await Y(H,W)}});await Promise.all($)}function dJ(J,X,Y,Z){let G=Y.length;switch(Z){case"hash":{let $=0;for(let H=0;H<J.length;H++){let V=J.charCodeAt(H);$=($<<5)-$+V,$=$&$}let W=Math.abs($)%G;return Y[W]}case"random":return Y[Math.floor(Math.random()*G)];default:return Y[X%G]}}async function ZJ(J,X){let Y=X.split(";").map((Z)=>Z.trim()).filter((Z)=>Z.length>0&&!Z.startsWith("--"));for(let Z of Y)try{await J.prepare(Z).run()}catch(G){throw console.error("Failed to execute schema statement:",Z,G),new _(`Schema migration failed: ${G}`,"SCHEMA_MIGRATION_FAILED")}}async function EJ(J,X){let Y=Object.entries(J).map(([Z,G])=>{return ZJ(G,X).catch(($)=>{throw new _(`Failed to create schema on shard ${Z}: ${$.message}`,"SCHEMA_CREATION_FAILED")})});await Promise.all(Y)}async function GJ(J,X){try{return await J.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(X).first()!==null}catch{return!1}}async function TJ(J,...X){for(let Y of X)try{await J.prepare(`DROP TABLE IF EXISTS ${Y}`).run()}catch(Z){console.error(`Failed to drop table ${Y}:`,Z)}}async function b(J){try{return(await J.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all()).results.map((Y)=>Y.name)}catch{return[]}}async function RJ(J,X,Y,Z){let G=await J.prepare(`SELECT * FROM ${Z} WHERE id = ?`).bind(Y).first();if(!G)throw new _(`Record with primary key ${Y} not found in source database`,"RECORD_NOT_FOUND");if(!await GJ(X,Z))await ZJ(X,Z);let $=Object.keys(G),W=$.map(()=>"?").join(", "),H=$.map((U)=>G[U]),V=`INSERT OR REPLACE INTO ${Z} (${$.join(", ")}) VALUES (${W})`;await X.prepare(V).bind(...H).run(),await J.prepare(`DELETE FROM ${Z} WHERE id = ?`).bind(Y).run()}async function o(J,X,Y="id"){try{return(await J.prepare(`SELECT ${Y} FROM ${X}`).all()).results.map((G)=>String(G[Y]))}catch(Z){throw new _(`Failed to discover primary keys in table ${X}: ${Z}`,"DISCOVERY_FAILED")}}async function l(J,X,Y="id"){try{let Z=`${X}_columns`,G;if(YJ.has(Z))G=YJ.get(Z).map((V)=>V.name);else{let U=(await J.prepare(`PRAGMA table_info(${X})`).all()).results.map((O)=>({name:O.name,type:O.type}));YJ.set(Z,U),G=U.map((O)=>O.name)}let $=[Y];if(G.includes("username"))$.push("username");if(G.includes("email"))$.push("email");if(G.includes("name"))$.push("name");let W=`SELECT ${$.join(", ")} FROM ${X}`;return(await J.prepare(W).all()).results}catch(Z){throw new _(`Failed to discover records with columns in table ${X}: ${Z}`,"DISCOVERY_FAILED")}}async function zJ(J,X,Y,Z,G={}){if(J.length===0||X.length===0)return;let $=Math.max(1,G.concurrency??25),W=J.map((H,V)=>({primaryKey:H,shard:dJ(H,V,X,Y)}));await Z.setShardMappingsBatch(W,{concurrency:$})}async function n(J,X,Y){let Z=[],G=0;try{if(!await J.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").bind(X).first())return Z.push(`Table '${X}' does not exist`),{isValid:!1,tableName:X,primaryKeyColumn:Y,recordCount:0,issues:Z};if(!(await J.prepare(`PRAGMA table_info(${X})`).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(G=(await J.prepare(`SELECT COUNT(*) as count FROM ${X}`).first())?.count||0,G===0)Z.push(`Table '${X}' is empty`)}catch($){Z.push(`Database validation error: ${$}`)}return{isValid:Z.length===0,tableName:X,primaryKeyColumn:Y,recordCount:G,issues:Z}}async function DJ(J,X,Y,Z={}){let{tables:G,primaryKeyColumn:$="id",strategy:W="hash",addShardMappingsTable:H=!0,dryRun:V=!1,migrateOtherColumns:U=!1,concurrency:O=25}=Z,F=Math.max(1,O),L=[],j=0,E=0,z=0;try{let A=(G||await b(J)).filter((I)=>I!=="shard_mappings");for(let I of A)try{let R=await n(J,I,$);if(!R.isValid){L.push(`Table ${I}: ${R.issues.join(", ")}`);continue}if(U){let T=await l(J,I,$);if(T.length===0){L.push(`Table ${I} has no records to process`);continue}if(!V){let P=T.map((Q)=>{let r=String(Q[$]),K=[];if(Q.username&&typeof Q.username==="string")K.push(`username:${Q.username}`);if(Q.email&&typeof Q.email==="string")K.push(`email:${Q.email}`);if(Q.name&&typeof Q.name==="string")K.push(`name:${Q.name}`);return{primaryKey:r,shard:X,additionalKeys:K}});await Y.setShardMappingsBatch(P,{concurrency:F}),z+=P.length}E+=T.length}else{let T=await o(J,I,$);if(T.length===0){L.push(`Table ${I} has no records to process`);continue}if(!V){let P=T.map((Q)=>({primaryKey:Q,shard:X}));await Y.setShardMappingsBatch(P,{concurrency:F}),z+=P.length}E+=T.length}j++}catch(R){L.push(`Failed to process table ${I}: ${R}`)}if(H&&!V){if(!(await b(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(!Y)await $.addKnownShard(Z)}catch(A){j.push(`Integration failed: ${A}`)}return{success:j.length===0||j.length>0&&X>0,shardName:Z,tablesProcessed:X,totalRecords:x,mappingsCreated:T,issues:j}}async function VJ(J,Z,$,W={}){let{primaryKeyColumn:Q="id",tablesToCheck:V,skipCache:O=!1,maxRecordsToCheck:U=1000,migrateOtherColumns:Y=!1}=W,H=`${Z}_migration_check`;if(!O&&M.has(H))return{migrationNeeded:!1,migrationPerformed:!1,recordsMigrated:0,tablesProcessed:0,issues:[]};let j=[],X=0,x=0,T=!1,A=!1;try{let{KVShardMapper:_}=await Promise.resolve().then(() => (S(),n)),w=new _($.kv,{hashShardMappings:$.hashShardMappings}),F=await N(J),z=V||F.filter((L)=>L!=="shard_mappings"&&!L.startsWith("sqlite_")&&L!=="sqlite_sequence");if(z.length===0)return M.set(H,!0),{migrationNeeded:!1,migrationPerformed:!1,recordsMigrated:0,tablesProcessed:0,issues:[]};for(let L of z)try{let D=await p(J,L,Q);if(!D.isValid||D.recordCount===0)continue;let B=Math.min(U,D.recordCount),K=await J.prepare(`
8
- SELECT ${Q} FROM ${L}
9
- ORDER BY ${Q}
10
- LIMIT ?`.trim()).bind(B).all(),r=0,LJ=K.results.slice(0,10).map(async(C)=>{let P=String(C[Q]);return{key:P,mapping:await w.getShardMapping(P)}}),XJ=await Promise.all(LJ);for(let C of XJ)if(!C.mapping)r++,T=!0;if(r>0){if($.debug)console.log(`Auto-migrating table ${L} in shard ${Z} (${D.recordCount} records)`);if(Y){let C=await g(J,L,Q),P=0;for(let q of C){let l=String(q[Q]);if(!await w.getShardMapping(l)){let c=[];if(q.username&&typeof q.username==="string")c.push(`username:${q.username}`);if(q.email&&typeof q.email==="string")c.push(`email:${q.email}`);if(q.name&&typeof q.name==="string")c.push(`name:${q.name}`);await w.setShardMapping(l,Z,c),P++}}X+=P}else{let C=await h(J,L,Q),P=0;for(let q of C)if(!await w.getShardMapping(q))await w.setShardMapping(q,Z),P++;X+=P}if(x++,A=!0,$.debug)console.log(`Auto-migrated ${X} records from table ${L}`)}}catch(D){j.push(`Auto-migration failed for table ${L}: ${D}`)}if(A){if(await w.addKnownShard(Z),!F.includes("shard_mappings"))await J.prepare(`CREATE TABLE IF NOT EXISTS shard_mappings (
7
+ );`.trim()).run()}if(!V)await Y.addKnownShard(X)}catch(M){L.push(`Integration failed: ${M}`)}return{success:L.length===0||L.length>0&&j>0,shardName:X,tablesProcessed:j,totalRecords:E,mappingsCreated:z,issues:L}}async function wJ(J,X,Y,Z={}){let{primaryKeyColumn:G="id",tablesToCheck:$,skipCache:W=!1,maxRecordsToCheck:H=1000,migrateOtherColumns:V=!1,concurrency:U=Y.migrationConcurrency??25}=Z,O=Math.max(1,U),F=`${X}_migration_check`;if(!W&&S.has(F))return{migrationNeeded:!1,migrationPerformed:!1,recordsMigrated:0,tablesProcessed:0,issues:[]};let L=[],j=0,E=0,z=!1,M=!1;try{let{KVShardMapper:A}=await Promise.resolve().then(() => (p(),XJ)),I=new A(Y.kv,{hashShardMappings:Y.hashShardMappings,mappingCacheTtlMs:Y.mappingCacheTtlMs,knownShardsCacheTtlMs:Y.knownShardsCacheTtlMs}),R=await b(J),T=$||R.filter((P)=>P!=="shard_mappings"&&!P.startsWith("sqlite_")&&P!=="sqlite_sequence");if(T.length===0)return S.set(F,!0),{migrationNeeded:!1,migrationPerformed:!1,recordsMigrated:0,tablesProcessed:0,issues:[]};for(let P of T)try{let Q=await n(J,P,G);if(!Q.isValid||Q.recordCount===0)continue;let r=Math.min(H,Q.recordCount),K=await J.prepare(`
8
+ SELECT ${G} FROM ${P}
9
+ ORDER BY ${G}
10
+ LIMIT ?`.trim()).bind(r).all(),IJ=0,hJ=K.results.slice(0,10).map(async(C)=>{let B=String(C[G]);return{key:B,mapping:await I.getShardMapping(B)}}),uJ=await Promise.all(hJ);for(let C of uJ)if(!C.mapping)IJ++,z=!0;if(IJ>0){if(Y.debug)console.log(`Auto-migrating table ${P} in shard ${X} (${Q.recordCount} records)`);if(V){let C=await l(J,P,G),B=[];if(await PJ(C,O,async(D)=>{let e=String(D[G]);if(await I.getShardMapping(e))return;let d=[];if(D.username&&typeof D.username==="string")d.push(`username:${D.username}`);if(D.email&&typeof D.email==="string")d.push(`email:${D.email}`);if(D.name&&typeof D.name==="string")d.push(`name:${D.name}`);B.push({primaryKey:e,shard:X,additionalKeys:d})}),B.length>0)await I.setShardMappingsBatch(B,{concurrency:O});j+=B.length}else{let C=await o(J,P,G),B=[];if(await PJ(C,O,async(D)=>{if(!await I.getShardMapping(D))B.push({primaryKey:D,shard:X})}),B.length>0)await I.setShardMappingsBatch(B,{concurrency:O});j+=B.length}if(E++,M=!0,Y.debug)console.log(`Auto-migrated ${j} records from table ${P}`)}}catch(Q){L.push(`Auto-migration failed for table ${P}: ${Q}`)}if(M){if(await I.addKnownShard(X),!R.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(M.set(H,!0),A&&$.debug)console.log(`Auto-migration completed for shard ${Z}: ${X} records from ${x} tables`)}catch(_){j.push(`Auto-migration error: ${_}`)}return{migrationNeeded:T,migrationPerformed:A,recordsMigrated:X,tablesProcessed:x,issues:j}}async function OJ(J,Z,$){let W=`${Z}_migration_check`;if(M.has(W))return!1;try{let Q=await N(J);if(Q.includes("shard_mappings"))return M.set(W,!0),!1;let{KVShardMapper:O}=await Promise.resolve().then(() => (S(),n)),U=new O($.kv,{hashShardMappings:$.hashShardMappings}),Y=Q.filter((H)=>H!=="shard_mappings"&&!H.startsWith("sqlite_")&&H!=="sqlite_sequence");for(let H of Y.slice(0,3))try{if(((await J.prepare(`SELECT COUNT(*) as count FROM ${H} LIMIT 1`).first())?.count||0)>0){let x=await J.prepare(`SELECT id FROM ${H} LIMIT 1`).first();if(x){let T=String(x.id);if(!await U.getShardMapping(T))return!0}}}catch{continue}return!1}catch{return!1}}function UJ(){M.clear()}function YJ(J){let Z=`${J}_migration_check`;M.delete(Z)}var M,o;var f=d(()=>{k();M=new Map,o=new Map});k();S();var b=null;function xJ(J){b=J;try{let Z=new I(J.kv,{hashShardMappings:J.hashShardMappings});Promise.all(Object.keys(J.shards).map(($)=>Z.addKnownShard($))).catch(()=>{return})}catch{}if(J.shards&&Object.keys(J.shards).length>0&&!J.disableAutoMigration)HJ(J).catch((Z)=>{console.warn("Background auto-migration failed:",Z)})}async function jJ(J){b=J;try{let Z=new I(J.kv,{hashShardMappings:J.hashShardMappings});await Promise.all(Object.keys(J.shards).map(($)=>Z.addKnownShard($)))}catch{}if(J.shards&&Object.keys(J.shards).length>0&&!J.disableAutoMigration)try{await HJ(J)}catch(Z){console.warn("Auto migration failed:",Z)}}async function zJ(J,Z){return await jJ(J),await Z()}async function HJ(J){try{let{autoDetectAndMigrate:Z}=await Promise.resolve().then(() => (f(),m)),$=Object.keys(J.shards);if(J.debug)console.log(`\uD83D\uDD0D Checking ${$.length} shards for existing data...`);let W=$.map(async(O)=>{let U=J.shards[O];if(!U)return null;try{let Y=await Z(U,O,J,{maxRecordsToCheck:1000});return{shardName:O,...Y}}catch(Y){return console.warn(`Auto-migration failed for shard ${O}:`,Y),null}}),V=(await Promise.all(W)).filter((O)=>O?.migrationPerformed);if(J.debug)if(V.length>0){let O=V.reduce((U,Y)=>U+(Y?.recordsMigrated||0),0);console.log(`\uD83C\uDF89 Auto-migration completed! Migrated ${O} records across ${V.length} shards`),V.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(Z){console.warn("Background auto-migration setup failed:",Z)}}function TJ(){b=null}function E(){if(!b)throw new G("CollegeDB not initialized. Call initialize() first.","NOT_INITIALIZED");return b}function wJ(J){let Z=J.trim().toUpperCase();if(Z.startsWith("SELECT")||Z.startsWith("VALUES")||Z.startsWith("TABLE")||Z.startsWith("PRAGMA")||Z.startsWith("EXPLAIN")||Z.startsWith("WITH")||Z.startsWith("SHOW"))return"read";return"write"}function AJ(J,Z){let $=J.strategy||"hash";if(typeof $==="string")return $;let W=$;return W[Z]||W.write||W.read||"hash"}function DJ(J,Z){if(J===Z)return 0;let $={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}},W=$[J],Q=$[Z],V=W.lat-Q.lat,O=W.lon-Q.lon;return Math.sqrt(V*V+O*O)}function _J(J){let Z=J.cf;if(!Z||!Z.country)return"wnam";let{country:$,continent:W}=Z;if(["US","CA","MX"].includes($)){let Q=Z.region||Z.regionCode||"",V=Z.timezone||"";if(Q.includes("CA")||Q.includes("WA")||Q.includes("OR")||Q.includes("NV")||Q.includes("AZ")||Q.includes("UT")||V.includes("Pacific")||V.includes("America/Los_Angeles"))return"wnam";return"enam"}if(["GL","PM","BM"].includes($))return"enam";if(["GB","IE","FR","ES","PT","NL","BE","LU","CH","AT","IT"].includes($))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($))return"eeur";if($==="RU")return"eeur";if(["JP","KR","CN","HK","TW","MO","MN","KP"].includes($))return"apac";if(["TH","VN","SG","MY","ID","PH","BN","KH","LA","MM","TL","IN","PK","BD","LK","NP","BT","MV","AF"].includes($))return"apac";if(["AU","NZ","PG","FJ","NC","VU","SB","WS","TO","KI","NR","PW","FM","MH","TV"].includes($))return"oc";if(["AE","SA","QA","KW","BH","OM","YE","IQ","IR","SY","LB","JO","IL","PS","TR","CY"].includes($))return"me";if(W==="AF"||["EG","LY","TN","DZ","MA","SD","SS","ET","ER","DJ","SO"].includes($))return"af";if(["KZ","UZ","TM","TJ","KG"].includes($))return"eeur";if(W==="SA"||["BR","AR","CL","PE","CO","VE","EC","BO","PY","UY","GY","SR","GF"].includes($))return"enam";if(["GT","BZ","SV","HN","NI","CR","PA","CU","JM","HT","DO","PR","TT","BB","GD","VC","LC","DM","AG","KN"].includes($))return"enam";return"wnam"}function qJ(J){if(typeof J==="string")return J;return J.region||"wnam"}async function FJ(J){try{let[Z,$]=await Promise.all([J.prepare("PRAGMA page_count").first(),J.prepare("PRAGMA page_size").first()]);if(!Z?.page_count||!$?.page_size)throw new G("Failed to retrieve database size information","SIZE_QUERY_FAILED");return Z.page_count*$.page_size}catch(Z){throw new G(`Failed to get database size: ${Z instanceof Error?Z.message:"Unknown error"}`,"SIZE_QUERY_FAILED")}}async function EJ(J,Z){let $=Z.maxDatabaseSize||10683731148,Q=(await Promise.allSettled(J.map(async(V)=>{let O=Z.shards[V];if(!O)throw new G(`Shard ${V} not found in configuration`,"SHARD_NOT_FOUND");let U=await FJ(O);return{shard:V,size:U,withinLimit:U<$}}))).filter((V)=>V.status==="fulfilled"&&V.value.withinLimit).map((V)=>V.value.shard);if(Q.length===0){if(Z.debug)console.warn("All shards exceed maxDatabaseSize limit. Allowing allocation to prevent failure.");return J}if(Z.debug&&Q.length<J.length){let V=J.filter((O)=>!Q.includes(O));console.log(`Excluded ${V.length} shards due to size limits: ${V.join(", ")}`)}return Q}function RJ(J,Z,$,W){let Q=Z.filter((j)=>$[j]);if(Q.length===0){let j=0;for(let x=0;x<W.length;x++){let T=W.charCodeAt(x);j=(j<<5)-j+T,j=j&j}let X=Math.abs(j)%Z.length;return Z[X]}let V=Q.map((j)=>{let X=$[j],x=DJ(J,qJ(X)),T=typeof X==="object"?X.priority||1:1,A=x-T*0.1;return{shard:j,score:A,distance:x,priority:T}});V.sort((j,X)=>j.score-X.score);let O=V[0].score,U=V.filter((j)=>Math.abs(j.score-O)<0.01);if(U.length===1)return U[0].shard;let Y=0;for(let j=0;j<W.length;j++){let X=W.charCodeAt(j);Y=(Y<<5)-Y+X,Y=Y&Y}let H=Math.abs(Y)%U.length;return U[H].shard}function u(J,Z,$,W){switch(J){case"hash":{let Q=0;for(let O=0;O<Z.length;O++){let U=Z.charCodeAt(O);Q=(Q<<5)-Q+U,Q=Q&Q}let V=Math.abs(Q)%$.length;return $[V]||$[0]}case"location":{if(!W.targetRegion)return u("hash",Z,$,W);return RJ(W.targetRegion,$,W.shardLocations||{},Z)}case"random":return $[Math.floor(Math.random()*$.length)]||$[0];default:return u("hash",Z,$,W)}}async function IJ(J,Z="write"){let $=E(),W=new I($.kv,{hashShardMappings:$.hashShardMappings}),Q=await W.getShardMapping(J);if(Q)return Q.shard;let V=Object.keys($.shards);if(V.length===0)throw new G("No shards configured","NO_SHARDS");let O=await EJ(V,$),U,Y=AJ($,Z);if($.coordinator)try{let H=$.coordinator.idFromName("default"),X=await $.coordinator.get(H).fetch("http://coordinator/allocate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primaryKey:J,strategy:Y,operationType:Z,targetRegion:$.targetRegion,shardLocations:$.shardLocations,availableShards:O})});if(X.ok)U=(await X.json()).shard;else U=u(Y,J,O,$)}catch(H){console.warn("Coordinator allocation failed, falling back to local strategy:",H),U=u(Y,J,O,$)}else U=u(Y,J,O,$);return await W.setShardMapping(J,U),U}async function BJ(J,Z="write"){let $=E(),W=await IJ(J,Z),Q=$.shards[W];if(!Q)throw new G(`Shard ${W} not found in configuration`,"SHARD_NOT_FOUND");return Q}async function vJ(J,Z){let{createSchema:$}=await Promise.resolve().then(() => (f(),m));await $(J,Z)}async function y(J,Z){let $=wJ(Z);return(await BJ(J,$)).prepare(Z)}async function PJ(J,Z,$=[]){let Q=await(await y(J,Z)).bind(...$).run();if(!Q.success)throw new G(`Query failed: ${Q.error||"Unknown error"}`,"QUERY_FAILED");return Q}async function CJ(J,Z,$=[]){let Q=await(await y(J,Z)).bind(...$).all();if(!Q.success)throw new G(`Query failed: ${Q.error||"Unknown error"}`,"QUERY_FAILED");return Q}async function MJ(J,Z,$=[]){return await(await y(J,Z)).bind(...$).first()}async function kJ(J,Z,$){let W=E();if(!W.shards[Z])throw new G(`Shard ${Z} not found in configuration`,"SHARD_NOT_FOUND");let Q=new I(W.kv,{hashShardMappings:W.hashShardMappings}),V=await Q.getShardMapping(J);if(!V)throw new G(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");if(V.shard!==Z){let{migrateRecord:O}=await Promise.resolve().then(() => (f(),m)),U=W.shards[V.shard],Y=W.shards[Z];if(!U||!Y)throw new G("Source or target shard not available","SHARD_UNAVAILABLE");await O(U,Y,J,$)}await Q.updateShardMapping(J,Z)}async function NJ(){let J=E();if(J.coordinator)try{let Z=J.coordinator.idFromName("default"),W=await J.coordinator.get(Z).fetch("http://coordinator/shards");if(W.ok)return await W.json()}catch(Z){console.warn("Failed to get shards from coordinator:",Z)}try{let $=await new I(J.kv,{hashShardMappings:J.hashShardMappings}).getKnownShards(),W=new Set([...Object.keys(J.shards),...$]);return Array.from(W)}catch{return Object.keys(J.shards)}}async function SJ(){let J=E();if(J.coordinator)try{let Q=J.coordinator.idFromName("default"),O=await J.coordinator.get(Q).fetch("http://coordinator/stats");if(O.ok)return await O.json()}catch(Q){console.warn("Failed to get stats from coordinator:",Q)}let Z=new I(J.kv,{hashShardMappings:J.hashShardMappings}),$=await Z.getShardKeyCounts(),W=Object.keys(J.shards);try{let Q=await Z.getKnownShards();W=Array.from(new Set([...W,...Q]))}catch{}return W.map((Q)=>({binding:Q,count:$[Q]||0}))}async function fJ(J,Z,$=[]){let Q=E().shards[J];if(!Q)throw new G(`Shard ${J} not found`,"SHARD_NOT_FOUND");let V=await Q.prepare(Z).bind(...$).run();if(!V.success)throw new G(`Query failed: ${V.error||"Unknown error"}`,"QUERY_FAILED");return V}async function uJ(J,Z,$=[]){let Q=E().shards[J];if(!Q)throw new G(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await Q.prepare(Z).bind(...$).all()}async function bJ(J,Z,$=[]){let Q=E().shards[J];if(!Q)throw new G(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await Q.prepare(Z).bind(...$).first()}async function KJ(J,Z=[],$=50){let W=E(),Q=[];for(let[O,U]of Object.entries(W.shards)){if(!O||!U){console.error(`Shard ${O??"<null>"} not found, skipping`);continue}Q.push(()=>U.prepare(J).bind(...Z).run().catch((Y)=>{return console.error(`Error executing query on shard ${O}:`,Y),{success:!1,results:[],meta:{count:0,duration:0}}}))}let V=[];for(let O=0;O<Q.length;O+=$){let U=Q.slice(O,O+$).map((Y)=>Y());V.push(...await Promise.all(U))}return V}async function cJ(J,Z=[],$=50){let W=E(),Q=[];for(let[O,U]of Object.entries(W.shards)){if(!O||!U){console.error(`Shard ${O??"<null>"} not found, skipping`);continue}Q.push(()=>U.prepare(J).bind(...Z).all().catch((Y)=>{return console.error(`Error executing query on shard ${O}:`,Y),{success:!1,results:[],meta:{count:0,duration:0}}}))}let V=[];for(let O=0;O<Q.length;O+=$){let U=Q.slice(O,O+$).map((Y)=>Y());V.push(...await Promise.all(U))}return V}async function hJ(J,Z=[],$=50){let W=E(),Q=[];for(let[O,U]of Object.entries(W.shards)){if(!O||!U){console.error(`Shard ${O??"<null>"} not found, skipping`);continue}Q.push(()=>U.prepare(J).bind(...Z).first().catch((Y)=>{return console.error(`Error executing query on shard ${O}:`,Y),null}))}let V=[];for(let O=0;O<Q.length;O+=$){let U=Q.slice(O,O+$).map((Y)=>Y());V.push(...await Promise.all(U))}return V}async function gJ(){let J=E();if(await new I(J.kv,{hashShardMappings:J.hashShardMappings}).clearAllMappings(),J.coordinator)try{let $=J.coordinator.idFromName("default");await J.coordinator.get($).fetch("http://coordinator/flush",{method:"POST"})}catch($){console.warn("Failed to flush coordinator:",$)}}async function pJ(J){let $=E().shards[J];if(!$)throw new G(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await FJ($)}k();class s{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 $=new URL(J.url).pathname,W=J.method;try{switch(`${W} ${$}`){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(Q){return console.error("ShardCoordinator error:",Q),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:Z}=await J.json();if(!Z||typeof Z!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let $=await this.getState();if(!$.knownShards.includes(Z))$.knownShards.push(Z),$.shardStats[Z]={binding:Z,count:0,lastUpdated:Date.now()},await this.saveState($);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleRemoveShard(J){let{shard:Z}=await J.json();if(!Z||typeof Z!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let $=await this.getState(),W=$.knownShards.indexOf(Z);if(W>-1){if($.knownShards.splice(W,1),delete $.shardStats[Z],$.roundRobinIndex>=$.knownShards.length)$.roundRobinIndex=0;await this.saveState($)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleGetStats(){let J=await this.getState(),Z=Object.values(J.shardStats);return new Response(JSON.stringify(Z),{headers:{"Content-Type":"application/json"}})}async handleUpdateStats(J){let{shard:Z,count:$}=await J.json();if(!Z||typeof Z!=="string")return new Response(JSON.stringify({error:"Missing or invalid shard parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if($===void 0||typeof $!=="number")return new Response(JSON.stringify({error:"Missing or invalid count parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let W=await this.getState();if(W.shardStats[Z])W.shardStats[Z].count=$,W.shardStats[Z].lastUpdated=Date.now(),await this.saveState(W);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleAllocateShard(J){let{primaryKey:Z,strategy:$,operationType:W,availableShards:Q}=await J.json();if(!Z||typeof Z!=="string")return new Response(JSON.stringify({error:"Missing or invalid primaryKey parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let V=await this.getState(),O=Q||V.knownShards;if(O.length===0)return new Response(JSON.stringify({error:"No shards available"}),{status:400,headers:{"Content-Type":"application/json"}});let U=this.resolveStrategy(V.strategy,$,W||"write"),Y=this.selectShard(Z,V,U,O);if(U==="round-robin")V.roundRobinIndex=(V.roundRobinIndex+1)%O.length,await this.saveState(V);return new Response(JSON.stringify({shard:Y}),{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,Z,$="write"){if(Z)return Z;if(typeof J==="string")return J;return J[$]}selectShard(J,Z,$,W){let Q=W||Z.knownShards;if(Q.length===0)throw new G("No shards available","NO_SHARDS");switch($){case"round-robin":return Q[Z.roundRobinIndex]??Q[0];case"random":return Q[Math.floor(Math.random()*Q.length)];case"hash":{let V=0;for(let U=0;U<J.length;U++){let Y=J.charCodeAt(U);V=(V<<5)-V+Y,V=V&V}let O=Math.abs(V)%Q.length;return Q[O]}case"location":{let V=Z.targetRegion,O=Z.shardLocations||{},U=Q.filter((F)=>O[F]);if(!V||U.length===0){let F=0;for(let L=0;L<J.length;L++){let D=J.charCodeAt(L);F=(F<<5)-F+D,F=F&F}let z=Math.abs(F)%Q.length;return Q[z]}let Y={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}},H=(F,z)=>(z in F),j=(F)=>H(Y,F)?F:"wnam",X=(F,z)=>{let L=Y[j(F)],D=Y[j(z)],B=L.lat-D.lat,K=L.lon-D.lon;return Math.sqrt(B*B+K*K)},x=U.map((F)=>{let z=O[F],L=X(V,z.region),D=z.priority||1;return{shard:F,score:L-D*0.1}});x.sort((F,z)=>F.score-z.score);let T=x[0].score,A=x.filter((F)=>Math.abs(F.score-T)<0.01);if(A.length===1)return A[0].shard;let _=0;for(let F=0;F<J.length;F++){let z=J.charCodeAt(F);_=(_<<5)-_+z,_=_&_}let w=Math.abs(_)%A.length;return A[w].shard}default:return Q[0]}}async incrementShardCount(J){let Z=await this.getState();if(Z.shardStats[J])Z.shardStats[J].count++,Z.shardStats[J].lastUpdated=Date.now(),await this.saveState(Z)}async decrementShardCount(J){let Z=await this.getState();if(Z.shardStats[J]&&Z.shardStats[J].count>0)Z.shardStats[J].count--,Z.shardStats[J].lastUpdated=Date.now(),await this.saveState(Z)}}if(typeof global!=="undefined"){class J{data=new Map;async get(W){return this.data.get(W)}async put(W,Q){this.data.set(W,Q)}async delete(W){return this.data.delete(W)}async deleteAll(){this.data.clear()}async list(W){if(!W?.prefix)return new Map(this.data);let Q=new Map;for(let[V,O]of this.data.entries())if(V.startsWith(W.prefix))Q.set(V,O);return Q}}class Z{storage;constructor(){this.storage=new J}}class ${coordinator;mockState;constructor(){this.mockState=new Z,this.coordinator=new s(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 Q=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"user-1",strategy:"round-robin"})}))).json(),O=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"user-2",strategy:"round-robin"})}))).json();console.assert(Q.shard!==O.shard,"Round-robin should alternate shards");let Y=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"consistent-key",strategy:"hash"})}))).json(),j=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"consistent-key",strategy:"hash"})}))).json();console.assert(Y.shard===j.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 Q=await(await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"}))).json();console.assert(Q.length===1,"Should have one shard stat"),console.assert(Q[0]?.binding==="db-stats-test","Should have correct binding name"),console.assert(Q[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 W=await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"test-key"})}));console.assert(W.status===400,"Should return 400 for no shards available");let Q=await this.coordinator.fetch(new Request("http://test/invalid",{method:"GET"}));console.assert(Q.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 W=await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"})),Q=await W.json(),V=Q.find((U)=>U.binding==="db-count-test");console.assert(V?.count===2,"Count should be 2 after two increments"),await this.coordinator.decrementShardCount("db-count-test"),W=await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"})),Q=await W.json();let O=Q.find((U)=>U.binding==="db-count-test");console.assert(O?.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(W){return console.error("❌ ShardCoordinator tests failed:",W),!1}}}globalThis.testShardCoordinator=()=>new $}k();S();f();export{p as validateTableForSharding,i as schemaExists,fJ as runShard,KJ as runAllShards,PJ as run,TJ as resetConfig,kJ as reassignShard,y as prepare,$J as migrateRecord,N as listTables,NJ as listKnownShards,WJ as integrateExistingDatabase,jJ as initializeAsync,xJ as initialize,SJ as getShardStats,pJ as getDatabaseSizeForShard,_J as getClosestRegionFromIP,gJ as flush,bJ as firstShard,hJ as firstAllShards,MJ as first,ZJ as dropSchema,g as discoverExistingRecordsWithColumns,h as discoverExistingPrimaryKeys,JJ as createSchemaAcrossShards,vJ as createSchema,QJ as createMappingsForExistingKeys,zJ as collegedb,YJ as clearShardMigrationCache,UJ as clearMigrationCache,OJ as checkMigrationNeeded,VJ as autoDetectAndMigrate,uJ as allShard,cJ as allAllShards,CJ as all,s as ShardCoordinator,I as KVShardMapper,G as CollegeDBError};
16
+ `).run()}if(S.set(F,!0),M&&Y.debug)console.log(`Auto-migration completed for shard ${X}: ${j} records from ${E} tables`)}catch(A){L.push(`Auto-migration error: ${A}`)}return{migrationNeeded:z,migrationPerformed:M,recordsMigrated:j,tablesProcessed:E,issues:L}}async function BJ(J,X,Y){let Z=`${X}_migration_check`;if(S.has(Z))return!1;try{let G=await b(J);if(G.includes("shard_mappings"))return S.set(Z,!0),!1;let{KVShardMapper:W}=await Promise.resolve().then(() => (p(),XJ)),H=new W(Y.kv,{hashShardMappings:Y.hashShardMappings,mappingCacheTtlMs:Y.mappingCacheTtlMs,knownShardsCacheTtlMs:Y.knownShardsCacheTtlMs}),V=G.filter((U)=>U!=="shard_mappings"&&!U.startsWith("sqlite_")&&U!=="sqlite_sequence");for(let U of V.slice(0,3))try{if(((await J.prepare(`SELECT COUNT(*) as count FROM ${U} LIMIT 1`).first())?.count||0)>0){let L=await J.prepare(`SELECT id FROM ${U} LIMIT 1`).first();if(L){let j=String(L.id);if(!await H.getShardMapping(j))return!0}}}catch{continue}return!1}catch{return!1}}function xJ(){S.clear()}function vJ(J){let X=`${J}_migration_check`;S.delete(X)}var S,YJ;var m=JJ(()=>{q();S=new Map,YJ=new Map});q();p();var y=null,h=null,u=new Map;function f(J){if(!h)h=new k(J.kv,{hashShardMappings:J.hashShardMappings,mappingCacheTtlMs:J.mappingCacheTtlMs,knownShardsCacheTtlMs:J.knownShardsCacheTtlMs});return h}function oJ(J){y=J,h=new k(J.kv,{hashShardMappings:J.hashShardMappings,mappingCacheTtlMs:J.mappingCacheTtlMs,knownShardsCacheTtlMs:J.knownShardsCacheTtlMs}),u.clear();try{let X=f(J);Promise.resolve().then(async()=>{let Y=await X.getKnownShards(),Z=Array.from(new Set([...Y,...Object.keys(J.shards)]));await X.setKnownShards(Z)}).catch(()=>{return})}catch{}if(J.shards&&Object.keys(J.shards).length>0&&!J.disableAutoMigration)NJ(J).catch((X)=>{console.warn("Background auto-migration failed:",X)})}async function MJ(J){y=J,h=new k(J.kv,{hashShardMappings:J.hashShardMappings,mappingCacheTtlMs:J.mappingCacheTtlMs,knownShardsCacheTtlMs:J.knownShardsCacheTtlMs}),u.clear();try{let X=f(J),Y=await X.getKnownShards(),Z=Array.from(new Set([...Y,...Object.keys(J.shards)]));await X.setKnownShards(Z)}catch{}if(J.shards&&Object.keys(J.shards).length>0&&!J.disableAutoMigration)try{await NJ(J)}catch(X){console.warn("Auto migration failed:",X)}}async function lJ(J,X){return await MJ(J),await X()}async function NJ(J){try{let{autoDetectAndMigrate:X}=await Promise.resolve().then(() => (m(),i)),Y=Object.keys(J.shards);if(J.debug)console.log(`\uD83D\uDD0D Checking ${Y.length} shards for existing data...`);let Z=Y.map(async(W)=>{let H=J.shards[W];if(!H)return null;try{let V=await X(H,W,J,{maxRecordsToCheck:1000});return{shardName:W,...V}}catch(V){return console.warn(`Auto-migration failed for shard ${W}:`,V),null}}),$=(await Promise.all(Z)).filter((W)=>W?.migrationPerformed);if(J.debug)if($.length>0){let W=$.reduce((H,V)=>H+(V?.recordsMigrated||0),0);console.log(`\uD83C\uDF89 Auto-migration completed! Migrated ${W} records across ${$.length} shards`),$.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(X){console.warn("Background auto-migration setup failed:",X)}}function nJ(){y=null,h=null,u.clear()}function w(){if(!y)throw new _("CollegeDB not initialized. Call initialize() first.","NOT_INITIALIZED");return y}function iJ(J){let X=J.trim().toUpperCase();if(X.startsWith("SELECT")||X.startsWith("VALUES")||X.startsWith("TABLE")||X.startsWith("PRAGMA")||X.startsWith("EXPLAIN")||X.startsWith("WITH")||X.startsWith("SHOW"))return"read";return"write"}function sJ(J,X){let Y=J.strategy||"hash";if(typeof Y==="string")return Y;let Z=Y;return Z[X]||Z.write||Z.read||"hash"}function tJ(J,X){if(J===X)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[J],G=Y[X],$=Z.lat-G.lat,W=Z.lon-G.lon;return Math.sqrt($*$+W*W)}function aJ(J){let X=J.cf;if(!X||!X.country)return"wnam";let{country:Y,continent:Z}=X;if(["US","CA","MX"].includes(Y)){let G=X.region||X.regionCode||"",$=X.timezone||"";if(G.includes("CA")||G.includes("WA")||G.includes("OR")||G.includes("NV")||G.includes("AZ")||G.includes("UT")||$.includes("Pacific")||$.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 rJ(J){if(typeof J==="string")return J;return J.region||"wnam"}async function CJ(J){try{let[X,Y]=await Promise.all([J.prepare("PRAGMA page_count").first(),J.prepare("PRAGMA page_size").first()]);if(!X?.page_count||!Y?.page_size)throw new _("Failed to retrieve database size information","SIZE_QUERY_FAILED");return X.page_count*Y.page_size}catch(X){throw new _(`Failed to get database size: ${X instanceof Error?X.message:"Unknown error"}`,"SIZE_QUERY_FAILED")}}async function eJ(J,X){let Y=Math.max(0,X.sizeCacheTtlMs??30000),Z=u.get(J);if(Z&&Z.expiresAt>=Date.now())return Z.size;let G=X.shards[J];if(!G)throw new _(`Shard ${J} not found in configuration`,"SHARD_NOT_FOUND");let $=await CJ(G);if(Y>0)u.set(J,{size:$,expiresAt:Date.now()+Y});return $}async function JX(J,X){if(typeof X.maxDatabaseSize!=="number"||!Number.isFinite(X.maxDatabaseSize)||X.maxDatabaseSize<=0)return J;let Y=X.maxDatabaseSize,G=(await Promise.allSettled(J.map(async($)=>{let W=await eJ($,X);return{shard:$,size:W,withinLimit:W<Y}}))).filter(($)=>$.status==="fulfilled"&&$.value.withinLimit).map(($)=>$.value.shard);if(G.length===0){if(X.debug)console.warn("All shards exceed maxDatabaseSize limit. Allowing allocation to prevent failure.");return J}if(X.debug&&G.length<J.length){let $=J.filter((W)=>!G.includes(W));console.log(`Excluded ${$.length} shards due to size limits: ${$.join(", ")}`)}return G}function XX(J,X,Y,Z){let G=X.filter((O)=>Y[O]);if(G.length===0){let O=0;for(let L=0;L<Z.length;L++){let j=Z.charCodeAt(L);O=(O<<5)-O+j,O=O&O}let F=Math.abs(O)%X.length;return X[F]}let $=G.map((O)=>{let F=Y[O],L=tJ(J,rJ(F)),j=typeof F==="object"?F.priority||1:1,E=L-j*0.1;return{shard:O,score:E,distance:L,priority:j}});$.sort((O,F)=>O.score-F.score);let W=$[0].score,H=$.filter((O)=>Math.abs(O.score-W)<0.01);if(H.length===1)return H[0].shard;let V=0;for(let O=0;O<Z.length;O++){let F=Z.charCodeAt(O);V=(V<<5)-V+F,V=V&V}let U=Math.abs(V)%H.length;return H[U].shard}function g(J,X,Y,Z){switch(J){case"hash":{let G=0;for(let W=0;W<X.length;W++){let H=X.charCodeAt(W);G=(G<<5)-G+H,G=G&G}let $=Math.abs(G)%Y.length;return Y[$]||Y[0]}case"location":{if(!Z.targetRegion)return g("hash",X,Y,Z);return XX(Z.targetRegion,Y,Z.shardLocations||{},X)}case"random":return Y[Math.floor(Math.random()*Y.length)]||Y[0];default:return g("hash",X,Y,Z)}}async function YX(J,X="write"){let Y=w(),Z=f(Y),G=await Z.getShardMapping(J);if(G)return G.shard;let $=Object.keys(Y.shards);if($.length===0)throw new _("No shards configured","NO_SHARDS");let W=await JX($,Y),H,V=sJ(Y,X);if(Y.coordinator)try{let U=Y.coordinator.idFromName("default"),F=await Y.coordinator.get(U).fetch("http://coordinator/allocate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primaryKey:J,strategy:V,operationType:X,targetRegion:Y.targetRegion,shardLocations:Y.shardLocations,availableShards:W})});if(F.ok)H=(await F.json()).shard;else H=g(V,J,W,Y)}catch(U){console.warn("Coordinator allocation failed, falling back to local strategy:",U),H=g(V,J,W,Y)}else H=g(V,J,W,Y);return await Z.setShardMapping(J,H),H}async function ZX(J,X="write"){let Y=w(),Z=await YX(J,X),G=Y.shards[Z];if(!G)throw new _(`Shard ${Z} not found in configuration`,"SHARD_NOT_FOUND");return G}async function GX(J,X){let{createSchema:Y}=await Promise.resolve().then(() => (m(),i));await Y(J,X)}async function s(J,X){let Y=iJ(X);return(await ZX(J,Y)).prepare(X)}async function $X(J,X,Y=[]){let G=await(await s(J,X)).bind(...Y).run();if(!G.success)throw new _(`Query failed: ${G.error||"Unknown error"}`,"QUERY_FAILED");return G}async function WX(J,X,Y=[]){let G=await(await s(J,X)).bind(...Y).all();if(!G.success)throw new _(`Query failed: ${G.error||"Unknown error"}`,"QUERY_FAILED");return G}async function HX(J,X,Y=[]){return await(await s(J,X)).bind(...Y).first()}async function VX(J,X,Y){let Z=w();if(!Z.shards[X])throw new _(`Shard ${X} not found in configuration`,"SHARD_NOT_FOUND");let G=f(Z),$=await G.getShardMapping(J);if(!$)throw new _(`No existing mapping found for primary key: ${J}`,"MAPPING_NOT_FOUND");if($.shard!==X){let{migrateRecord:W}=await Promise.resolve().then(() => (m(),i)),H=Z.shards[$.shard],V=Z.shards[X];if(!H||!V)throw new _("Source or target shard not available","SHARD_UNAVAILABLE");await W(H,V,J,Y)}await G.updateShardMapping(J,X)}async function UX(){let J=w();if(J.coordinator)try{let X=J.coordinator.idFromName("default"),Z=await J.coordinator.get(X).fetch("http://coordinator/shards");if(Z.ok)return await Z.json()}catch(X){console.warn("Failed to get shards from coordinator:",X)}try{let Y=await f(J).getKnownShards(),Z=new Set([...Object.keys(J.shards),...Y]);return Array.from(Z)}catch{return Object.keys(J.shards)}}async function OX(){let J=w();if(J.coordinator)try{let G=J.coordinator.idFromName("default"),W=await J.coordinator.get(G).fetch("http://coordinator/stats");if(W.ok)return await W.json()}catch(G){console.warn("Failed to get stats from coordinator:",G)}let X=f(J),Y=await X.getShardKeyCounts(),Z=Object.keys(J.shards);try{let G=await X.getKnownShards();Z=Array.from(new Set([...Z,...G]))}catch{}return Z.map((G)=>({binding:G,count:Y[G]||0}))}async function _X(J,X,Y=[]){let G=w().shards[J];if(!G)throw new _(`Shard ${J} not found`,"SHARD_NOT_FOUND");let $=await G.prepare(X).bind(...Y).run();if(!$.success)throw new _(`Query failed: ${$.error||"Unknown error"}`,"QUERY_FAILED");return $}async function FX(J,X,Y=[]){let G=w().shards[J];if(!G)throw new _(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await G.prepare(X).bind(...Y).all()}async function LX(J,X,Y=[]){let G=w().shards[J];if(!G)throw new _(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await G.prepare(X).bind(...Y).first()}async function AX(J,X=[],Y=50){let Z=w(),G=[];for(let[W,H]of Object.entries(Z.shards)){if(!W||!H){console.error(`Shard ${W??"<null>"} not found, skipping`);continue}G.push(()=>H.prepare(J).bind(...X).run().catch((V)=>{return console.error(`Error executing query on shard ${W}:`,V),{success:!1,results:[],error:V instanceof Error?V.message:String(V),meta:{duration:0}}}))}let $=[];for(let W=0;W<G.length;W+=Y){let H=G.slice(W,W+Y).map((V)=>V());$.push(...await Promise.all(H))}return $}async function IX(J,X=[],Y=50){let Z=w(),G=[];for(let[W,H]of Object.entries(Z.shards)){if(!W||!H){console.error(`Shard ${W??"<null>"} not found, skipping`);continue}G.push(()=>H.prepare(J).bind(...X).all().catch((V)=>{return console.error(`Error executing query on shard ${W}:`,V),{success:!1,results:[],error:V instanceof Error?V.message:String(V),meta:{duration:0}}}))}let $=[];for(let W=0;W<G.length;W+=Y){let H=G.slice(W,W+Y).map((V)=>V());$.push(...await Promise.all(H))}return $}async function jX(J,X=[],Y=50){let Z=w(),G=[];for(let[W,H]of Object.entries(Z.shards)){if(!W||!H){console.error(`Shard ${W??"<null>"} not found, skipping`);continue}G.push(()=>H.prepare(J).bind(...X).first().catch((V)=>{return console.error(`Error executing query on shard ${W}:`,V),null}))}let $=[];for(let W=0;W<G.length;W+=Y){let H=G.slice(W,W+Y).map((V)=>V());$.push(...await Promise.all(H))}return $}async function QX(){let J=w();if(await f(J).clearAllMappings(),u.clear(),J.coordinator)try{let Y=J.coordinator.idFromName("default");await J.coordinator.get(Y).fetch("http://coordinator/flush",{method:"POST"})}catch(Y){console.warn("Failed to flush coordinator:",Y)}}async function PX(J){let Y=w().shards[J];if(!Y)throw new _(`Shard ${J} not found`,"SHARD_NOT_FOUND");return await CJ(Y)}q();class $J{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 Y=new URL(J.url).pathname,Z=J.method;try{switch(`${Z} ${Y}`){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(G){return console.error("ShardCoordinator error:",G),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:X}=await J.json();if(!X||typeof X!=="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(X))Y.knownShards.push(X),Y.shardStats[X]={binding:X,count:0,lastUpdated:Date.now()},await this.saveState(Y);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleRemoveShard(J){let{shard:X}=await J.json();if(!X||typeof X!=="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(X);if(Z>-1){if(Y.knownShards.splice(Z,1),delete Y.shardStats[X],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 J=await this.getState(),X=Object.values(J.shardStats);return new Response(JSON.stringify(X),{headers:{"Content-Type":"application/json"}})}async handleUpdateStats(J){let{shard:X,count:Y}=await J.json();if(!X||typeof X!=="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[X])Z.shardStats[X].count=Y,Z.shardStats[X].lastUpdated=Date.now(),await this.saveState(Z);return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}async handleAllocateShard(J){let{primaryKey:X,strategy:Y,operationType:Z,availableShards:G}=await J.json();if(!X||typeof X!=="string")return new Response(JSON.stringify({error:"Missing or invalid primaryKey parameter"}),{status:400,headers:{"Content-Type":"application/json"}});let $=await this.getState(),W=G||$.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($.strategy,Y,Z||"write"),V=this.selectShard(X,$,H,W);if(H==="round-robin")$.roundRobinIndex=($.roundRobinIndex+1)%W.length,await this.saveState($);return new Response(JSON.stringify({shard:V}),{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,X,Y="write"){if(X)return X;if(typeof J==="string")return J;return J[Y]}selectShard(J,X,Y,Z){let G=Z||X.knownShards;if(G.length===0)throw new _("No shards available","NO_SHARDS");switch(Y){case"round-robin":return G[X.roundRobinIndex]??G[0];case"random":return G[Math.floor(Math.random()*G.length)];case"hash":{let $=0;for(let H=0;H<J.length;H++){let V=J.charCodeAt(H);$=($<<5)-$+V,$=$&$}let W=Math.abs($)%G.length;return G[W]}case"location":{let $=X.targetRegion,W=X.shardLocations||{},H=G.filter((A)=>W[A]);if(!$||H.length===0){let A=0;for(let R=0;R<J.length;R++){let T=J.charCodeAt(R);A=(A<<5)-A+T,A=A&A}let I=Math.abs(A)%G.length;return G[I]}let V={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,I)=>(I in A),O=(A)=>U(V,A)?A:"wnam",F=(A,I)=>{let R=V[O(A)],T=V[O(I)],P=R.lat-T.lat,Q=R.lon-T.lon;return Math.sqrt(P*P+Q*Q)},L=H.map((A)=>{let I=W[A],R=F($,I.region),T=I.priority||1;return{shard:A,score:R-T*0.1}});L.sort((A,I)=>A.score-I.score);let j=L[0].score,E=L.filter((A)=>Math.abs(A.score-j)<0.01);if(E.length===1)return E[0].shard;let z=0;for(let A=0;A<J.length;A++){let I=J.charCodeAt(A);z=(z<<5)-z+I,z=z&z}let M=Math.abs(z)%E.length;return E[M].shard}default:return G[0]}}async incrementShardCount(J){let X=await this.getState();if(X.shardStats[J])X.shardStats[J].count++,X.shardStats[J].lastUpdated=Date.now(),await this.saveState(X)}async decrementShardCount(J){let X=await this.getState();if(X.shardStats[J]&&X.shardStats[J].count>0)X.shardStats[J].count--,X.shardStats[J].lastUpdated=Date.now(),await this.saveState(X)}}if(typeof global<"u"){class J{data=new Map;async get(Z){return this.data.get(Z)}async put(Z,G){this.data.set(Z,G)}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 G=new Map;for(let[$,W]of this.data.entries())if($.startsWith(Z.prefix))G.set($,W);return G}}class X{storage;constructor(){this.storage=new J}}class Y{coordinator;mockState;constructor(){this.mockState=new X,this.coordinator=new $J(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 G=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(G.shard!==W.shard,"Round-robin should alternate shards");let V=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"consistent-key",strategy:"hash"})}))).json(),O=await(await this.coordinator.fetch(new Request("http://test/allocate",{method:"POST",body:JSON.stringify({primaryKey:"consistent-key",strategy:"hash"})}))).json();console.assert(V.shard===O.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 G=await(await this.coordinator.fetch(new Request("http://test/stats",{method:"GET"}))).json();console.assert(G.length===1,"Should have one shard stat"),console.assert(G[0]?.binding==="db-stats-test","Should have correct binding name"),console.assert(G[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 G=await this.coordinator.fetch(new Request("http://test/invalid",{method:"GET"}));console.assert(G.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"})),G=await Z.json(),$=G.find((H)=>H.binding==="db-count-test");console.assert($?.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"})),G=await Z.json();let W=G.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();p();q();var EX=500;function SJ(J,X={}){let Y=X.scanCount??EX;return{async get(Z,G="text"){let $=await J.get(Z);if($===null)return null;if(G!=="json")return $;try{return JSON.parse($)}catch(W){throw new _(`Failed to parse JSON from Redis for key ${Z}: ${W instanceof Error?W.message:String(W)}`,"KV_JSON_PARSE_FAILED")}},async put(Z,G){await J.set(Z,G)},async delete(Z){await J.del(Z)},async list(Z){let G=Z?.prefix??"",$=`${G}*`,W=Z?.cursor??"0",H=Z?.limit,V=[];do{let U=await vX(J,W,$,Y);W=U.cursor;for(let O of U.keys){if(!G||O.startsWith(G))V.push(O);if(H&&V.length>=H)break}if(H&&V.length>=H)break}while(W!=="0");return{keys:V.map((U)=>({name:U})),cursor:W,list_complete:W==="0"}}}}function TX(J,X={}){return SJ(J,X)}function fJ(J,X){if(X)return a(J,X);return{prepare(Y){return new _J(J,Y)}}}function KJ(J,X){if(X)return a(J,X);return{prepare(Y){return new FJ(J,Y)}}}function RX(J,X){if(X)return a(J,X);return{prepare(Y){return new LJ(J,Y)}}}function a(J,X){return{prepare(Y){return new AJ(J,X,Y)}}}function zX(J){return{async get(X,Y="text"){let Z=await qX(J,X);if(Z===null||Z===void 0)return null;if(Y==="json"){if(typeof Z==="string")try{return JSON.parse(Z)}catch(G){throw new _(`Failed to parse JSON from NuxtHub KV for key ${X}: ${G instanceof Error?G.message:String(G)}`,"KV_JSON_PARSE_FAILED")}return Z}return typeof Z==="string"?Z:JSON.stringify(Z)},async put(X,Y){await kX(J,X,Y)},async delete(X){await SX(J,X)},async list(X){let Y=X?.prefix??"",Z=await fX(J,Y);return{keys:(typeof X?.limit==="number"?Z.slice(0,X.limit):Z).map(($)=>({name:$})),list_complete:!0}}}}function DX(J,X){return fJ({query:async(Z,G=[])=>{let $=X(J.connectionString);if(typeof $.connect==="function")await $.connect();try{return await $.query(Z,G)}finally{if(typeof $.release==="function")$.release();else if(typeof $.end==="function")await $.end()}}})}function wX(J,X){return KJ({execute:async(Z,G=[])=>{let $=X(J.connectionString);try{if(typeof $.execute==="function")return await $.execute(Z,G);if(typeof $.query==="function")return await $.query(Z,G);throw new _("Hyperdrive MySQL client is missing execute/query methods","MYSQL_CLIENT_INVALID")}finally{if(typeof $.end==="function")await $.end();else if(typeof $.close==="function")await $.close();else if(typeof $.destroy==="function")$.destroy()}}})}function BX(J){if(!J||typeof J!=="object")return!1;return typeof J.prepare==="function"}function xX(J){if(!J||typeof J!=="object")return!1;let X=J;return typeof X.get==="function"&&typeof X.put==="function"&&typeof X.delete==="function"&&typeof X.list==="function"}class _J{client;sql;bindings;constructor(J,X,Y=[]){this.client=J,this.sql=X,this.bindings=Y}bind(...J){return new _J(this.client,this.sql,J)}async run(){let J=Date.now(),X=OJ(this.sql),Y=await this.client.query(X,this.bindings);return{success:!0,results:Y.rows??[],meta:v(J,{changes:typeof Y.rowCount==="number"?Y.rowCount:void 0,command:Y.command})}}async all(){let J=Date.now(),X=OJ(this.sql),Y=await this.client.query(X,this.bindings);return{success:!0,results:Y.rows??[],meta:v(J,{changes:typeof Y.rowCount==="number"?Y.rowCount:void 0,command:Y.command})}}async first(){let J=OJ(this.sql);return(await this.client.query(J,this.bindings)).rows?.[0]??null}}class FJ{client;sql;bindings;constructor(J,X,Y=[]){this.client=J,this.sql=X,this.bindings=Y}bind(...J){return new FJ(this.client,this.sql,J)}async run(){let J=Date.now(),X=await WJ(this.client,this.sql,this.bindings);if(Array.isArray(X))return{success:!0,results:X,meta:v(J)};let Y=X;return{success:!0,results:[],meta:v(J,{changes:Y.affectedRows,last_row_id:Y.insertId,warningStatus:Y.warningStatus})}}async all(){let J=Date.now(),X=await WJ(this.client,this.sql,this.bindings);return{success:!0,results:Array.isArray(X)?X:[],meta:v(J,{changes:!Array.isArray(X)?X.affectedRows:void 0})}}async first(){let J=await WJ(this.client,this.sql,this.bindings);if(!Array.isArray(J)||J.length===0)return null;return J[0]}}class LJ{client;sql;bindings;constructor(J,X,Y=[]){this.client=J,this.sql=X,this.bindings=Y}bind(...J){return new LJ(this.client,this.sql,J)}async run(){let J=Date.now();if(typeof this.client.execute==="function"){let G=await this.client.execute(this.sql,this.bindings);return{success:!0,results:UJ(G),meta:v(J)}}let X=this.client.prepare?.(this.sql);if(!X||typeof X.run!=="function")throw new _("SQLite client must expose execute() or prepare().run()","SQLITE_CLIENT_INVALID");let Z=await X.run(...this.bindings)??{};return{success:!0,results:[],meta:v(J,{changes:t(Z.changes),last_row_id:Z.lastInsertRowid??Z.lastID})}}async all(){let J=Date.now();if(typeof this.client.execute==="function"){let Z=await this.client.execute(this.sql,this.bindings);return{success:!0,results:UJ(Z),meta:v(J)}}let X=this.client.prepare?.(this.sql);if(!X||typeof X.all!=="function")throw new _("SQLite client must expose execute() or prepare().all()","SQLITE_CLIENT_INVALID");let Y=await X.all(...this.bindings);return{success:!0,results:Array.isArray(Y)?Y:[],meta:v(J)}}async first(){if(typeof this.client.execute==="function"){let X=await this.client.execute(this.sql,this.bindings);return UJ(X)[0]??null}let J=this.client.prepare?.(this.sql);if(!J)throw new _("SQLite client must expose execute() or prepare().get()","SQLITE_CLIENT_INVALID");if(typeof J.get==="function"){let X=await J.get(...this.bindings);return X===void 0||X===null?null:X}if(typeof J.all==="function"){let X=await J.all(...this.bindings);if(!Array.isArray(X)||X.length===0)return null;let Y=X[0];return Y===void 0||Y===null?null:Y}throw new _("SQLite prepare() result must expose get() or all()","SQLITE_CLIENT_INVALID")}}class AJ{client;sqlTag;sqlText;bindings;constructor(J,X,Y,Z=[]){this.client=J,this.sqlTag=X,this.sqlText=Y,this.bindings=Z}bind(...J){return new AJ(this.client,this.sqlTag,this.sqlText,J)}async run(){let J=Date.now(),X=HJ(this.sqlTag,this.sqlText,this.bindings),Y=await MX(this.client,X);return{success:!0,results:VJ(Y),meta:v(J,kJ(Y))}}async all(){let J=Date.now(),X=HJ(this.sqlTag,this.sqlText,this.bindings),Y=await bJ(this.client,X);return{success:!0,results:VJ(Y),meta:v(J,kJ(Y))}}async first(){let J=HJ(this.sqlTag,this.sqlText,this.bindings),X=await NX(this.client,J),Y=VJ(X);if(Y.length>0)return Y[0]??null;if(X&&typeof X==="object"&&"row"in X){let Z=X.row;return Z===void 0||Z===null?null:Z}if(X&&typeof X==="object"&&!Array.isArray(X)&&!("rows"in X)&&!("results"in X)&&!("data"in X))return X;return null}}async function vX(J,X,Y,Z){try{let G=await J.scan(X,{MATCH:Y,COUNT:Z});return qJ(G)}catch{let G=await J.scan(X,"MATCH",Y,"COUNT",String(Z));return qJ(G)}}function qJ(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 WJ(J,X,Y){if(typeof J.execute==="function"){let[Z]=await J.execute(X,Y);return Z}if(typeof J.query==="function"){let[Z]=await J.query(X,Y);return Z}throw new _("MySQL client must expose execute() or query()","MYSQL_CLIENT_INVALID")}async function MX(J,X){if(typeof J.run==="function")return await J.run(X);if(typeof J.execute==="function")return await J.execute(X);if(typeof J.all==="function")return await J.all(X);throw new _("Drizzle client must expose run(), execute(), or all()","DRIZZLE_CLIENT_INVALID")}async function bJ(J,X){if(typeof J.all==="function")return await J.all(X);if(typeof J.execute==="function")return await J.execute(X);if(typeof J.run==="function")return await J.run(X);throw new _("Drizzle client must expose all(), execute(), or run()","DRIZZLE_CLIENT_INVALID")}async function NX(J,X){if(typeof J.get==="function")return await J.get(X);return await bJ(J,X)}function HJ(J,X,Y){let Z=CX(X),G=Z.length-1;if(G!==Y.length)throw new _(`Drizzle binding mismatch: expected ${G} bindings, received ${Y.length}`,"DRIZZLE_BINDINGS_MISMATCH");if(G===0)return J.raw(X);let $=typeof J.empty==="function"?J.empty():J.raw("");for(let W=0;W<Z.length;W++){let H=Z[W];if(H)$.append(J.raw(H));if(W<G)$.append(J`${Y[W]}`)}return $}function CX(J){let X=[],Y=0,Z=!1,G=!1,$=!1,W=!1;for(let H=0;H<J.length;H++){let V=J[H],U=H+1<J.length?J[H+1]:"";if($){if(V===`
17
+ `)$=!1;continue}if(W){if(V==="*"&&U==="/")H++,W=!1;continue}if(!Z&&!G){if(V==="-"&&U==="-"){H++,$=!0;continue}if(V==="/"&&U==="*"){H++,W=!0;continue}}if(V==="'"&&!G){if(Z&&U==="'"){H++;continue}Z=!Z;continue}if(V==='"'&&!Z){if(G&&U==='"'){H++;continue}G=!G;continue}if(V==="?"&&!Z&&!G)X.push(J.slice(Y,H)),Y=H+1}return X.push(J.slice(Y)),X}function VJ(J){if(Array.isArray(J)){if(J.length===2&&Array.isArray(J[0]))return J[0];if(J.length===2&&J[0]&&typeof J[0]==="object"&&!Array.isArray(J[0])&&(Array.isArray(J[1])||J[1]===null||J[1]===void 0))return[];return J}if(J&&typeof J==="object"){let X=J;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[]}function kJ(J){if(!J)return{};let X;if(Array.isArray(J)&&J.length===2&&J[0]&&typeof J[0]==="object"&&!Array.isArray(J[0]))X=J[0];else if(typeof J==="object"&&!Array.isArray(J))X=J;if(!X)return{};let Y={},Z=t(X.rowCount)??t(X.changes)??t(X.affectedRows);if(Z!==void 0)Y.changes=Z;let G=X.lastInsertRowid??X.lastInsertId??X.insertId;if(typeof G==="number"||typeof G==="string")Y.last_row_id=G;if(X.meta&&typeof X.meta==="object")Object.assign(Y,X.meta);return Y}async function qX(J,X){if(typeof J.get==="function")return await J.get(X);if(typeof J.getItem==="function")return await J.getItem(X);throw new _("NuxtHub KV client must expose get() or getItem()","NUXTHUB_KV_CLIENT_INVALID")}async function kX(J,X,Y){if(typeof J.set==="function"){await J.set(X,Y);return}if(typeof J.setItem==="function"){await J.setItem(X,Y);return}throw new _("NuxtHub KV client must expose set() or setItem()","NUXTHUB_KV_CLIENT_INVALID")}async function SX(J,X){if(typeof J.del==="function"){await J.del(X);return}if(typeof J.removeItem==="function"){await J.removeItem(X);return}throw new _("NuxtHub KV client must expose del() or removeItem()","NUXTHUB_KV_CLIENT_INVALID")}async function fX(J,X){let Y;if(typeof J.keys==="function")Y=await J.keys(X);else if(typeof J.getKeys==="function")Y=await J.getKeys(X);else throw new _("NuxtHub KV client must expose keys() or getKeys()","NUXTHUB_KV_CLIENT_INVALID");if(!Array.isArray(Y))return[];if(!X)return Y;return Y.filter((Z)=>Z.startsWith(X))}function UJ(J){if(Array.isArray(J))return J;if(J&&typeof J==="object"){let X=J;if(Array.isArray(X.rows))return X.rows;if(Array.isArray(X.results))return X.results}return[]}function v(J,X={}){return{duration:Date.now()-J,...X}}function t(J){if(typeof J==="number"&&Number.isFinite(J))return J;return}var c=new Map;function OJ(J){let X=c.get(J);if(X)return X;let Y="",Z=0,G=!1,$=!1,W=!1,H=!1;for(let V=0;V<J.length;V++){let U=J[V],O=V+1<J.length?J[V+1]:"";if(W){if(Y+=U,U===`
18
+ `)W=!1;continue}if(H){if(Y+=U,U==="*"&&O==="/")Y+="/",V++,H=!1;continue}if(!G&&!$){if(U==="-"&&O==="-"){Y+="--",V++,W=!0;continue}if(U==="/"&&O==="*"){Y+="/*",V++,H=!0;continue}}if(U==="'"&&!$){G=!G,Y+=U;continue}if(U==='"'&&!G){$=!$,Y+=U;continue}if(U==="?"&&!G&&!$){Z++,Y+=`$${Z}`;continue}Y+=U}if(c.set(J,Y),c.size>5000){let V=c.keys().next().value;if(V)c.delete(V)}return Y}m();export{n as validateTableForSharding,GJ as schemaExists,_X as runShard,AX as runAllShards,$X as run,nJ as resetConfig,VX as reassignShard,s as prepare,RJ as migrateRecord,b as listTables,UX as listKnownShards,BX as isSQLDatabase,xX as isKVStorage,DJ as integrateExistingDatabase,MJ as initializeAsync,oJ as initialize,OX as getShardStats,PX as getDatabaseSizeForShard,aJ as getClosestRegionFromIP,QX as flush,LX as firstShard,jX as firstAllShards,HX as first,TJ as dropSchema,l as discoverExistingRecordsWithColumns,o as discoverExistingPrimaryKeys,TX as createValkeyKVProvider,EJ as createSchemaAcrossShards,GX as createSchema,RX as createSQLiteProvider,SJ as createRedisKVProvider,fJ as createPostgreSQLProvider,zX as createNuxtHubKVProvider,KJ as createMySQLProvider,zJ as createMappingsForExistingKeys,DX as createHyperdrivePostgresProvider,wX as createHyperdriveMySQLProvider,a as createDrizzleSQLProvider,lJ as collegedb,vJ as clearShardMigrationCache,xJ as clearMigrationCache,BJ as checkMigrationNeeded,wJ as autoDetectAndMigrate,FX as allShard,IX as allAllShards,WX as all,$J as ShardCoordinator,k as KVShardMapper,_ as CollegeDBError};
17
19
 
18
- //# debugId=60113EC501E41FC764756E2164756E21
20
+ //# debugId=B2F0A9ADB6FD57E164756E2164756E21
19
21
  //# sourceMappingURL=index.js.map