nodejs-json-db 0.0.2 → 0.0.3

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/index.d.ts CHANGED
@@ -712,6 +712,10 @@ declare class LazyStorage {
712
712
  private getFilePath;
713
713
  private getIndexFilePath;
714
714
  private acquireLock;
715
+ /**
716
+ * Get collection metadata and cache safely (throws if not initialized)
717
+ */
718
+ private getCollectionData;
715
719
  /**
716
720
  * Initialize a collection - loads index only, not documents
717
721
  */
@@ -1335,4 +1339,4 @@ declare function generateId(_length?: number): string;
1335
1339
  */
1336
1340
  declare function isValidId(id: unknown): id is string;
1337
1341
 
1338
- export { Collection, type CollectionData, CollectionError, type CollectionOptions, type ComparisonOperators, type Document, DocumentNotFoundError, DuplicateKeyError, type FindOptions, HighConcurrencyCollection, type HighConcurrencyOptions, HighConcurrencyStorage, JsonDB, JsonDBError, type JsonDBOptions, PartitionManager, type Projection, type Query, type QueryField, type SchemaIssue, type SchemaValidator$1 as SchemaValidator, type Sort, type SortOrder, type StorageAdapter, StorageError, type UpdateOperators, ValidationError, WorkerPool, WriteQueue, generateId, isValidId, parallelLimit };
1342
+ export { type AnyCollection, Collection, type CollectionData, CollectionError, type CollectionOptions, type ComparisonOperators, type Document, DocumentNotFoundError, DuplicateKeyError, type FindOptions, HighConcurrencyCollection, type HighConcurrencyOptions, HighConcurrencyStorage, JsonDB, JsonDBError, type JsonDBOptions, LazyCollection, PartitionManager, type Projection, type Query, type QueryField, type SchemaIssue, type SchemaValidator$1 as SchemaValidator, type Sort, type SortOrder, type StorageAdapter, StorageError, type UpdateOperators, ValidationError, WorkerPool, WriteQueue, generateId, isValidId, parallelLimit };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var d=require('fs'),S=require('path'),bson=require('bson');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__namespace=/*#__PURE__*/_interopNamespace(d);var S__namespace=/*#__PURE__*/_interopNamespace(S);var D=class extends Error{constructor(t){super(t),this.name="JsonDBError",Error.captureStackTrace?.(this,this.constructor);}},j=class extends D{constructor(t,e){super(e?`Document with id "${e}" not found in collection "${t}"`:`Document not found in collection "${t}"`),this.name="DocumentNotFoundError";}},y=class extends D{constructor(t,e){super(`Duplicate key error: document with id "${e}" already exists in collection "${t}"`),this.name="DuplicateKeyError";}},w=class extends D{collectionName;issues;field;value;constructor(t,e,i,s){let n=e.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ");super(`Validation failed for collection "${t}": ${n}`),this.name="ValidationError",this.collectionName=t,this.issues=e,this.field=i,this.value=s;}},f=class extends D{cause;constructor(t,e){super(t),this.name="StorageError",this.cause=e;}},v=class extends D{constructor(t){super(t),this.name="CollectionError";}};var F=class{dataDir;fileExtension;prettyPrint;cache=new Map;locks=new Map;constructor(t){this.dataDir=S__namespace.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.ensureDirectory();}ensureDirectory(){try{d__namespace.existsSync(this.dataDir)||d__namespace.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t){return S__namespace.join(this.dataDir,`${t}${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async read(t){if(this.cache.has(t))return this.cache.get(t);let e=this.getFilePath(t);try{if(!d__namespace.existsSync(e))return null;let i=await d__namespace.promises.readFile(e,"utf-8"),s=JSON.parse(i);return this.cache.set(t,s),s}catch(i){throw new f(`Failed to read collection "${t}"`,i)}}async write(t,e){let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`,n=await this.acquireLock(t);try{e.updatedAt=new Date().toISOString();let r=this.prettyPrint?JSON.stringify(e,null,2):JSON.stringify(e);await d__namespace.promises.writeFile(s,r,"utf-8"),await d__namespace.promises.rename(s,i),this.cache.set(t,e);}catch(r){try{d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s);}catch{}throw new f(`Failed to write collection "${t}"`,r)}finally{n();}}async exists(t){let e=this.getFilePath(t);return d__namespace.existsSync(e)}async delete(t){let e=this.getFilePath(t),i=await this.acquireLock(t);try{d__namespace.existsSync(e)&&await d__namespace.promises.unlink(e),this.cache.delete(t);}catch(s){throw new f(`Failed to delete collection "${t}"`,s)}finally{i();}}async list(){try{return (await d__namespace.promises.readdir(this.dataDir)).filter(e=>e.endsWith(this.fileExtension)).map(e=>e.slice(0,-this.fileExtension.length))}catch(t){throw new f("Failed to list collections",t)}}clearCache(t){t?this.cache.delete(t):this.cache.clear();}getDataDir(){return this.dataDir}};function P(c){return new bson.ObjectId().toHexString()}function B(c){return typeof c!="string"||c.length===0||c.length>64?false:c.length===24?bson.ObjectId.isValid(c):true}function h(c){if(c===null||typeof c!="object")return c;if(c instanceof Date)return new Date(c.getTime());if(c instanceof RegExp)return new RegExp(c.source,c.flags);if(Array.isArray(c))return c.map(e=>h(e));let t={};for(let e in c)Object.prototype.hasOwnProperty.call(c,e)&&(t[e]=h(c[e]));return t}function R(c,t){let e=t.split("."),i=c;for(let s of e){if(i==null||typeof i!="object")return;i=i[s];}return i}function x(c,t,e){let i=t.split("."),s=c;for(let n=0;n<i.length-1;n++){let r=i[n];(!(r in s)||typeof s[r]!="object"||s[r]===null)&&(s[r]={}),s=s[r];}s[i[i.length-1]]=e;}function k(c,t){let e=t.split("."),i=c;for(let n=0;n<e.length-1;n++){let r=e[n];if(!(r in i)||typeof i[r]!="object"||i[r]===null)return false;i=i[r];}let s=e[e.length-1];return s in i?(delete i[s],true):false}function V(c){return typeof c=="object"&&c!==null&&!Array.isArray(c)&&!(c instanceof Date)&&!(c instanceof RegExp)}function b(c,t){if(!t||Object.keys(t).length===0)return c;let e=Object.entries(t).filter(([a])=>a!=="_id"),i=t._id,s=e.some(([,a])=>a===1||a===true),n=e.some(([,a])=>a===0||a===false);if(s&&n)throw new Error("Cannot mix inclusion and exclusion in projection");let r=s,o={};if(r){i!==0&&i!==false&&"_id"in c&&(o._id=c._id);for(let[l,u]of e)(u===1||u===true)&&l in c&&(o[l]=c[l]);}else {let a=new Set(e.filter(([,u])=>u===0||u===false).map(([u])=>u));(i===0||i===false)&&a.add("_id");for(let u of Object.keys(c))a.has(u)||(o[u]=c[u]);}return o}var T=class{filter(t,e){return !e||Object.keys(e).length===0?t:t.filter(i=>this.matches(i,e))}matches(t,e){if("$and"in e&&e.$and)return e.$and.every(i=>this.matches(t,i));if("$or"in e&&e.$or)return e.$or.some(i=>this.matches(t,i));if("$not"in e&&e.$not)return !this.matches(t,e.$not);for(let[i,s]of Object.entries(e)){if(i.startsWith("$"))continue;let n=R(t,i);if(!this.matchesCondition(n,s))return false}return true}matchesCondition(t,e){if(!V(e)||!this.hasOperators(e))return this.isEqual(t,e);let i=e;if("$eq"in i&&!this.isEqual(t,i.$eq)||"$ne"in i&&this.isEqual(t,i.$ne)||"$gt"in i&&!this.compareValues(t,i.$gt,">")||"$gte"in i&&!this.compareValues(t,i.$gte,">=")||"$lt"in i&&!this.compareValues(t,i.$lt,"<")||"$lte"in i&&!this.compareValues(t,i.$lte,"<=")||"$in"in i&&Array.isArray(i.$in)&&!i.$in.some(s=>this.isEqual(t,s))||"$nin"in i&&Array.isArray(i.$nin)&&i.$nin.some(s=>this.isEqual(t,s)))return false;if("$exists"in i){let s=t!=null;if(i.$exists!==s)return false}if("$regex"in i&&(typeof t!="string"||!(i.$regex instanceof RegExp?i.$regex:new RegExp(i.$regex)).test(t))||"$startsWith"in i&&(typeof t!="string"||typeof i.$startsWith!="string"||!t.startsWith(i.$startsWith))||"$endsWith"in i&&(typeof t!="string"||typeof i.$endsWith!="string"||!t.endsWith(i.$endsWith))||"$contains"in i&&(!Array.isArray(t)||!t.some(s=>this.isEqual(s,i.$contains)))||"$all"in i&&Array.isArray(i.$all)&&(!Array.isArray(t)||!i.$all.every(s=>t.some(n=>this.isEqual(n,s)))))return false;if("$elemMatch"in i&&i.$elemMatch){if(!Array.isArray(t))return false;let s=i.$elemMatch;if(!t.some(r=>typeof r!="object"||r===null?false:Object.entries(s).every(([o,a])=>{let l=r[o];return this.matchesCondition(l,a)})))return false}if("$size"in i&&typeof i.$size=="number"&&(!Array.isArray(t)||t.length!==i.$size))return false;if("$type"in i&&i.$type){let s=i.$type,n;if(t===null?n="null":t===void 0?n="undefined":Array.isArray(t)?n="array":n=typeof t,n!==s)return false}if("$mod"in i&&Array.isArray(i.$mod)&&i.$mod.length===2){if(typeof t!="number")return false;let[s,n]=i.$mod;if(t%s!==n)return false}return true}hasOperators(t){return Object.keys(t).some(e=>e.startsWith("$"))}isEqual(t,e){if(t===e)return true;if(t===null||e===null||t===void 0||e===void 0)return t===e;if(typeof t!=typeof e)return false;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?false:t.every((i,s)=>this.isEqual(i,e[s]));if(typeof t=="object"&&typeof e=="object"){let i=Object.keys(t),s=Object.keys(e);return i.length!==s.length?false:i.every(n=>this.isEqual(t[n],e[n]))}return false}compareValues(t,e,i){if(typeof t=="number"&&typeof e=="number")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(typeof t=="string"&&typeof e=="string")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(t instanceof Date&&e instanceof Date)switch(i){case ">":return t.getTime()>e.getTime();case ">=":return t.getTime()>=e.getTime();case "<":return t.getTime()<e.getTime();case "<=":return t.getTime()<=e.getTime()}return false}};var O=class{name;storage;queryEngine;autoSave;saveDebounce;idGenerator;schema;saveTimeout=null;pendingSave=null;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new T,this.autoSave=i.autoSave??true,this.saveDebounce=i.saveDebounce??0,this.idGenerator=i.idGenerator??P,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new w(this.name,e.error.issues);return e.data}async getData(){let t=await this.storage.read(this.name);if(!t){let e={name:this.name,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return await this.storage.write(this.name,e),e}return t}async save(t){if(this.autoSave){if(this.saveDebounce>0)return this.saveTimeout&&clearTimeout(this.saveTimeout),new Promise(e=>{this.saveTimeout=setTimeout(async()=>{await this.storage.write(this.name,t),this.saveTimeout=null,e();},this.saveDebounce);});await this.storage.write(this.name,t);}}async flush(){this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.pendingSave&&await this.pendingSave;let t=await this.getData();await this.storage.write(this.name,t);}async insert(t){let e=await this.getData(),i=t._id||this.idGenerator();if(e.documents.some(r=>r._id===i))throw new y(this.name,i);let s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertFast(t){let e=await this.getData(),i=t._id||this.idGenerator(),s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertMany(t){if(t.length===0)return [];let e=await this.getData(),i=[],s=new Set(e.documents.map(n=>n._id));for(let n of t){let r=n._id||this.idGenerator();if(s.has(r))throw new y(this.name,r);s.add(r);let o={...h(n),_id:r},a=this.validate(o);e.documents.push(a),i.push(h(a));}return await this.save(e),i}async find(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>b(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){return this.findOne({_id:t})}async count(t){let e=await this.getData();return this.queryEngine.filter(e.documents,t).length}async update(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e);return await this.save(i),s.length}async updateOne(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.save(i),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.getData(),i=e.documents.length;e.documents=e.documents.filter(n=>!this.queryEngine.matches(n,t));let s=i-e.documents.length;return s>0&&await this.save(e),s}async deleteOne(t){let e=await this.getData(),i=e.documents.findIndex(n=>this.queryEngine.matches(n,t));if(i===-1)return null;let[s]=e.documents.splice(i,1);return await this.save(e),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){let t=await this.getData();t.documents=[],await this.save(t);}async drop(){await this.storage.delete(this.name);}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&x(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&k(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var $=class{batchSize;flushInterval;coalesceWrites;batchProcessor;queue=new Map;flushTimer=null;pendingFlush=null;totalQueued=0;isShuttingDown=false;constructor(t,e={}){this.batchSize=e.batchSize??1e3,this.flushInterval=e.flushInterval??100,this.coalesceWrites=e.coalesceWrites??true,this.batchProcessor=t;}async enqueue(t){if(this.isShuttingDown)throw new Error("WriteQueue is shutting down, no new writes accepted");return new Promise((e,i)=>{let s={operation:t,resolve:e,reject:i,timestamp:Date.now()},n=t.collectionName,r=this.queue.get(n);r||(r=[],this.queue.set(n,r)),!(this.coalesceWrites&&this.tryCoalesce(n,s))&&(r.push(s),this.totalQueued++,this.scheduleFlush(),this.totalQueued>=this.batchSize&&this.flush().catch(i));})}tryCoalesce(t,e){let i=this.queue.get(t);if(!i||i.length===0)return false;let s=e.operation;if(s.type==="update")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;if(r.type==="update"&&r.documentId===s.documentId){r.changes={...r.changes,...s.changes};let o=i[n].resolve;return i[n].resolve=()=>{o(),e.resolve();},true}}if(s.type==="delete")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;(r.type==="insert"&&r.document._id===s.documentId||r.type==="update"&&r.documentId===s.documentId)&&(i.splice(n,1),this.totalQueued--);}if(s.type==="clear"||s.type==="fullWrite"){for(let n of i)n.resolve();i.length=0,this.totalQueued-=i.length;}return false}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(t=>{console.error("WriteQueue flush error:",t);});},this.flushInterval));}async flush(){if(this.pendingFlush)return this.pendingFlush;if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.totalQueued===0)return;let t=this.queue;this.queue=new Map,this.totalQueued=0;let e=new Map;for(let[i,s]of t)e.set(i,s.map(n=>n.operation));this.pendingFlush=this.processBatch(t,e),await this.pendingFlush,this.pendingFlush=null;}async processBatch(t,e){try{await this.batchProcessor(e);for(let i of t.values())for(let s of i)s.resolve();}catch(i){for(let s of t.values())for(let n of s)n.reject(i);}}async shutdown(){this.isShuttingDown=true,await this.flush();}pending(){return this.totalQueued}isEmpty(){return this.totalQueued===0}isClosing(){return this.isShuttingDown}};var A=class{dataDir;partitionCount;prettyPrint;fileExtension;cache=new Map;locks=new Map;constructor(t,e={}){this.dataDir=S__namespace.resolve(t),this.partitionCount=e.partitionCount??16,this.prettyPrint=e.prettyPrint??true,this.fileExtension=e.fileExtension??".json",this.ensureDirectory();}ensureDirectory(){try{d__namespace.existsSync(this.dataDir)||d__namespace.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getPartitionIndex(t){let e=0;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=(e<<5)-e+s,e=e&e;}return Math.abs(e)%this.partitionCount}getPartitionFileName(t,e){return `${t}_p${e.toString().padStart(3,"0")}${this.fileExtension}`}getPartitionFilePath(t,e){return S__namespace.join(this.dataDir,this.getPartitionFileName(t,e))}getCacheKey(t,e){return `${t}:${e}`}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async readPartition(t,e){let i=this.getCacheKey(t,e);if(this.cache.has(i))return this.cache.get(i);let s=this.getPartitionFilePath(t,e);try{if(!d__namespace.existsSync(s))return null;let n=await d__namespace.promises.readFile(s,"utf-8"),r=JSON.parse(n);return this.cache.set(i,r),r}catch(n){throw new f(`Failed to read partition ${e} for collection "${t}"`,n)}}async writePartition(t,e,i){let s=this.getPartitionFilePath(t,e),n=`${s}.tmp.${Date.now()}`,r=this.getCacheKey(t,e),o=await this.acquireLock(r);try{i.updatedAt=new Date().toISOString();let a=this.prettyPrint?JSON.stringify(i,null,2):JSON.stringify(i);await d__namespace.promises.writeFile(n,a,"utf-8"),await d__namespace.promises.rename(n,s),this.cache.set(r,i);}catch(a){try{d__namespace.existsSync(n)&&await d__namespace.promises.unlink(n);}catch{}throw new f(`Failed to write partition ${e} for collection "${t}"`,a)}finally{o();}}async readAllPartitions(t){let e=new Map,i=[];for(let s=0;s<this.partitionCount;s++)i.push(this.readPartition(t,s).then(n=>{n&&e.set(s,n);}));return await Promise.all(i),e}async writePartitions(t,e){let i=[];for(let[s,n]of e)i.push(this.writePartition(t,s,n));await Promise.all(i);}async initializePartitions(t){let e=[];for(let i=0;i<this.partitionCount;i++)if(!d__namespace.existsSync(this.getPartitionFilePath(t,i))){let n={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};e.push(this.writePartition(t,i,n));}await Promise.all(e);}async getPartitionInfo(t){let e=await this.readAllPartitions(t),i=[];for(let s=0;s<this.partitionCount;s++){let n=e.get(s);i.push({name:this.getPartitionFileName(t,s),partitionIndex:s,documentCount:n?.documents.length??0});}return i}async getAllDocuments(t){let e=await this.readAllPartitions(t),i=[];for(let s of e.values())i.push(...s.documents);return i}async findById(t,e){let i=this.getPartitionIndex(e),s=await this.readPartition(t,i);return s?s.documents.find(n=>n._id===e)??null:null}async deleteCollection(t){let e=[];for(let i=0;i<this.partitionCount;i++){let s=this.getPartitionFilePath(t,i),n=this.getCacheKey(t,i);e.push((async()=>{let r=await this.acquireLock(n);try{d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s),this.cache.delete(n);}finally{r();}})());}await Promise.all(e);}clearCache(t){if(t)for(let e=0;e<this.partitionCount;e++)this.cache.delete(this.getCacheKey(t,e));else this.cache.clear();}getPartitionCount(){return this.partitionCount}async listCollections(){try{let t=await d__namespace.promises.readdir(this.dataDir),e=new Set,i=new RegExp(`^(.+)_p\\d{3}\\${this.fileExtension}$`);for(let s of t){let n=s.match(i);n&&e.add(n[1]);}return Array.from(e)}catch(t){throw new f("Failed to list partitioned collections",t)}}};var E=class{maxConcurrent;maxQueueSize;queue=[];activeCount=0;completedCount=0;failedCount=0;isShuttingDown=false;constructor(t={}){this.maxConcurrent=t.maxConcurrent??4,this.maxQueueSize=t.maxQueueSize??1e4;}async submit(t,e=0){if(this.isShuttingDown)throw new Error("WorkerPool is shutting down, no new tasks accepted");if(this.queue.length>=this.maxQueueSize)throw new Error("WorkerPool queue is full, task rejected (backpressure)");return new Promise((i,s)=>{let n={task:t,resolve:i,reject:s,priority:e},r=false;for(let o=0;o<this.queue.length;o++)if(e>this.queue[o].priority){this.queue.splice(o,0,n),r=true;break}r||this.queue.push(n),this.processNext();})}async submitAll(t,e=0){let i=t.map(s=>this.submit(s,e));return Promise.all(i)}async*submitStream(t,e=0){let i=t.map(s=>this.submit(s,e));for(let s of i)yield await s;}processNext(){if(this.activeCount>=this.maxConcurrent||this.queue.length===0)return;let t=this.queue.shift();t&&(this.activeCount++,t.task().then(e=>{this.completedCount++,t.resolve(e);}).catch(e=>{this.failedCount++,t.reject(e);}).finally(()=>{this.activeCount--,this.processNext();}));}async drain(){return new Promise(t=>{let e=()=>{this.activeCount===0&&this.queue.length===0?t():setImmediate(e);};e();})}async shutdown(){this.isShuttingDown=true,await this.drain();}getStats(){return {activeWorkers:this.activeCount,queuedTasks:this.queue.length,completedTasks:this.completedCount,failedTasks:this.failedCount}}isIdle(){return this.activeCount===0&&this.queue.length===0}isClosing(){return this.isShuttingDown}queueSize(){return this.queue.length}activeWorkers(){return this.activeCount}};async function q(c,t,e){let i=[],s=0;async function n(){let o=s++;o>=c.length||(i[o]=await e(c[o],o),await n());}let r=Array(Math.min(t,c.length)).fill(null).map(()=>n());return await Promise.all(r),i}var U={partitions:16,batchSize:1e3,flushInterval:100,maxConcurrentIO:4,coalesceWrites:true},I=class{partitionManager;writeQueue;workerPool;options;constructor(t){let e=t.highConcurrency;this.options={...U,...e},this.partitionManager=new A(t.dataDir,{partitionCount:this.options.partitions,prettyPrint:t.prettyPrint??true,fileExtension:t.fileExtension??".json"}),this.workerPool=new E({maxConcurrent:this.options.maxConcurrentIO});let i=this.processBatch.bind(this);this.writeQueue=new $(i,{batchSize:this.options.batchSize,flushInterval:this.options.flushInterval,coalesceWrites:this.options.coalesceWrites});}async processBatch(t){let e=Array.from(t.entries());await q(e,this.options.maxConcurrentIO,async([i,s])=>{await this.processCollectionOperations(i,s);});}async processCollectionOperations(t,e){let i=new Map,s=n=>{let r=i.get(n);return r||(r=[],i.set(n,r)),r};for(let n of e)if(n.type==="fullWrite"||n.type==="clear")for(let r=0;r<this.partitionManager.getPartitionCount();r++)s(r).push(n);else if(n.type==="insert"){let r=this.partitionManager.getPartitionIndex(n.document._id);s(r).push(n);}else if(n.type==="update"||n.type==="delete"){let r=this.partitionManager.getPartitionIndex(n.documentId);s(r).push(n);}else if(n.type==="bulkInsert")for(let r of n.documents){let o=this.partitionManager.getPartitionIndex(r._id);s(o).push({type:"insert",collectionName:t,document:r});}else if(n.type==="bulkUpdate"||n.type==="bulkDelete")for(let r of n.documentIds){let o=this.partitionManager.getPartitionIndex(r);n.type==="bulkUpdate"?s(o).push({type:"update",collectionName:t,documentId:r,changes:n.changes}):s(o).push({type:"delete",collectionName:t,documentId:r});}await q(Array.from(i.entries()),this.options.maxConcurrentIO,async([n,r])=>{await this.processPartitionOperations(t,n,r);});}async processPartitionOperations(t,e,i){let s=await this.partitionManager.readPartition(t,e);s||(s={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});for(let n of i)switch(n.type){case "insert":s.documents.push(n.document);break;case "update":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&Object.assign(s.documents[r],n.changes);break}case "delete":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&s.documents.splice(r,1);break}case "clear":s.documents=[];break;case "fullWrite":{let r=n.data.documents.filter(o=>this.partitionManager.getPartitionIndex(o._id)===e);s.documents=r;break}}await this.partitionManager.writePartition(t,e,s);}async insert(t,e){await this.writeQueue.enqueue({type:"insert",collectionName:t,document:e});}async insertMany(t,e){await this.writeQueue.enqueue({type:"bulkInsert",collectionName:t,documents:e});}async update(t,e,i){await this.writeQueue.enqueue({type:"update",collectionName:t,documentId:e,changes:i});}async delete(t,e){await this.writeQueue.enqueue({type:"delete",collectionName:t,documentId:e});}async clear(t){await this.writeQueue.enqueue({type:"clear",collectionName:t});}async findById(t,e){return await this.writeQueue.flush(),this.partitionManager.findById(t,e)}async readAll(t){return await this.writeQueue.flush(),this.partitionManager.getAllDocuments(t)}async exists(t){return (await this.partitionManager.listCollections()).includes(t)}async initializeCollection(t){await this.partitionManager.initializePartitions(t);}async deleteCollection(t){await this.writeQueue.flush(),await this.partitionManager.deleteCollection(t);}async listCollections(){return this.partitionManager.listCollections()}async flush(){await this.writeQueue.flush();}async shutdown(){await this.writeQueue.shutdown(),await this.workerPool.shutdown();}pendingWrites(){return this.writeQueue.pending()}getStats(){return {pendingWrites:this.writeQueue.pending(),workerPool:this.workerPool.getStats(),partitions:this.options.partitions}}clearCache(t){this.partitionManager.clearCache(t);}};var _=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new T,this.idGenerator=i.idGenerator??P,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new w(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(await this.storage.findById(this.name,e))throw new y(this.name,e);let s={...h(t),_id:e},n=this.validate(s);return await this.storage.insert(this.name,n),n}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insert(this.name,s),s}async insertMany(t){if(t.length===0)return [];let e=[],i=[];for(let s of t){let n=s._id||this.idGenerator(),r={...h(s),_id:n},o=this.validate(r);i.push(o),e.push(h(o));}return await this.storage.insertMany(this.name,i),e}async find(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.findById(this.name,t);return e?h(e):null}async count(t){let e=await this.storage.readAll(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s){let r=this.getUpdateChanges(n,e);await this.storage.update(this.name,n._id,r);}return s.length}async updateOne(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0],r=this.getUpdateChanges(n,e);return await this.storage.update(this.name,n._id,r),Object.assign(n,r),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;for(let s of i)await this.storage.delete(this.name,s._id);return i.length}async deleteOne(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.delete(this.name,s._id),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){await this.storage.clear(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}getUpdateChanges(t,e){if(!Object.keys(e).some(r=>r.startsWith("$")))return e;let s=e,n={};if(s.$set)for(let[r,o]of Object.entries(s.$set))r!=="_id"&&(n[r]=o);if(s.$inc)for(let[r,o]of Object.entries(s.$inc)){let a=t[r];typeof a=="number"&&typeof o=="number"&&(n[r]=a+o);}if(s.$push)for(let[r,o]of Object.entries(s.$push)){let a=t[r];Array.isArray(a)&&(n[r]=[...a,o]);}if(s.$pull)for(let[r,o]of Object.entries(s.$pull)){let a=t[r];Array.isArray(a)&&(n[r]=a.filter(l=>JSON.stringify(l)!==JSON.stringify(o)));}if(s.$addToSet)for(let[r,o]of Object.entries(s.$addToSet)){let a=t[r];Array.isArray(a)&&(a.some(u=>JSON.stringify(u)===JSON.stringify(o))?n[r]=a:n[r]=[...a,o]);}return n}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var C=class{capacity;cache;constructor(t){this.capacity=t,this.cache=new Map;}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}forEach(t){this.cache.forEach(t);}};var W=class{dataDir;fileExtension;prettyPrint;cacheSize;chunkSize;documentCache;collections;locks;constructor(t){this.dataDir=S__namespace.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.cacheSize=t.lazyLoading?.cacheSize??1e3,this.chunkSize=t.lazyLoading?.chunkSize??1e4,this.documentCache=new Map,this.collections=new Map,this.locks=new Map,this.ensureDirectory();}ensureDirectory(){try{d__namespace.existsSync(this.dataDir)||d__namespace.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t,e){return e!==void 0&&this.chunkSize>0?S__namespace.join(this.dataDir,`${t}_chunk${e}${this.fileExtension}`):S__namespace.join(this.dataDir,`${t}${this.fileExtension}`)}getIndexFilePath(t){return S__namespace.join(this.dataDir,`${t}.index${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async initCollection(t){if(this.collections.has(t))return;let e=this.getFilePath(t),i=this.getIndexFilePath(t);if(d__namespace.existsSync(i))try{let s=await d__namespace.promises.readFile(i,"utf-8"),n=JSON.parse(s),r={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:new Map(n.ids.map((o,a)=>[o,{id:o,offset:a}])),count:n.ids.length,dirty:!1};this.collections.set(t,r),this.documentCache.set(t,new C(this.cacheSize));return}catch{}if(d__namespace.existsSync(e))try{let s=await d__namespace.promises.readFile(e,"utf-8"),n=JSON.parse(s),r=new Map;n.documents.forEach((u,Q)=>{r.set(u._id,{id:u._id,offset:Q});});let o={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:r,count:n.documents.length,dirty:!1};this.collections.set(t,o),this.documentCache.set(t,new C(this.cacheSize));let a=this.documentCache.get(t),l=Math.min(n.documents.length,this.cacheSize);for(let u=0;u<l;u++)a.set(n.documents[u]._id,n.documents[u]);await this.saveIndex(t);}catch(s){throw new f(`Failed to initialize collection "${t}"`,s)}else {let s={name:t,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),index:new Map,count:0,dirty:false};this.collections.set(t,s),this.documentCache.set(t,new C(this.cacheSize));}}async saveIndex(t){let e=this.collections.get(t);if(!e)return;let i=this.getIndexFilePath(t),s={name:t,createdAt:e.createdAt,updatedAt:e.updatedAt,ids:Array.from(e.index.keys())},n=this.prettyPrint?JSON.stringify(s,null,2):JSON.stringify(s);await d__namespace.promises.writeFile(i,n,"utf-8");}getCount(t){return this.collections.get(t)?.count??0}hasDocument(t,e){return this.collections.get(t)?.index.has(e)??false}getDocumentIds(t){let e=this.collections.get(t);return e?Array.from(e.index.keys()):[]}async getDocument(t,e){await this.initCollection(t);let i=this.collections.get(t);if(!i||!i.index.has(e))return null;let s=this.documentCache.get(t),n=s.get(e);if(n)return n;let r=await this.loadDocumentFromDisk(t,e);return r&&s.set(e,r),r}async loadDocumentFromDisk(t,e){let i=this.getFilePath(t);try{let s=await d__namespace.promises.readFile(i,"utf-8");return JSON.parse(s).documents.find(r=>r._id===e)??null}catch{return null}}async getDocuments(t,e){await this.initCollection(t);let i=this.documentCache.get(t),s=[],n=[];for(let r of e){let o=i.get(r);o?s.push(o):n.push(r);}if(n.length>0){let r=await this.loadDocumentsFromDisk(t,n);for(let o of r)i.set(o._id,o),s.push(o);}return s}async loadDocumentsFromDisk(t,e){let i=this.getFilePath(t),s=new Set(e);try{let n=await d__namespace.promises.readFile(i,"utf-8");return JSON.parse(n).documents.filter(o=>s.has(o._id))}catch{return []}}async getAllDocuments(t){await this.initCollection(t);let e=this.getFilePath(t);try{if(!d__namespace.existsSync(e))return [];let i=await d__namespace.promises.readFile(e,"utf-8"),s=JSON.parse(i),n=this.documentCache.get(t);for(let r of s.documents)n.set(r._id,r);return s.documents}catch{return []}}async insertDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);s.index.set(e._id,{id:e._id,offset:s.count}),s.count++,s.updatedAt=new Date().toISOString(),s.dirty=!0,n.set(e._id,e),await this.persistCollection(t);}finally{i();}}async insertDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);for(let r of e)s.index.set(r._id,{id:r._id,offset:s.count}),s.count++,n.set(r._id,r);s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async updateDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);if(!s.index.has(e._id))return;n.set(e._id,e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);if(!s.index.has(e))return;s.index.delete(e),s.count--,n.delete(e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);for(let r of e)s.index.has(r)&&(s.index.delete(r),s.count--,n.delete(r));s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async clearCollection(t){await this.initCollection(t);let e=await this.acquireLock(t);try{let i=this.collections.get(t),s=this.documentCache.get(t);i.index.clear(),i.count=0,s.clear(),i.updatedAt=new Date().toISOString(),i.dirty=!0,await this.persistCollection(t);}finally{e();}}async persistCollection(t){let e=this.collections.get(t);if(!e)return;let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`;try{let n=await this.buildDocumentArray(t),r={name:t,documents:n,createdAt:e.createdAt,updatedAt:e.updatedAt},o=this.prettyPrint?JSON.stringify(r,null,2):JSON.stringify(r);await d__namespace.promises.writeFile(s,o,"utf-8"),await d__namespace.promises.rename(s,i),await this.saveIndex(t),e.dirty=!1;}catch(n){try{d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s);}catch{}throw new f(`Failed to persist collection "${t}"`,n)}}async buildDocumentArray(t){let e=this.collections.get(t);if(!e||e.count===0)return [];let i=this.getFilePath(t),s=[];try{if(d__namespace.existsSync(i)){let a=await d__namespace.promises.readFile(i,"utf-8");s=JSON.parse(a).documents;}}catch{}let n=new Map;for(let a of s)n.set(a._id,a);this.documentCache.get(t).forEach((a,l)=>{n.set(l,a);});let o=[];for(let a of e.index.keys()){let l=n.get(a);l&&o.push(l);}return o}async deleteCollection(t){let e=await this.acquireLock(t);try{this.collections.delete(t),this.documentCache.delete(t);let i=this.getFilePath(t),s=this.getIndexFilePath(t);d__namespace.existsSync(i)&&await d__namespace.promises.unlink(i),d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s);}finally{e();}}async exists(t){if(this.collections.has(t))return true;let e=this.getFilePath(t);return d__namespace.existsSync(e)}async list(){try{let t=await d__namespace.promises.readdir(this.dataDir),e=new Set;for(let i of t)i.includes(".index")||i.includes("_chunk")||i.endsWith(this.fileExtension)&&e.add(i.slice(0,-this.fileExtension.length));return Array.from(e)}catch{return []}}getStats(){let t=0;for(let e of this.documentCache.values())t+=e.size;return {collections:this.collections.size,cachedDocuments:t,cacheSize:this.cacheSize}}clearCache(t){if(t)this.documentCache.get(t)?.clear();else for(let e of this.documentCache.values())e.clear();}async flush(){for(let[t,e]of this.collections.entries())e.dirty&&await this.persistCollection(t);}getDataDir(){return this.dataDir}};var L=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new T,this.idGenerator=i.idGenerator??P,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new w(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(this.storage.hasDocument(this.name,e))throw new y(this.name,e);let i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertMany(t){if(t.length===0)return [];let e=new Set(this.storage.getDocumentIds(this.name)),i=[];for(let s of t){let n=s._id||this.idGenerator();if(e.has(n))throw new y(this.name,n);e.add(n);let r={...h(s),_id:n},o=this.validate(r);i.push(o);}return await this.storage.insertDocuments(this.name,i),i.map(s=>h(s))}async find(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>b(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.getDocument(this.name,t);return e?h(e):null}async count(t){if(!t||Object.keys(t).length===0)return this.storage.getCount(this.name);let e=await this.storage.getAllDocuments(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n);return s.length}async updateOne(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n),h(n)}async updateById(t,e){let i=await this.storage.getDocument(this.name,t);return i?(this.applyUpdate(i,e),await this.storage.updateDocument(this.name,i),h(i)):null}async delete(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;let s=i.map(n=>n._id);return await this.storage.deleteDocuments(this.name,s),i.length}async deleteOne(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.deleteDocument(this.name,s._id),h(s)}async deleteById(t){let e=await this.storage.getDocument(this.name,t);return e?(await this.storage.deleteDocument(this.name,t),h(e)):null}async getAll(){return this.find()}async clear(){await this.storage.clearCollection(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&x(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&k(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var K={autoSave:true,saveDebounce:0,prettyPrint:true,fileExtension:".json"},H=class{options;storage;hcStorage;lazyStorage;collections=new Map;isHighConcurrency;isLazyLoading;connected=false;constructor(t){if(this.options={...K,...t},this.isHighConcurrency=t.highConcurrency?.enabled??false,this.isLazyLoading=t.lazyLoading?.enabled??false,this.isHighConcurrency&&this.isLazyLoading)throw new Error("Cannot enable both highConcurrency and lazyLoading modes simultaneously");this.isHighConcurrency?(this.storage=null,this.hcStorage=new I(this.options),this.lazyStorage=null):this.isLazyLoading?(this.storage=null,this.hcStorage=null,this.lazyStorage=new W(this.options)):(this.storage=new F(this.options),this.hcStorage=null,this.lazyStorage=null);}getStorage(){if(this.storage===null)throw new Error("Storage is not available in high-concurrency or lazy loading mode");return this.storage}getHCStorage(){if(this.hcStorage===null)throw new Error("HighConcurrencyStorage is not available in standard or lazy loading mode");return this.hcStorage}getLazyStorage(){if(this.lazyStorage===null)throw new Error("LazyStorage is not available in standard or high-concurrency mode");return this.lazyStorage}async connect(){if(!this.connected){if(this.isHighConcurrency){let t=await this.getHCStorage().listCollections();for(let e of t)this.getOrCreateCollection(e);}else if(this.isLazyLoading){let t=await this.getLazyStorage().list();for(let e of t)this.getOrCreateCollection(e);}else {let t=await this.getStorage().list();for(let e of t)this.getOrCreateCollection(e);}this.connected=true;}}async close(){if(this.connected){for(let t of this.collections.values())await t.flush();this.isHighConcurrency&&this.hcStorage&&await this.hcStorage.shutdown(),this.collections.clear(),this.storage&&this.storage.clearCache(),this.hcStorage&&this.hcStorage.clearCache(),this.lazyStorage&&this.lazyStorage.clearCache(),this.connected=false;}}collection(t,e){if(!t||typeof t!="string")throw new v("Collection name must be a non-empty string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(t))throw new v("Collection name must start with a letter or underscore and contain only letters, numbers, underscores, and hyphens");return this.getOrCreateCollection(t,e)}getOrCreateCollection(t,e){if(this.collections.has(t))return this.collections.get(t);if(this.isHighConcurrency){let i=new _(t,this.getHCStorage(),{schema:e?.schema});this.collections.set(t,i);}else if(this.isLazyLoading){let i=new L(t,this.getLazyStorage(),{schema:e?.schema});this.collections.set(t,i);}else {let i=new O(t,this.getStorage(),{autoSave:this.options.autoSave,saveDebounce:this.options.saveDebounce,schema:e?.schema});this.collections.set(t,i);}return this.collections.get(t)}async hasCollection(t){return this.isHighConcurrency?this.getHCStorage().exists(t):this.getStorage().exists(t)}async listCollections(){return this.isHighConcurrency?this.getHCStorage().listCollections():this.getStorage().list()}async dropCollection(t){let e=this.collections.get(t);e?(await e.drop(),this.collections.delete(t)):this.isHighConcurrency?await this.getHCStorage().deleteCollection(t):await this.getStorage().delete(t);}async drop(){if(this.isHighConcurrency){let t=this.getHCStorage(),e=await t.listCollections();for(let i of e)await t.deleteCollection(i);}else {let t=this.getStorage(),e=await t.list();for(let i of e)await t.delete(i);}this.collections.clear(),this.storage?.clearCache(),this.hcStorage?.clearCache();}getDataDir(){return this.isHighConcurrency?this.options.dataDir:this.getStorage().getDataDir()}isConnected(){return this.connected}isHighConcurrencyMode(){return this.isHighConcurrency}getStats(){return !this.isHighConcurrency||!this.hcStorage?null:this.hcStorage.getStats()}async flush(){for(let t of this.collections.values())await t.flush();}};exports.Collection=O;exports.CollectionError=v;exports.DocumentNotFoundError=j;exports.DuplicateKeyError=y;exports.HighConcurrencyCollection=_;exports.HighConcurrencyStorage=I;exports.JsonDB=H;exports.JsonDBError=D;exports.PartitionManager=A;exports.StorageError=f;exports.ValidationError=w;exports.WorkerPool=E;exports.WriteQueue=$;exports.generateId=P;exports.isValidId=B;exports.parallelLimit=q;
1
+ 'use strict';var d=require('fs'),S=require('path'),bson=require('bson');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__namespace=/*#__PURE__*/_interopNamespace(d);var S__namespace=/*#__PURE__*/_interopNamespace(S);var D=class extends Error{constructor(t){super(t),this.name="JsonDBError",Error.captureStackTrace?.(this,this.constructor);}},j=class extends D{constructor(t,e){super(e?`Document with id "${e}" not found in collection "${t}"`:`Document not found in collection "${t}"`),this.name="DocumentNotFoundError";}},y=class extends D{constructor(t,e){super(`Duplicate key error: document with id "${e}" already exists in collection "${t}"`),this.name="DuplicateKeyError";}},w=class extends D{collectionName;issues;field;value;constructor(t,e,i,s){let n=e.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ");super(`Validation failed for collection "${t}": ${n}`),this.name="ValidationError",this.collectionName=t,this.issues=e,this.field=i,this.value=s;}},f=class extends D{cause;constructor(t,e){super(t),this.name="StorageError",this.cause=e;}},v=class extends D{constructor(t){super(t),this.name="CollectionError";}};var z=class{dataDir;fileExtension;prettyPrint;cache=new Map;locks=new Map;constructor(t){this.dataDir=S__namespace.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.ensureDirectory();}ensureDirectory(){try{d__namespace.existsSync(this.dataDir)||d__namespace.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t){return S__namespace.join(this.dataDir,`${t}${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async read(t){if(this.cache.has(t))return this.cache.get(t);let e=this.getFilePath(t);try{if(!d__namespace.existsSync(e))return null;let i=await d__namespace.promises.readFile(e,"utf-8"),s=JSON.parse(i);return this.cache.set(t,s),s}catch(i){throw new f(`Failed to read collection "${t}"`,i)}}async write(t,e){let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`,n=await this.acquireLock(t);try{e.updatedAt=new Date().toISOString();let r=this.prettyPrint?JSON.stringify(e,null,2):JSON.stringify(e);await d__namespace.promises.writeFile(s,r,"utf-8"),await d__namespace.promises.rename(s,i),this.cache.set(t,e);}catch(r){try{d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s);}catch{}throw new f(`Failed to write collection "${t}"`,r)}finally{n();}}async exists(t){let e=this.getFilePath(t);return d__namespace.existsSync(e)}async delete(t){let e=this.getFilePath(t),i=await this.acquireLock(t);try{d__namespace.existsSync(e)&&await d__namespace.promises.unlink(e),this.cache.delete(t);}catch(s){throw new f(`Failed to delete collection "${t}"`,s)}finally{i();}}async list(){try{return (await d__namespace.promises.readdir(this.dataDir)).filter(e=>e.endsWith(this.fileExtension)).map(e=>e.slice(0,-this.fileExtension.length))}catch(t){throw new f("Failed to list collections",t)}}clearCache(t){t?this.cache.delete(t):this.cache.clear();}getDataDir(){return this.dataDir}};function P(c){return new bson.ObjectId().toHexString()}function B(c){return typeof c!="string"||c.length===0||c.length>64?false:c.length===24?bson.ObjectId.isValid(c):true}function h(c){if(c===null||typeof c!="object")return c;if(c instanceof Date)return new Date(c.getTime());if(c instanceof RegExp)return new RegExp(c.source,c.flags);if(Array.isArray(c))return c.map(e=>h(e));let t={};for(let e in c)Object.prototype.hasOwnProperty.call(c,e)&&(t[e]=h(c[e]));return t}function R(c,t){let e=t.split("."),i=c;for(let s of e){if(i==null||typeof i!="object")return;i=i[s];}return i}function x(c,t,e){let i=t.split("."),s=c;for(let n=0;n<i.length-1;n++){let r=i[n];(!(r in s)||typeof s[r]!="object"||s[r]===null)&&(s[r]={}),s=s[r];}s[i[i.length-1]]=e;}function k(c,t){let e=t.split("."),i=c;for(let n=0;n<e.length-1;n++){let r=e[n];if(!(r in i)||typeof i[r]!="object"||i[r]===null)return false;i=i[r];}let s=e[e.length-1];return s in i?(delete i[s],true):false}function V(c){return typeof c=="object"&&c!==null&&!Array.isArray(c)&&!(c instanceof Date)&&!(c instanceof RegExp)}function b(c,t){if(!t||Object.keys(t).length===0)return c;let e=Object.entries(t).filter(([a])=>a!=="_id"),i=t._id,s=e.some(([,a])=>a===1||a===true),n=e.some(([,a])=>a===0||a===false);if(s&&n)throw new Error("Cannot mix inclusion and exclusion in projection");let r=s,o={};if(r){i!==0&&i!==false&&"_id"in c&&(o._id=c._id);for(let[l,u]of e)(u===1||u===true)&&l in c&&(o[l]=c[l]);}else {let a=new Set(e.filter(([,u])=>u===0||u===false).map(([u])=>u));(i===0||i===false)&&a.add("_id");for(let u of Object.keys(c))a.has(u)||(o[u]=c[u]);}return o}var T=class{filter(t,e){return !e||Object.keys(e).length===0?t:t.filter(i=>this.matches(i,e))}matches(t,e){if("$and"in e&&e.$and)return e.$and.every(i=>this.matches(t,i));if("$or"in e&&e.$or)return e.$or.some(i=>this.matches(t,i));if("$not"in e&&e.$not)return !this.matches(t,e.$not);for(let[i,s]of Object.entries(e)){if(i.startsWith("$"))continue;let n=R(t,i);if(!this.matchesCondition(n,s))return false}return true}matchesCondition(t,e){if(!V(e)||!this.hasOperators(e))return this.isEqual(t,e);let i=e;if("$eq"in i&&!this.isEqual(t,i.$eq)||"$ne"in i&&this.isEqual(t,i.$ne)||"$gt"in i&&!this.compareValues(t,i.$gt,">")||"$gte"in i&&!this.compareValues(t,i.$gte,">=")||"$lt"in i&&!this.compareValues(t,i.$lt,"<")||"$lte"in i&&!this.compareValues(t,i.$lte,"<=")||"$in"in i&&Array.isArray(i.$in)&&!i.$in.some(s=>this.isEqual(t,s))||"$nin"in i&&Array.isArray(i.$nin)&&i.$nin.some(s=>this.isEqual(t,s)))return false;if("$exists"in i){let s=t!=null;if(i.$exists!==s)return false}if("$regex"in i&&(typeof t!="string"||!(i.$regex instanceof RegExp?i.$regex:new RegExp(i.$regex)).test(t))||"$startsWith"in i&&(typeof t!="string"||typeof i.$startsWith!="string"||!t.startsWith(i.$startsWith))||"$endsWith"in i&&(typeof t!="string"||typeof i.$endsWith!="string"||!t.endsWith(i.$endsWith))||"$contains"in i&&(!Array.isArray(t)||!t.some(s=>this.isEqual(s,i.$contains)))||"$all"in i&&Array.isArray(i.$all)&&(!Array.isArray(t)||!i.$all.every(s=>t.some(n=>this.isEqual(n,s)))))return false;if("$elemMatch"in i&&i.$elemMatch){if(!Array.isArray(t))return false;let s=i.$elemMatch;if(!t.some(r=>typeof r!="object"||r===null?false:Object.entries(s).every(([o,a])=>{let l=r[o];return this.matchesCondition(l,a)})))return false}if("$size"in i&&typeof i.$size=="number"&&(!Array.isArray(t)||t.length!==i.$size))return false;if("$type"in i&&i.$type){let s=i.$type,n;if(t===null?n="null":t===void 0?n="undefined":Array.isArray(t)?n="array":n=typeof t,n!==s)return false}if("$mod"in i&&Array.isArray(i.$mod)&&i.$mod.length===2){if(typeof t!="number")return false;let[s,n]=i.$mod;if(t%s!==n)return false}return true}hasOperators(t){return Object.keys(t).some(e=>e.startsWith("$"))}isEqual(t,e){if(t===e)return true;if(t===null||e===null||t===void 0||e===void 0)return t===e;if(typeof t!=typeof e)return false;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?false:t.every((i,s)=>this.isEqual(i,e[s]));if(typeof t=="object"&&typeof e=="object"){let i=Object.keys(t),s=Object.keys(e);return i.length!==s.length?false:i.every(n=>this.isEqual(t[n],e[n]))}return false}compareValues(t,e,i){if(typeof t=="number"&&typeof e=="number")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(typeof t=="string"&&typeof e=="string")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(t instanceof Date&&e instanceof Date)switch(i){case ">":return t.getTime()>e.getTime();case ">=":return t.getTime()>=e.getTime();case "<":return t.getTime()<e.getTime();case "<=":return t.getTime()<=e.getTime()}return false}};var O=class{name;storage;queryEngine;autoSave;saveDebounce;idGenerator;schema;saveTimeout=null;pendingSave=null;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new T,this.autoSave=i.autoSave??true,this.saveDebounce=i.saveDebounce??0,this.idGenerator=i.idGenerator??P,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new w(this.name,e.error.issues);return e.data}async getData(){let t=await this.storage.read(this.name);if(!t){let e={name:this.name,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return await this.storage.write(this.name,e),e}return t}async save(t){if(this.autoSave){if(this.saveDebounce>0)return this.saveTimeout&&clearTimeout(this.saveTimeout),new Promise(e=>{this.saveTimeout=setTimeout(async()=>{await this.storage.write(this.name,t),this.saveTimeout=null,e();},this.saveDebounce);});await this.storage.write(this.name,t);}}async flush(){this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.pendingSave&&await this.pendingSave;let t=await this.getData();await this.storage.write(this.name,t);}async insert(t){let e=await this.getData(),i=t._id||this.idGenerator();if(e.documents.some(r=>r._id===i))throw new y(this.name,i);let s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertFast(t){let e=await this.getData(),i=t._id||this.idGenerator(),s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertMany(t){if(t.length===0)return [];let e=await this.getData(),i=[],s=new Set(e.documents.map(n=>n._id));for(let n of t){let r=n._id||this.idGenerator();if(s.has(r))throw new y(this.name,r);s.add(r);let o={...h(n),_id:r},a=this.validate(o);e.documents.push(a),i.push(h(a));}return await this.save(e),i}async find(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>b(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){return this.findOne({_id:t})}async count(t){let e=await this.getData();return this.queryEngine.filter(e.documents,t).length}async update(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e);return await this.save(i),s.length}async updateOne(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.save(i),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.getData(),i=e.documents.length;e.documents=e.documents.filter(n=>!this.queryEngine.matches(n,t));let s=i-e.documents.length;return s>0&&await this.save(e),s}async deleteOne(t){let e=await this.getData(),i=e.documents.findIndex(n=>this.queryEngine.matches(n,t));if(i===-1)return null;let[s]=e.documents.splice(i,1);return await this.save(e),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){let t=await this.getData();t.documents=[],await this.save(t);}async drop(){await this.storage.delete(this.name);}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&x(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&k(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var $=class{batchSize;flushInterval;coalesceWrites;batchProcessor;queue=new Map;flushTimer=null;pendingFlush=null;totalQueued=0;isShuttingDown=false;constructor(t,e={}){this.batchSize=e.batchSize??1e3,this.flushInterval=e.flushInterval??100,this.coalesceWrites=e.coalesceWrites??true,this.batchProcessor=t;}async enqueue(t){if(this.isShuttingDown)throw new Error("WriteQueue is shutting down, no new writes accepted");return new Promise((e,i)=>{let s={operation:t,resolve:e,reject:i,timestamp:Date.now()},n=t.collectionName,r=this.queue.get(n);r||(r=[],this.queue.set(n,r)),!(this.coalesceWrites&&this.tryCoalesce(n,s))&&(r.push(s),this.totalQueued++,this.scheduleFlush(),this.totalQueued>=this.batchSize&&this.flush().catch(i));})}tryCoalesce(t,e){let i=this.queue.get(t);if(!i||i.length===0)return false;let s=e.operation;if(s.type==="update")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;if(r.type==="update"&&r.documentId===s.documentId){r.changes={...r.changes,...s.changes};let o=i[n].resolve;return i[n].resolve=()=>{o(),e.resolve();},true}}if(s.type==="delete")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;(r.type==="insert"&&r.document._id===s.documentId||r.type==="update"&&r.documentId===s.documentId)&&(i.splice(n,1),this.totalQueued--);}if(s.type==="clear"||s.type==="fullWrite"){for(let n of i)n.resolve();i.length=0,this.totalQueued-=i.length;}return false}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(t=>{console.error("WriteQueue flush error:",t);});},this.flushInterval));}async flush(){if(this.pendingFlush)return this.pendingFlush;if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.totalQueued===0)return;let t=this.queue;this.queue=new Map,this.totalQueued=0;let e=new Map;for(let[i,s]of t)e.set(i,s.map(n=>n.operation));this.pendingFlush=this.processBatch(t,e),await this.pendingFlush,this.pendingFlush=null;}async processBatch(t,e){try{await this.batchProcessor(e);for(let i of t.values())for(let s of i)s.resolve();}catch(i){for(let s of t.values())for(let n of s)n.reject(i);}}async shutdown(){this.isShuttingDown=true,await this.flush();}pending(){return this.totalQueued}isEmpty(){return this.totalQueued===0}isClosing(){return this.isShuttingDown}};var A=class{dataDir;partitionCount;prettyPrint;fileExtension;cache=new Map;locks=new Map;constructor(t,e={}){this.dataDir=S__namespace.resolve(t),this.partitionCount=e.partitionCount??16,this.prettyPrint=e.prettyPrint??true,this.fileExtension=e.fileExtension??".json",this.ensureDirectory();}ensureDirectory(){try{d__namespace.existsSync(this.dataDir)||d__namespace.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getPartitionIndex(t){let e=0;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=(e<<5)-e+s,e=e&e;}return Math.abs(e)%this.partitionCount}getPartitionFileName(t,e){return `${t}_p${e.toString().padStart(3,"0")}${this.fileExtension}`}getPartitionFilePath(t,e){return S__namespace.join(this.dataDir,this.getPartitionFileName(t,e))}getCacheKey(t,e){return `${t}:${e}`}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async readPartition(t,e){let i=this.getCacheKey(t,e);if(this.cache.has(i))return this.cache.get(i);let s=this.getPartitionFilePath(t,e);try{if(!d__namespace.existsSync(s))return null;let n=await d__namespace.promises.readFile(s,"utf-8"),r=JSON.parse(n);return this.cache.set(i,r),r}catch(n){throw new f(`Failed to read partition ${e} for collection "${t}"`,n)}}async writePartition(t,e,i){let s=this.getPartitionFilePath(t,e),n=`${s}.tmp.${Date.now()}`,r=this.getCacheKey(t,e),o=await this.acquireLock(r);try{i.updatedAt=new Date().toISOString();let a=this.prettyPrint?JSON.stringify(i,null,2):JSON.stringify(i);await d__namespace.promises.writeFile(n,a,"utf-8"),await d__namespace.promises.rename(n,s),this.cache.set(r,i);}catch(a){try{d__namespace.existsSync(n)&&await d__namespace.promises.unlink(n);}catch{}throw new f(`Failed to write partition ${e} for collection "${t}"`,a)}finally{o();}}async readAllPartitions(t){let e=new Map,i=[];for(let s=0;s<this.partitionCount;s++)i.push(this.readPartition(t,s).then(n=>{n&&e.set(s,n);}));return await Promise.all(i),e}async writePartitions(t,e){let i=[];for(let[s,n]of e)i.push(this.writePartition(t,s,n));await Promise.all(i);}async initializePartitions(t){let e=[];for(let i=0;i<this.partitionCount;i++)if(!d__namespace.existsSync(this.getPartitionFilePath(t,i))){let n={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};e.push(this.writePartition(t,i,n));}await Promise.all(e);}async getPartitionInfo(t){let e=await this.readAllPartitions(t),i=[];for(let s=0;s<this.partitionCount;s++){let n=e.get(s);i.push({name:this.getPartitionFileName(t,s),partitionIndex:s,documentCount:n?.documents.length??0});}return i}async getAllDocuments(t){let e=await this.readAllPartitions(t),i=[];for(let s of e.values())i.push(...s.documents);return i}async findById(t,e){let i=this.getPartitionIndex(e),s=await this.readPartition(t,i);return s?s.documents.find(n=>n._id===e)??null:null}async deleteCollection(t){let e=[];for(let i=0;i<this.partitionCount;i++){let s=this.getPartitionFilePath(t,i),n=this.getCacheKey(t,i);e.push((async()=>{let r=await this.acquireLock(n);try{d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s),this.cache.delete(n);}finally{r();}})());}await Promise.all(e);}clearCache(t){if(t)for(let e=0;e<this.partitionCount;e++)this.cache.delete(this.getCacheKey(t,e));else this.cache.clear();}getPartitionCount(){return this.partitionCount}async listCollections(){try{let t=await d__namespace.promises.readdir(this.dataDir),e=new Set,i=new RegExp(`^(.+)_p\\d{3}\\${this.fileExtension}$`);for(let s of t){let n=s.match(i);n&&e.add(n[1]);}return Array.from(e)}catch(t){throw new f("Failed to list partitioned collections",t)}}};var E=class{maxConcurrent;maxQueueSize;queue=[];activeCount=0;completedCount=0;failedCount=0;isShuttingDown=false;constructor(t={}){this.maxConcurrent=t.maxConcurrent??4,this.maxQueueSize=t.maxQueueSize??1e4;}async submit(t,e=0){if(this.isShuttingDown)throw new Error("WorkerPool is shutting down, no new tasks accepted");if(this.queue.length>=this.maxQueueSize)throw new Error("WorkerPool queue is full, task rejected (backpressure)");return new Promise((i,s)=>{let n={task:t,resolve:i,reject:s,priority:e},r=false;for(let o=0;o<this.queue.length;o++)if(e>this.queue[o].priority){this.queue.splice(o,0,n),r=true;break}r||this.queue.push(n),this.processNext();})}async submitAll(t,e=0){let i=t.map(s=>this.submit(s,e));return Promise.all(i)}async*submitStream(t,e=0){let i=t.map(s=>this.submit(s,e));for(let s of i)yield await s;}processNext(){if(this.activeCount>=this.maxConcurrent||this.queue.length===0)return;let t=this.queue.shift();t&&(this.activeCount++,t.task().then(e=>{this.completedCount++,t.resolve(e);}).catch(e=>{this.failedCount++,t.reject(e);}).finally(()=>{this.activeCount--,this.processNext();}));}async drain(){return new Promise(t=>{let e=()=>{this.activeCount===0&&this.queue.length===0?t():setImmediate(e);};e();})}async shutdown(){this.isShuttingDown=true,await this.drain();}getStats(){return {activeWorkers:this.activeCount,queuedTasks:this.queue.length,completedTasks:this.completedCount,failedTasks:this.failedCount}}isIdle(){return this.activeCount===0&&this.queue.length===0}isClosing(){return this.isShuttingDown}queueSize(){return this.queue.length}activeWorkers(){return this.activeCount}};async function W(c,t,e){let i=[],s=0;async function n(){let o=s++;o>=c.length||(i[o]=await e(c[o],o),await n());}let r=Array(Math.min(t,c.length)).fill(null).map(()=>n());return await Promise.all(r),i}var U={partitions:16,batchSize:1e3,flushInterval:100,maxConcurrentIO:4,coalesceWrites:true},I=class{partitionManager;writeQueue;workerPool;options;constructor(t){let e=t.highConcurrency;this.options={...U,...e},this.partitionManager=new A(t.dataDir,{partitionCount:this.options.partitions,prettyPrint:t.prettyPrint??true,fileExtension:t.fileExtension??".json"}),this.workerPool=new E({maxConcurrent:this.options.maxConcurrentIO});let i=this.processBatch.bind(this);this.writeQueue=new $(i,{batchSize:this.options.batchSize,flushInterval:this.options.flushInterval,coalesceWrites:this.options.coalesceWrites});}async processBatch(t){let e=Array.from(t.entries());await W(e,this.options.maxConcurrentIO,async([i,s])=>{await this.processCollectionOperations(i,s);});}async processCollectionOperations(t,e){let i=new Map,s=n=>{let r=i.get(n);return r||(r=[],i.set(n,r)),r};for(let n of e)if(n.type==="fullWrite"||n.type==="clear")for(let r=0;r<this.partitionManager.getPartitionCount();r++)s(r).push(n);else if(n.type==="insert"){let r=this.partitionManager.getPartitionIndex(n.document._id);s(r).push(n);}else if(n.type==="update"||n.type==="delete"){let r=this.partitionManager.getPartitionIndex(n.documentId);s(r).push(n);}else if(n.type==="bulkInsert")for(let r of n.documents){let o=this.partitionManager.getPartitionIndex(r._id);s(o).push({type:"insert",collectionName:t,document:r});}else if(n.type==="bulkUpdate"||n.type==="bulkDelete")for(let r of n.documentIds){let o=this.partitionManager.getPartitionIndex(r);n.type==="bulkUpdate"?s(o).push({type:"update",collectionName:t,documentId:r,changes:n.changes}):s(o).push({type:"delete",collectionName:t,documentId:r});}await W(Array.from(i.entries()),this.options.maxConcurrentIO,async([n,r])=>{await this.processPartitionOperations(t,n,r);});}async processPartitionOperations(t,e,i){let s=await this.partitionManager.readPartition(t,e);s||(s={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});for(let n of i)switch(n.type){case "insert":s.documents.push(n.document);break;case "update":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&Object.assign(s.documents[r],n.changes);break}case "delete":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&s.documents.splice(r,1);break}case "clear":s.documents=[];break;case "fullWrite":{let r=n.data.documents.filter(o=>this.partitionManager.getPartitionIndex(o._id)===e);s.documents=r;break}}await this.partitionManager.writePartition(t,e,s);}async insert(t,e){await this.writeQueue.enqueue({type:"insert",collectionName:t,document:e});}async insertMany(t,e){await this.writeQueue.enqueue({type:"bulkInsert",collectionName:t,documents:e});}async update(t,e,i){await this.writeQueue.enqueue({type:"update",collectionName:t,documentId:e,changes:i});}async delete(t,e){await this.writeQueue.enqueue({type:"delete",collectionName:t,documentId:e});}async clear(t){await this.writeQueue.enqueue({type:"clear",collectionName:t});}async findById(t,e){return await this.writeQueue.flush(),this.partitionManager.findById(t,e)}async readAll(t){return await this.writeQueue.flush(),this.partitionManager.getAllDocuments(t)}async exists(t){return (await this.partitionManager.listCollections()).includes(t)}async initializeCollection(t){await this.partitionManager.initializePartitions(t);}async deleteCollection(t){await this.writeQueue.flush(),await this.partitionManager.deleteCollection(t);}async listCollections(){return this.partitionManager.listCollections()}async flush(){await this.writeQueue.flush();}async shutdown(){await this.writeQueue.shutdown(),await this.workerPool.shutdown();}pendingWrites(){return this.writeQueue.pending()}getStats(){return {pendingWrites:this.writeQueue.pending(),workerPool:this.workerPool.getStats(),partitions:this.options.partitions}}clearCache(t){this.partitionManager.clearCache(t);}};var _=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new T,this.idGenerator=i.idGenerator??P,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new w(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(await this.storage.findById(this.name,e))throw new y(this.name,e);let s={...h(t),_id:e},n=this.validate(s);return await this.storage.insert(this.name,n),n}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insert(this.name,s),s}async insertMany(t){if(t.length===0)return [];let e=[],i=[];for(let s of t){let n=s._id||this.idGenerator(),r={...h(s),_id:n},o=this.validate(r);i.push(o),e.push(h(o));}return await this.storage.insertMany(this.name,i),e}async find(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.findById(this.name,t);return e?h(e):null}async count(t){let e=await this.storage.readAll(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s){let r=this.getUpdateChanges(n,e);await this.storage.update(this.name,n._id,r);}return s.length}async updateOne(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0],r=this.getUpdateChanges(n,e);return await this.storage.update(this.name,n._id,r),Object.assign(n,r),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;for(let s of i)await this.storage.delete(this.name,s._id);return i.length}async deleteOne(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.delete(this.name,s._id),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){await this.storage.clear(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}getUpdateChanges(t,e){if(!Object.keys(e).some(r=>r.startsWith("$")))return e;let s=e,n={};if(s.$set)for(let[r,o]of Object.entries(s.$set))r!=="_id"&&(n[r]=o);if(s.$inc)for(let[r,o]of Object.entries(s.$inc)){let a=t[r];typeof a=="number"&&typeof o=="number"&&(n[r]=a+o);}if(s.$push)for(let[r,o]of Object.entries(s.$push)){let a=t[r];Array.isArray(a)&&(n[r]=[...a,o]);}if(s.$pull)for(let[r,o]of Object.entries(s.$pull)){let a=t[r];Array.isArray(a)&&(n[r]=a.filter(l=>JSON.stringify(l)!==JSON.stringify(o)));}if(s.$addToSet)for(let[r,o]of Object.entries(s.$addToSet)){let a=t[r];Array.isArray(a)&&(a.some(u=>JSON.stringify(u)===JSON.stringify(o))?n[r]=a:n[r]=[...a,o]);}return n}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var C=class{capacity;cache;constructor(t){this.capacity=t,this.cache=new Map;}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);if(e!==void 0)return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}forEach(t){this.cache.forEach(t);}};var L=class{dataDir;fileExtension;prettyPrint;cacheSize;chunkSize;documentCache;collections;locks;constructor(t){this.dataDir=S__namespace.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.cacheSize=t.lazyLoading?.cacheSize??1e3,this.chunkSize=t.lazyLoading?.chunkSize??1e4,this.documentCache=new Map,this.collections=new Map,this.locks=new Map,this.ensureDirectory();}ensureDirectory(){try{d__namespace.existsSync(this.dataDir)||d__namespace.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t,e){return e!==void 0&&this.chunkSize>0?S__namespace.join(this.dataDir,`${t}_chunk${e}${this.fileExtension}`):S__namespace.join(this.dataDir,`${t}${this.fileExtension}`)}getIndexFilePath(t){return S__namespace.join(this.dataDir,`${t}.index${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}getCollectionData(t){let e=this.collections.get(t),i=this.documentCache.get(t);if(!e||!i)throw new f(`Collection "${t}" is not initialized`,new Error("Not initialized"));return {meta:e,cache:i}}async initCollection(t){if(this.collections.has(t))return;let e=this.getFilePath(t),i=this.getIndexFilePath(t);if(d__namespace.existsSync(i))try{let s=await d__namespace.promises.readFile(i,"utf-8"),n=JSON.parse(s),r={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:new Map(n.ids.map((o,a)=>[o,{id:o,offset:a}])),count:n.ids.length,dirty:!1};this.collections.set(t,r),this.documentCache.set(t,new C(this.cacheSize));return}catch{}if(d__namespace.existsSync(e))try{let s=await d__namespace.promises.readFile(e,"utf-8"),n=JSON.parse(s),r=new Map;n.documents.forEach((u,F)=>{r.set(u._id,{id:u._id,offset:F});});let o={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:r,count:n.documents.length,dirty:!1};this.collections.set(t,o),this.documentCache.set(t,new C(this.cacheSize));let{cache:a}=this.getCollectionData(t),l=Math.min(n.documents.length,this.cacheSize);for(let u=0;u<l;u++)a.set(n.documents[u]._id,n.documents[u]);await this.saveIndex(t);}catch(s){throw new f(`Failed to initialize collection "${t}"`,s)}else {let s={name:t,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),index:new Map,count:0,dirty:false};this.collections.set(t,s),this.documentCache.set(t,new C(this.cacheSize));}}async saveIndex(t){let e=this.collections.get(t);if(!e)return;let i=this.getIndexFilePath(t),s={name:t,createdAt:e.createdAt,updatedAt:e.updatedAt,ids:Array.from(e.index.keys())},n=this.prettyPrint?JSON.stringify(s,null,2):JSON.stringify(s);await d__namespace.promises.writeFile(i,n,"utf-8");}getCount(t){return this.collections.get(t)?.count??0}hasDocument(t,e){return this.collections.get(t)?.index.has(e)??false}getDocumentIds(t){let e=this.collections.get(t);return e?Array.from(e.index.keys()):[]}async getDocument(t,e){await this.initCollection(t);let i=this.collections.get(t);if(!i||!i.index.has(e))return null;let{cache:s}=this.getCollectionData(t),n=s.get(e);if(n)return n;let r=await this.loadDocumentFromDisk(t,e);return r&&s.set(e,r),r}async loadDocumentFromDisk(t,e){let i=this.getFilePath(t);try{let s=await d__namespace.promises.readFile(i,"utf-8");return JSON.parse(s).documents.find(r=>r._id===e)??null}catch{return null}}async getDocuments(t,e){await this.initCollection(t);let{cache:i}=this.getCollectionData(t),s=[],n=[];for(let r of e){let o=i.get(r);o?s.push(o):n.push(r);}if(n.length>0){let r=await this.loadDocumentsFromDisk(t,n);for(let o of r)i.set(o._id,o),s.push(o);}return s}async loadDocumentsFromDisk(t,e){let i=this.getFilePath(t),s=new Set(e);try{let n=await d__namespace.promises.readFile(i,"utf-8");return JSON.parse(n).documents.filter(o=>s.has(o._id))}catch{return []}}async getAllDocuments(t){await this.initCollection(t);let e=this.getFilePath(t);try{if(!d__namespace.existsSync(e))return [];let i=await d__namespace.promises.readFile(e,"utf-8"),s=JSON.parse(i),{cache:n}=this.getCollectionData(t);for(let r of s.documents)n.set(r._id,r);return s.documents}catch{return []}}async insertDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);s.index.set(e._id,{id:e._id,offset:s.count}),s.count++,s.updatedAt=new Date().toISOString(),s.dirty=!0,n.set(e._id,e),await this.persistCollection(t);}finally{i();}}async insertDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);for(let r of e)s.index.set(r._id,{id:r._id,offset:s.count}),s.count++,n.set(r._id,r);s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async updateDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);if(!s.index.has(e._id))return;n.set(e._id,e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);if(!s.index.has(e))return;s.index.delete(e),s.count--,n.delete(e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);for(let r of e)s.index.has(r)&&(s.index.delete(r),s.count--,n.delete(r));s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async clearCollection(t){await this.initCollection(t);let e=await this.acquireLock(t);try{let{meta:i,cache:s}=this.getCollectionData(t);i.index.clear(),i.count=0,s.clear(),i.updatedAt=new Date().toISOString(),i.dirty=!0,await this.persistCollection(t);}finally{e();}}async persistCollection(t){let e=this.collections.get(t);if(!e)return;let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`;try{let n=await this.buildDocumentArray(t),r={name:t,documents:n,createdAt:e.createdAt,updatedAt:e.updatedAt},o=this.prettyPrint?JSON.stringify(r,null,2):JSON.stringify(r);await d__namespace.promises.writeFile(s,o,"utf-8"),await d__namespace.promises.rename(s,i),await this.saveIndex(t),e.dirty=!1;}catch(n){try{d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s);}catch{}throw new f(`Failed to persist collection "${t}"`,n)}}async buildDocumentArray(t){let e=this.collections.get(t);if(!e||e.count===0)return [];let i=this.getFilePath(t),s=[];try{if(d__namespace.existsSync(i)){let a=await d__namespace.promises.readFile(i,"utf-8");s=JSON.parse(a).documents;}}catch{}let n=new Map;for(let a of s)n.set(a._id,a);let{cache:r}=this.getCollectionData(t);r.forEach((a,l)=>{n.set(l,a);});let o=[];for(let a of e.index.keys()){let l=n.get(a);l&&o.push(l);}return o}async deleteCollection(t){let e=await this.acquireLock(t);try{this.collections.delete(t),this.documentCache.delete(t);let i=this.getFilePath(t),s=this.getIndexFilePath(t);d__namespace.existsSync(i)&&await d__namespace.promises.unlink(i),d__namespace.existsSync(s)&&await d__namespace.promises.unlink(s);}finally{e();}}async exists(t){if(this.collections.has(t))return true;let e=this.getFilePath(t);return d__namespace.existsSync(e)}async list(){try{let t=await d__namespace.promises.readdir(this.dataDir),e=new Set;for(let i of t)i.includes(".index")||i.includes("_chunk")||i.endsWith(this.fileExtension)&&e.add(i.slice(0,-this.fileExtension.length));return Array.from(e)}catch{return []}}getStats(){let t=0;for(let e of this.documentCache.values())t+=e.size;return {collections:this.collections.size,cachedDocuments:t,cacheSize:this.cacheSize}}clearCache(t){if(t)this.documentCache.get(t)?.clear();else for(let e of this.documentCache.values())e.clear();}async flush(){for(let[t,e]of this.collections.entries())e.dirty&&await this.persistCollection(t);}getDataDir(){return this.dataDir}};var Q=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new T,this.idGenerator=i.idGenerator??P,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new w(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(this.storage.hasDocument(this.name,e))throw new y(this.name,e);let i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertMany(t){if(t.length===0)return [];let e=new Set(this.storage.getDocumentIds(this.name)),i=[];for(let s of t){let n=s._id||this.idGenerator();if(e.has(n))throw new y(this.name,n);e.add(n);let r={...h(s),_id:n},o=this.validate(r);i.push(o);}return await this.storage.insertDocuments(this.name,i),i.map(s=>h(s))}async find(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>b(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.getDocument(this.name,t);return e?h(e):null}async count(t){if(!t||Object.keys(t).length===0)return this.storage.getCount(this.name);let e=await this.storage.getAllDocuments(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n);return s.length}async updateOne(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n),h(n)}async updateById(t,e){let i=await this.storage.getDocument(this.name,t);return i?(this.applyUpdate(i,e),await this.storage.updateDocument(this.name,i),h(i)):null}async delete(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;let s=i.map(n=>n._id);return await this.storage.deleteDocuments(this.name,s),i.length}async deleteOne(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.deleteDocument(this.name,s._id),h(s)}async deleteById(t){let e=await this.storage.getDocument(this.name,t);return e?(await this.storage.deleteDocument(this.name,t),h(e)):null}async getAll(){return this.find()}async clear(){await this.storage.clearCollection(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&x(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&k(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var K={autoSave:true,saveDebounce:0,prettyPrint:true,fileExtension:".json"},J=class{options;storage;hcStorage;lazyStorage;collections=new Map;isHighConcurrency;isLazyLoading;connected=false;constructor(t){if(this.options={...K,...t},this.isHighConcurrency=t.highConcurrency?.enabled??false,this.isLazyLoading=t.lazyLoading?.enabled??false,this.isHighConcurrency&&this.isLazyLoading)throw new Error("Cannot enable both highConcurrency and lazyLoading modes simultaneously");this.isHighConcurrency?(this.storage=null,this.hcStorage=new I(this.options),this.lazyStorage=null):this.isLazyLoading?(this.storage=null,this.hcStorage=null,this.lazyStorage=new L(this.options)):(this.storage=new z(this.options),this.hcStorage=null,this.lazyStorage=null);}getStorage(){if(this.storage===null)throw new Error("Storage is not available in high-concurrency or lazy loading mode");return this.storage}getHCStorage(){if(this.hcStorage===null)throw new Error("HighConcurrencyStorage is not available in standard or lazy loading mode");return this.hcStorage}getLazyStorage(){if(this.lazyStorage===null)throw new Error("LazyStorage is not available in standard or high-concurrency mode");return this.lazyStorage}async connect(){if(!this.connected){if(this.isHighConcurrency){let t=await this.getHCStorage().listCollections();for(let e of t)this.getOrCreateCollection(e);}else if(this.isLazyLoading){let t=await this.getLazyStorage().list();for(let e of t)this.getOrCreateCollection(e);}else {let t=await this.getStorage().list();for(let e of t)this.getOrCreateCollection(e);}this.connected=true;}}async close(){if(this.connected){for(let t of this.collections.values())await t.flush();this.isHighConcurrency&&this.hcStorage&&await this.hcStorage.shutdown(),this.collections.clear(),this.storage&&this.storage.clearCache(),this.hcStorage&&this.hcStorage.clearCache(),this.lazyStorage&&this.lazyStorage.clearCache(),this.connected=false;}}collection(t,e){if(!t||typeof t!="string")throw new v("Collection name must be a non-empty string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(t))throw new v("Collection name must start with a letter or underscore and contain only letters, numbers, underscores, and hyphens");return this.getOrCreateCollection(t,e)}getOrCreateCollection(t,e){if(this.collections.has(t))return this.collections.get(t);if(this.isHighConcurrency){let i=new _(t,this.getHCStorage(),{schema:e?.schema});this.collections.set(t,i);}else if(this.isLazyLoading){let i=new Q(t,this.getLazyStorage(),{schema:e?.schema});this.collections.set(t,i);}else {let i=new O(t,this.getStorage(),{autoSave:this.options.autoSave,saveDebounce:this.options.saveDebounce,schema:e?.schema});this.collections.set(t,i);}return this.collections.get(t)}async hasCollection(t){return this.isHighConcurrency?this.getHCStorage().exists(t):this.getStorage().exists(t)}async listCollections(){return this.isHighConcurrency?this.getHCStorage().listCollections():this.getStorage().list()}async dropCollection(t){let e=this.collections.get(t);e?(await e.drop(),this.collections.delete(t)):this.isHighConcurrency?await this.getHCStorage().deleteCollection(t):await this.getStorage().delete(t);}async drop(){if(this.isHighConcurrency){let t=this.getHCStorage(),e=await t.listCollections();for(let i of e)await t.deleteCollection(i);}else {let t=this.getStorage(),e=await t.list();for(let i of e)await t.delete(i);}this.collections.clear(),this.storage?.clearCache(),this.hcStorage?.clearCache();}getDataDir(){return this.isHighConcurrency?this.options.dataDir:this.getStorage().getDataDir()}isConnected(){return this.connected}isHighConcurrencyMode(){return this.isHighConcurrency}getStats(){return !this.isHighConcurrency||!this.hcStorage?null:this.hcStorage.getStats()}async flush(){for(let t of this.collections.values())await t.flush();}};exports.Collection=O;exports.CollectionError=v;exports.DocumentNotFoundError=j;exports.DuplicateKeyError=y;exports.HighConcurrencyCollection=_;exports.HighConcurrencyStorage=I;exports.JsonDB=J;exports.JsonDBError=D;exports.LazyCollection=Q;exports.PartitionManager=A;exports.StorageError=f;exports.ValidationError=w;exports.WorkerPool=E;exports.WriteQueue=$;exports.generateId=P;exports.isValidId=B;exports.parallelLimit=W;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import*as d from'fs';import*as x from'path';import {ObjectId}from'bson';var P=class extends Error{constructor(t){super(t),this.name="JsonDBError",Error.captureStackTrace?.(this,this.constructor);}},R=class extends P{constructor(t,e){super(e?`Document with id "${e}" not found in collection "${t}"`:`Document not found in collection "${t}"`),this.name="DocumentNotFoundError";}},w=class extends P{constructor(t,e){super(`Duplicate key error: document with id "${e}" already exists in collection "${t}"`),this.name="DuplicateKeyError";}},T=class extends P{collectionName;issues;field;value;constructor(t,e,i,s){let n=e.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ");super(`Validation failed for collection "${t}": ${n}`),this.name="ValidationError",this.collectionName=t,this.issues=e,this.field=i,this.value=s;}},f=class extends P{cause;constructor(t,e){super(t),this.name="StorageError",this.cause=e;}},C=class extends P{constructor(t){super(t),this.name="CollectionError";}};var z=class{dataDir;fileExtension;prettyPrint;cache=new Map;locks=new Map;constructor(t){this.dataDir=x.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.ensureDirectory();}ensureDirectory(){try{d.existsSync(this.dataDir)||d.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t){return x.join(this.dataDir,`${t}${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async read(t){if(this.cache.has(t))return this.cache.get(t);let e=this.getFilePath(t);try{if(!d.existsSync(e))return null;let i=await d.promises.readFile(e,"utf-8"),s=JSON.parse(i);return this.cache.set(t,s),s}catch(i){throw new f(`Failed to read collection "${t}"`,i)}}async write(t,e){let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`,n=await this.acquireLock(t);try{e.updatedAt=new Date().toISOString();let r=this.prettyPrint?JSON.stringify(e,null,2):JSON.stringify(e);await d.promises.writeFile(s,r,"utf-8"),await d.promises.rename(s,i),this.cache.set(t,e);}catch(r){try{d.existsSync(s)&&await d.promises.unlink(s);}catch{}throw new f(`Failed to write collection "${t}"`,r)}finally{n();}}async exists(t){let e=this.getFilePath(t);return d.existsSync(e)}async delete(t){let e=this.getFilePath(t),i=await this.acquireLock(t);try{d.existsSync(e)&&await d.promises.unlink(e),this.cache.delete(t);}catch(s){throw new f(`Failed to delete collection "${t}"`,s)}finally{i();}}async list(){try{return (await d.promises.readdir(this.dataDir)).filter(e=>e.endsWith(this.fileExtension)).map(e=>e.slice(0,-this.fileExtension.length))}catch(t){throw new f("Failed to list collections",t)}}clearCache(t){t?this.cache.delete(t):this.cache.clear();}getDataDir(){return this.dataDir}};function v(c){return new ObjectId().toHexString()}function U(c){return typeof c!="string"||c.length===0||c.length>64?false:c.length===24?ObjectId.isValid(c):true}function h(c){if(c===null||typeof c!="object")return c;if(c instanceof Date)return new Date(c.getTime());if(c instanceof RegExp)return new RegExp(c.source,c.flags);if(Array.isArray(c))return c.map(e=>h(e));let t={};for(let e in c)Object.prototype.hasOwnProperty.call(c,e)&&(t[e]=h(c[e]));return t}function V(c,t){let e=t.split("."),i=c;for(let s of e){if(i==null||typeof i!="object")return;i=i[s];}return i}function k(c,t,e){let i=t.split("."),s=c;for(let n=0;n<i.length-1;n++){let r=i[n];(!(r in s)||typeof s[r]!="object"||s[r]===null)&&(s[r]={}),s=s[r];}s[i[i.length-1]]=e;}function b(c,t){let e=t.split("."),i=c;for(let n=0;n<e.length-1;n++){let r=e[n];if(!(r in i)||typeof i[r]!="object"||i[r]===null)return false;i=i[r];}let s=e[e.length-1];return s in i?(delete i[s],true):false}function H(c){return typeof c=="object"&&c!==null&&!Array.isArray(c)&&!(c instanceof Date)&&!(c instanceof RegExp)}function O(c,t){if(!t||Object.keys(t).length===0)return c;let e=Object.entries(t).filter(([a])=>a!=="_id"),i=t._id,s=e.some(([,a])=>a===1||a===true),n=e.some(([,a])=>a===0||a===false);if(s&&n)throw new Error("Cannot mix inclusion and exclusion in projection");let r=s,o={};if(r){i!==0&&i!==false&&"_id"in c&&(o._id=c._id);for(let[l,u]of e)(u===1||u===true)&&l in c&&(o[l]=c[l]);}else {let a=new Set(e.filter(([,u])=>u===0||u===false).map(([u])=>u));(i===0||i===false)&&a.add("_id");for(let u of Object.keys(c))a.has(u)||(o[u]=c[u]);}return o}var D=class{filter(t,e){return !e||Object.keys(e).length===0?t:t.filter(i=>this.matches(i,e))}matches(t,e){if("$and"in e&&e.$and)return e.$and.every(i=>this.matches(t,i));if("$or"in e&&e.$or)return e.$or.some(i=>this.matches(t,i));if("$not"in e&&e.$not)return !this.matches(t,e.$not);for(let[i,s]of Object.entries(e)){if(i.startsWith("$"))continue;let n=V(t,i);if(!this.matchesCondition(n,s))return false}return true}matchesCondition(t,e){if(!H(e)||!this.hasOperators(e))return this.isEqual(t,e);let i=e;if("$eq"in i&&!this.isEqual(t,i.$eq)||"$ne"in i&&this.isEqual(t,i.$ne)||"$gt"in i&&!this.compareValues(t,i.$gt,">")||"$gte"in i&&!this.compareValues(t,i.$gte,">=")||"$lt"in i&&!this.compareValues(t,i.$lt,"<")||"$lte"in i&&!this.compareValues(t,i.$lte,"<=")||"$in"in i&&Array.isArray(i.$in)&&!i.$in.some(s=>this.isEqual(t,s))||"$nin"in i&&Array.isArray(i.$nin)&&i.$nin.some(s=>this.isEqual(t,s)))return false;if("$exists"in i){let s=t!=null;if(i.$exists!==s)return false}if("$regex"in i&&(typeof t!="string"||!(i.$regex instanceof RegExp?i.$regex:new RegExp(i.$regex)).test(t))||"$startsWith"in i&&(typeof t!="string"||typeof i.$startsWith!="string"||!t.startsWith(i.$startsWith))||"$endsWith"in i&&(typeof t!="string"||typeof i.$endsWith!="string"||!t.endsWith(i.$endsWith))||"$contains"in i&&(!Array.isArray(t)||!t.some(s=>this.isEqual(s,i.$contains)))||"$all"in i&&Array.isArray(i.$all)&&(!Array.isArray(t)||!i.$all.every(s=>t.some(n=>this.isEqual(n,s)))))return false;if("$elemMatch"in i&&i.$elemMatch){if(!Array.isArray(t))return false;let s=i.$elemMatch;if(!t.some(r=>typeof r!="object"||r===null?false:Object.entries(s).every(([o,a])=>{let l=r[o];return this.matchesCondition(l,a)})))return false}if("$size"in i&&typeof i.$size=="number"&&(!Array.isArray(t)||t.length!==i.$size))return false;if("$type"in i&&i.$type){let s=i.$type,n;if(t===null?n="null":t===void 0?n="undefined":Array.isArray(t)?n="array":n=typeof t,n!==s)return false}if("$mod"in i&&Array.isArray(i.$mod)&&i.$mod.length===2){if(typeof t!="number")return false;let[s,n]=i.$mod;if(t%s!==n)return false}return true}hasOperators(t){return Object.keys(t).some(e=>e.startsWith("$"))}isEqual(t,e){if(t===e)return true;if(t===null||e===null||t===void 0||e===void 0)return t===e;if(typeof t!=typeof e)return false;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?false:t.every((i,s)=>this.isEqual(i,e[s]));if(typeof t=="object"&&typeof e=="object"){let i=Object.keys(t),s=Object.keys(e);return i.length!==s.length?false:i.every(n=>this.isEqual(t[n],e[n]))}return false}compareValues(t,e,i){if(typeof t=="number"&&typeof e=="number")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(typeof t=="string"&&typeof e=="string")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(t instanceof Date&&e instanceof Date)switch(i){case ">":return t.getTime()>e.getTime();case ">=":return t.getTime()>=e.getTime();case "<":return t.getTime()<e.getTime();case "<=":return t.getTime()<=e.getTime()}return false}};var $=class{name;storage;queryEngine;autoSave;saveDebounce;idGenerator;schema;saveTimeout=null;pendingSave=null;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new D,this.autoSave=i.autoSave??true,this.saveDebounce=i.saveDebounce??0,this.idGenerator=i.idGenerator??v,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new T(this.name,e.error.issues);return e.data}async getData(){let t=await this.storage.read(this.name);if(!t){let e={name:this.name,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return await this.storage.write(this.name,e),e}return t}async save(t){if(this.autoSave){if(this.saveDebounce>0)return this.saveTimeout&&clearTimeout(this.saveTimeout),new Promise(e=>{this.saveTimeout=setTimeout(async()=>{await this.storage.write(this.name,t),this.saveTimeout=null,e();},this.saveDebounce);});await this.storage.write(this.name,t);}}async flush(){this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.pendingSave&&await this.pendingSave;let t=await this.getData();await this.storage.write(this.name,t);}async insert(t){let e=await this.getData(),i=t._id||this.idGenerator();if(e.documents.some(r=>r._id===i))throw new w(this.name,i);let s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertFast(t){let e=await this.getData(),i=t._id||this.idGenerator(),s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertMany(t){if(t.length===0)return [];let e=await this.getData(),i=[],s=new Set(e.documents.map(n=>n._id));for(let n of t){let r=n._id||this.idGenerator();if(s.has(r))throw new w(this.name,r);s.add(r);let o={...h(n),_id:r},a=this.validate(o);e.documents.push(a),i.push(h(a));}return await this.save(e),i}async find(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>O(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){return this.findOne({_id:t})}async count(t){let e=await this.getData();return this.queryEngine.filter(e.documents,t).length}async update(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e);return await this.save(i),s.length}async updateOne(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.save(i),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.getData(),i=e.documents.length;e.documents=e.documents.filter(n=>!this.queryEngine.matches(n,t));let s=i-e.documents.length;return s>0&&await this.save(e),s}async deleteOne(t){let e=await this.getData(),i=e.documents.findIndex(n=>this.queryEngine.matches(n,t));if(i===-1)return null;let[s]=e.documents.splice(i,1);return await this.save(e),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){let t=await this.getData();t.documents=[],await this.save(t);}async drop(){await this.storage.delete(this.name);}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&k(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&b(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var A=class{batchSize;flushInterval;coalesceWrites;batchProcessor;queue=new Map;flushTimer=null;pendingFlush=null;totalQueued=0;isShuttingDown=false;constructor(t,e={}){this.batchSize=e.batchSize??1e3,this.flushInterval=e.flushInterval??100,this.coalesceWrites=e.coalesceWrites??true,this.batchProcessor=t;}async enqueue(t){if(this.isShuttingDown)throw new Error("WriteQueue is shutting down, no new writes accepted");return new Promise((e,i)=>{let s={operation:t,resolve:e,reject:i,timestamp:Date.now()},n=t.collectionName,r=this.queue.get(n);r||(r=[],this.queue.set(n,r)),!(this.coalesceWrites&&this.tryCoalesce(n,s))&&(r.push(s),this.totalQueued++,this.scheduleFlush(),this.totalQueued>=this.batchSize&&this.flush().catch(i));})}tryCoalesce(t,e){let i=this.queue.get(t);if(!i||i.length===0)return false;let s=e.operation;if(s.type==="update")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;if(r.type==="update"&&r.documentId===s.documentId){r.changes={...r.changes,...s.changes};let o=i[n].resolve;return i[n].resolve=()=>{o(),e.resolve();},true}}if(s.type==="delete")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;(r.type==="insert"&&r.document._id===s.documentId||r.type==="update"&&r.documentId===s.documentId)&&(i.splice(n,1),this.totalQueued--);}if(s.type==="clear"||s.type==="fullWrite"){for(let n of i)n.resolve();i.length=0,this.totalQueued-=i.length;}return false}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(t=>{console.error("WriteQueue flush error:",t);});},this.flushInterval));}async flush(){if(this.pendingFlush)return this.pendingFlush;if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.totalQueued===0)return;let t=this.queue;this.queue=new Map,this.totalQueued=0;let e=new Map;for(let[i,s]of t)e.set(i,s.map(n=>n.operation));this.pendingFlush=this.processBatch(t,e),await this.pendingFlush,this.pendingFlush=null;}async processBatch(t,e){try{await this.batchProcessor(e);for(let i of t.values())for(let s of i)s.resolve();}catch(i){for(let s of t.values())for(let n of s)n.reject(i);}}async shutdown(){this.isShuttingDown=true,await this.flush();}pending(){return this.totalQueued}isEmpty(){return this.totalQueued===0}isClosing(){return this.isShuttingDown}};var E=class{dataDir;partitionCount;prettyPrint;fileExtension;cache=new Map;locks=new Map;constructor(t,e={}){this.dataDir=x.resolve(t),this.partitionCount=e.partitionCount??16,this.prettyPrint=e.prettyPrint??true,this.fileExtension=e.fileExtension??".json",this.ensureDirectory();}ensureDirectory(){try{d.existsSync(this.dataDir)||d.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getPartitionIndex(t){let e=0;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=(e<<5)-e+s,e=e&e;}return Math.abs(e)%this.partitionCount}getPartitionFileName(t,e){return `${t}_p${e.toString().padStart(3,"0")}${this.fileExtension}`}getPartitionFilePath(t,e){return x.join(this.dataDir,this.getPartitionFileName(t,e))}getCacheKey(t,e){return `${t}:${e}`}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async readPartition(t,e){let i=this.getCacheKey(t,e);if(this.cache.has(i))return this.cache.get(i);let s=this.getPartitionFilePath(t,e);try{if(!d.existsSync(s))return null;let n=await d.promises.readFile(s,"utf-8"),r=JSON.parse(n);return this.cache.set(i,r),r}catch(n){throw new f(`Failed to read partition ${e} for collection "${t}"`,n)}}async writePartition(t,e,i){let s=this.getPartitionFilePath(t,e),n=`${s}.tmp.${Date.now()}`,r=this.getCacheKey(t,e),o=await this.acquireLock(r);try{i.updatedAt=new Date().toISOString();let a=this.prettyPrint?JSON.stringify(i,null,2):JSON.stringify(i);await d.promises.writeFile(n,a,"utf-8"),await d.promises.rename(n,s),this.cache.set(r,i);}catch(a){try{d.existsSync(n)&&await d.promises.unlink(n);}catch{}throw new f(`Failed to write partition ${e} for collection "${t}"`,a)}finally{o();}}async readAllPartitions(t){let e=new Map,i=[];for(let s=0;s<this.partitionCount;s++)i.push(this.readPartition(t,s).then(n=>{n&&e.set(s,n);}));return await Promise.all(i),e}async writePartitions(t,e){let i=[];for(let[s,n]of e)i.push(this.writePartition(t,s,n));await Promise.all(i);}async initializePartitions(t){let e=[];for(let i=0;i<this.partitionCount;i++)if(!d.existsSync(this.getPartitionFilePath(t,i))){let n={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};e.push(this.writePartition(t,i,n));}await Promise.all(e);}async getPartitionInfo(t){let e=await this.readAllPartitions(t),i=[];for(let s=0;s<this.partitionCount;s++){let n=e.get(s);i.push({name:this.getPartitionFileName(t,s),partitionIndex:s,documentCount:n?.documents.length??0});}return i}async getAllDocuments(t){let e=await this.readAllPartitions(t),i=[];for(let s of e.values())i.push(...s.documents);return i}async findById(t,e){let i=this.getPartitionIndex(e),s=await this.readPartition(t,i);return s?s.documents.find(n=>n._id===e)??null:null}async deleteCollection(t){let e=[];for(let i=0;i<this.partitionCount;i++){let s=this.getPartitionFilePath(t,i),n=this.getCacheKey(t,i);e.push((async()=>{let r=await this.acquireLock(n);try{d.existsSync(s)&&await d.promises.unlink(s),this.cache.delete(n);}finally{r();}})());}await Promise.all(e);}clearCache(t){if(t)for(let e=0;e<this.partitionCount;e++)this.cache.delete(this.getCacheKey(t,e));else this.cache.clear();}getPartitionCount(){return this.partitionCount}async listCollections(){try{let t=await d.promises.readdir(this.dataDir),e=new Set,i=new RegExp(`^(.+)_p\\d{3}\\${this.fileExtension}$`);for(let s of t){let n=s.match(i);n&&e.add(n[1]);}return Array.from(e)}catch(t){throw new f("Failed to list partitioned collections",t)}}};var I=class{maxConcurrent;maxQueueSize;queue=[];activeCount=0;completedCount=0;failedCount=0;isShuttingDown=false;constructor(t={}){this.maxConcurrent=t.maxConcurrent??4,this.maxQueueSize=t.maxQueueSize??1e4;}async submit(t,e=0){if(this.isShuttingDown)throw new Error("WorkerPool is shutting down, no new tasks accepted");if(this.queue.length>=this.maxQueueSize)throw new Error("WorkerPool queue is full, task rejected (backpressure)");return new Promise((i,s)=>{let n={task:t,resolve:i,reject:s,priority:e},r=false;for(let o=0;o<this.queue.length;o++)if(e>this.queue[o].priority){this.queue.splice(o,0,n),r=true;break}r||this.queue.push(n),this.processNext();})}async submitAll(t,e=0){let i=t.map(s=>this.submit(s,e));return Promise.all(i)}async*submitStream(t,e=0){let i=t.map(s=>this.submit(s,e));for(let s of i)yield await s;}processNext(){if(this.activeCount>=this.maxConcurrent||this.queue.length===0)return;let t=this.queue.shift();t&&(this.activeCount++,t.task().then(e=>{this.completedCount++,t.resolve(e);}).catch(e=>{this.failedCount++,t.reject(e);}).finally(()=>{this.activeCount--,this.processNext();}));}async drain(){return new Promise(t=>{let e=()=>{this.activeCount===0&&this.queue.length===0?t():setImmediate(e);};e();})}async shutdown(){this.isShuttingDown=true,await this.drain();}getStats(){return {activeWorkers:this.activeCount,queuedTasks:this.queue.length,completedTasks:this.completedCount,failedTasks:this.failedCount}}isIdle(){return this.activeCount===0&&this.queue.length===0}isClosing(){return this.isShuttingDown}queueSize(){return this.queue.length}activeWorkers(){return this.activeCount}};async function W(c,t,e){let i=[],s=0;async function n(){let o=s++;o>=c.length||(i[o]=await e(c[o],o),await n());}let r=Array(Math.min(t,c.length)).fill(null).map(()=>n());return await Promise.all(r),i}var K={partitions:16,batchSize:1e3,flushInterval:100,maxConcurrentIO:4,coalesceWrites:true},_=class{partitionManager;writeQueue;workerPool;options;constructor(t){let e=t.highConcurrency;this.options={...K,...e},this.partitionManager=new E(t.dataDir,{partitionCount:this.options.partitions,prettyPrint:t.prettyPrint??true,fileExtension:t.fileExtension??".json"}),this.workerPool=new I({maxConcurrent:this.options.maxConcurrentIO});let i=this.processBatch.bind(this);this.writeQueue=new A(i,{batchSize:this.options.batchSize,flushInterval:this.options.flushInterval,coalesceWrites:this.options.coalesceWrites});}async processBatch(t){let e=Array.from(t.entries());await W(e,this.options.maxConcurrentIO,async([i,s])=>{await this.processCollectionOperations(i,s);});}async processCollectionOperations(t,e){let i=new Map,s=n=>{let r=i.get(n);return r||(r=[],i.set(n,r)),r};for(let n of e)if(n.type==="fullWrite"||n.type==="clear")for(let r=0;r<this.partitionManager.getPartitionCount();r++)s(r).push(n);else if(n.type==="insert"){let r=this.partitionManager.getPartitionIndex(n.document._id);s(r).push(n);}else if(n.type==="update"||n.type==="delete"){let r=this.partitionManager.getPartitionIndex(n.documentId);s(r).push(n);}else if(n.type==="bulkInsert")for(let r of n.documents){let o=this.partitionManager.getPartitionIndex(r._id);s(o).push({type:"insert",collectionName:t,document:r});}else if(n.type==="bulkUpdate"||n.type==="bulkDelete")for(let r of n.documentIds){let o=this.partitionManager.getPartitionIndex(r);n.type==="bulkUpdate"?s(o).push({type:"update",collectionName:t,documentId:r,changes:n.changes}):s(o).push({type:"delete",collectionName:t,documentId:r});}await W(Array.from(i.entries()),this.options.maxConcurrentIO,async([n,r])=>{await this.processPartitionOperations(t,n,r);});}async processPartitionOperations(t,e,i){let s=await this.partitionManager.readPartition(t,e);s||(s={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});for(let n of i)switch(n.type){case "insert":s.documents.push(n.document);break;case "update":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&Object.assign(s.documents[r],n.changes);break}case "delete":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&s.documents.splice(r,1);break}case "clear":s.documents=[];break;case "fullWrite":{let r=n.data.documents.filter(o=>this.partitionManager.getPartitionIndex(o._id)===e);s.documents=r;break}}await this.partitionManager.writePartition(t,e,s);}async insert(t,e){await this.writeQueue.enqueue({type:"insert",collectionName:t,document:e});}async insertMany(t,e){await this.writeQueue.enqueue({type:"bulkInsert",collectionName:t,documents:e});}async update(t,e,i){await this.writeQueue.enqueue({type:"update",collectionName:t,documentId:e,changes:i});}async delete(t,e){await this.writeQueue.enqueue({type:"delete",collectionName:t,documentId:e});}async clear(t){await this.writeQueue.enqueue({type:"clear",collectionName:t});}async findById(t,e){return await this.writeQueue.flush(),this.partitionManager.findById(t,e)}async readAll(t){return await this.writeQueue.flush(),this.partitionManager.getAllDocuments(t)}async exists(t){return (await this.partitionManager.listCollections()).includes(t)}async initializeCollection(t){await this.partitionManager.initializePartitions(t);}async deleteCollection(t){await this.writeQueue.flush(),await this.partitionManager.deleteCollection(t);}async listCollections(){return this.partitionManager.listCollections()}async flush(){await this.writeQueue.flush();}async shutdown(){await this.writeQueue.shutdown(),await this.workerPool.shutdown();}pendingWrites(){return this.writeQueue.pending()}getStats(){return {pendingWrites:this.writeQueue.pending(),workerPool:this.workerPool.getStats(),partitions:this.options.partitions}}clearCache(t){this.partitionManager.clearCache(t);}};var Q=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new D,this.idGenerator=i.idGenerator??v,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new T(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(await this.storage.findById(this.name,e))throw new w(this.name,e);let s={...h(t),_id:e},n=this.validate(s);return await this.storage.insert(this.name,n),n}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insert(this.name,s),s}async insertMany(t){if(t.length===0)return [];let e=[],i=[];for(let s of t){let n=s._id||this.idGenerator(),r={...h(s),_id:n},o=this.validate(r);i.push(o),e.push(h(o));}return await this.storage.insertMany(this.name,i),e}async find(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.findById(this.name,t);return e?h(e):null}async count(t){let e=await this.storage.readAll(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s){let r=this.getUpdateChanges(n,e);await this.storage.update(this.name,n._id,r);}return s.length}async updateOne(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0],r=this.getUpdateChanges(n,e);return await this.storage.update(this.name,n._id,r),Object.assign(n,r),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;for(let s of i)await this.storage.delete(this.name,s._id);return i.length}async deleteOne(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.delete(this.name,s._id),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){await this.storage.clear(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}getUpdateChanges(t,e){if(!Object.keys(e).some(r=>r.startsWith("$")))return e;let s=e,n={};if(s.$set)for(let[r,o]of Object.entries(s.$set))r!=="_id"&&(n[r]=o);if(s.$inc)for(let[r,o]of Object.entries(s.$inc)){let a=t[r];typeof a=="number"&&typeof o=="number"&&(n[r]=a+o);}if(s.$push)for(let[r,o]of Object.entries(s.$push)){let a=t[r];Array.isArray(a)&&(n[r]=[...a,o]);}if(s.$pull)for(let[r,o]of Object.entries(s.$pull)){let a=t[r];Array.isArray(a)&&(n[r]=a.filter(l=>JSON.stringify(l)!==JSON.stringify(o)));}if(s.$addToSet)for(let[r,o]of Object.entries(s.$addToSet)){let a=t[r];Array.isArray(a)&&(a.some(u=>JSON.stringify(u)===JSON.stringify(o))?n[r]=a:n[r]=[...a,o]);}return n}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var S=class{capacity;cache;constructor(t){this.capacity=t,this.cache=new Map;}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}forEach(t){this.cache.forEach(t);}};var L=class{dataDir;fileExtension;prettyPrint;cacheSize;chunkSize;documentCache;collections;locks;constructor(t){this.dataDir=x.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.cacheSize=t.lazyLoading?.cacheSize??1e3,this.chunkSize=t.lazyLoading?.chunkSize??1e4,this.documentCache=new Map,this.collections=new Map,this.locks=new Map,this.ensureDirectory();}ensureDirectory(){try{d.existsSync(this.dataDir)||d.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t,e){return e!==void 0&&this.chunkSize>0?x.join(this.dataDir,`${t}_chunk${e}${this.fileExtension}`):x.join(this.dataDir,`${t}${this.fileExtension}`)}getIndexFilePath(t){return x.join(this.dataDir,`${t}.index${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async initCollection(t){if(this.collections.has(t))return;let e=this.getFilePath(t),i=this.getIndexFilePath(t);if(d.existsSync(i))try{let s=await d.promises.readFile(i,"utf-8"),n=JSON.parse(s),r={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:new Map(n.ids.map((o,a)=>[o,{id:o,offset:a}])),count:n.ids.length,dirty:!1};this.collections.set(t,r),this.documentCache.set(t,new S(this.cacheSize));return}catch{}if(d.existsSync(e))try{let s=await d.promises.readFile(e,"utf-8"),n=JSON.parse(s),r=new Map;n.documents.forEach((u,F)=>{r.set(u._id,{id:u._id,offset:F});});let o={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:r,count:n.documents.length,dirty:!1};this.collections.set(t,o),this.documentCache.set(t,new S(this.cacheSize));let a=this.documentCache.get(t),l=Math.min(n.documents.length,this.cacheSize);for(let u=0;u<l;u++)a.set(n.documents[u]._id,n.documents[u]);await this.saveIndex(t);}catch(s){throw new f(`Failed to initialize collection "${t}"`,s)}else {let s={name:t,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),index:new Map,count:0,dirty:false};this.collections.set(t,s),this.documentCache.set(t,new S(this.cacheSize));}}async saveIndex(t){let e=this.collections.get(t);if(!e)return;let i=this.getIndexFilePath(t),s={name:t,createdAt:e.createdAt,updatedAt:e.updatedAt,ids:Array.from(e.index.keys())},n=this.prettyPrint?JSON.stringify(s,null,2):JSON.stringify(s);await d.promises.writeFile(i,n,"utf-8");}getCount(t){return this.collections.get(t)?.count??0}hasDocument(t,e){return this.collections.get(t)?.index.has(e)??false}getDocumentIds(t){let e=this.collections.get(t);return e?Array.from(e.index.keys()):[]}async getDocument(t,e){await this.initCollection(t);let i=this.collections.get(t);if(!i||!i.index.has(e))return null;let s=this.documentCache.get(t),n=s.get(e);if(n)return n;let r=await this.loadDocumentFromDisk(t,e);return r&&s.set(e,r),r}async loadDocumentFromDisk(t,e){let i=this.getFilePath(t);try{let s=await d.promises.readFile(i,"utf-8");return JSON.parse(s).documents.find(r=>r._id===e)??null}catch{return null}}async getDocuments(t,e){await this.initCollection(t);let i=this.documentCache.get(t),s=[],n=[];for(let r of e){let o=i.get(r);o?s.push(o):n.push(r);}if(n.length>0){let r=await this.loadDocumentsFromDisk(t,n);for(let o of r)i.set(o._id,o),s.push(o);}return s}async loadDocumentsFromDisk(t,e){let i=this.getFilePath(t),s=new Set(e);try{let n=await d.promises.readFile(i,"utf-8");return JSON.parse(n).documents.filter(o=>s.has(o._id))}catch{return []}}async getAllDocuments(t){await this.initCollection(t);let e=this.getFilePath(t);try{if(!d.existsSync(e))return [];let i=await d.promises.readFile(e,"utf-8"),s=JSON.parse(i),n=this.documentCache.get(t);for(let r of s.documents)n.set(r._id,r);return s.documents}catch{return []}}async insertDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);s.index.set(e._id,{id:e._id,offset:s.count}),s.count++,s.updatedAt=new Date().toISOString(),s.dirty=!0,n.set(e._id,e),await this.persistCollection(t);}finally{i();}}async insertDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);for(let r of e)s.index.set(r._id,{id:r._id,offset:s.count}),s.count++,n.set(r._id,r);s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async updateDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);if(!s.index.has(e._id))return;n.set(e._id,e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);if(!s.index.has(e))return;s.index.delete(e),s.count--,n.delete(e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let s=this.collections.get(t),n=this.documentCache.get(t);for(let r of e)s.index.has(r)&&(s.index.delete(r),s.count--,n.delete(r));s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async clearCollection(t){await this.initCollection(t);let e=await this.acquireLock(t);try{let i=this.collections.get(t),s=this.documentCache.get(t);i.index.clear(),i.count=0,s.clear(),i.updatedAt=new Date().toISOString(),i.dirty=!0,await this.persistCollection(t);}finally{e();}}async persistCollection(t){let e=this.collections.get(t);if(!e)return;let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`;try{let n=await this.buildDocumentArray(t),r={name:t,documents:n,createdAt:e.createdAt,updatedAt:e.updatedAt},o=this.prettyPrint?JSON.stringify(r,null,2):JSON.stringify(r);await d.promises.writeFile(s,o,"utf-8"),await d.promises.rename(s,i),await this.saveIndex(t),e.dirty=!1;}catch(n){try{d.existsSync(s)&&await d.promises.unlink(s);}catch{}throw new f(`Failed to persist collection "${t}"`,n)}}async buildDocumentArray(t){let e=this.collections.get(t);if(!e||e.count===0)return [];let i=this.getFilePath(t),s=[];try{if(d.existsSync(i)){let a=await d.promises.readFile(i,"utf-8");s=JSON.parse(a).documents;}}catch{}let n=new Map;for(let a of s)n.set(a._id,a);this.documentCache.get(t).forEach((a,l)=>{n.set(l,a);});let o=[];for(let a of e.index.keys()){let l=n.get(a);l&&o.push(l);}return o}async deleteCollection(t){let e=await this.acquireLock(t);try{this.collections.delete(t),this.documentCache.delete(t);let i=this.getFilePath(t),s=this.getIndexFilePath(t);d.existsSync(i)&&await d.promises.unlink(i),d.existsSync(s)&&await d.promises.unlink(s);}finally{e();}}async exists(t){if(this.collections.has(t))return true;let e=this.getFilePath(t);return d.existsSync(e)}async list(){try{let t=await d.promises.readdir(this.dataDir),e=new Set;for(let i of t)i.includes(".index")||i.includes("_chunk")||i.endsWith(this.fileExtension)&&e.add(i.slice(0,-this.fileExtension.length));return Array.from(e)}catch{return []}}getStats(){let t=0;for(let e of this.documentCache.values())t+=e.size;return {collections:this.collections.size,cachedDocuments:t,cacheSize:this.cacheSize}}clearCache(t){if(t)this.documentCache.get(t)?.clear();else for(let e of this.documentCache.values())e.clear();}async flush(){for(let[t,e]of this.collections.entries())e.dirty&&await this.persistCollection(t);}getDataDir(){return this.dataDir}};var j=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new D,this.idGenerator=i.idGenerator??v,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new T(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(this.storage.hasDocument(this.name,e))throw new w(this.name,e);let i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertMany(t){if(t.length===0)return [];let e=new Set(this.storage.getDocumentIds(this.name)),i=[];for(let s of t){let n=s._id||this.idGenerator();if(e.has(n))throw new w(this.name,n);e.add(n);let r={...h(s),_id:n},o=this.validate(r);i.push(o);}return await this.storage.insertDocuments(this.name,i),i.map(s=>h(s))}async find(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>O(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.getDocument(this.name,t);return e?h(e):null}async count(t){if(!t||Object.keys(t).length===0)return this.storage.getCount(this.name);let e=await this.storage.getAllDocuments(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n);return s.length}async updateOne(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n),h(n)}async updateById(t,e){let i=await this.storage.getDocument(this.name,t);return i?(this.applyUpdate(i,e),await this.storage.updateDocument(this.name,i),h(i)):null}async delete(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;let s=i.map(n=>n._id);return await this.storage.deleteDocuments(this.name,s),i.length}async deleteOne(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.deleteDocument(this.name,s._id),h(s)}async deleteById(t){let e=await this.storage.getDocument(this.name,t);return e?(await this.storage.deleteDocument(this.name,t),h(e)):null}async getAll(){return this.find()}async clear(){await this.storage.clearCollection(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&k(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&b(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var G={autoSave:true,saveDebounce:0,prettyPrint:true,fileExtension:".json"},J=class{options;storage;hcStorage;lazyStorage;collections=new Map;isHighConcurrency;isLazyLoading;connected=false;constructor(t){if(this.options={...G,...t},this.isHighConcurrency=t.highConcurrency?.enabled??false,this.isLazyLoading=t.lazyLoading?.enabled??false,this.isHighConcurrency&&this.isLazyLoading)throw new Error("Cannot enable both highConcurrency and lazyLoading modes simultaneously");this.isHighConcurrency?(this.storage=null,this.hcStorage=new _(this.options),this.lazyStorage=null):this.isLazyLoading?(this.storage=null,this.hcStorage=null,this.lazyStorage=new L(this.options)):(this.storage=new z(this.options),this.hcStorage=null,this.lazyStorage=null);}getStorage(){if(this.storage===null)throw new Error("Storage is not available in high-concurrency or lazy loading mode");return this.storage}getHCStorage(){if(this.hcStorage===null)throw new Error("HighConcurrencyStorage is not available in standard or lazy loading mode");return this.hcStorage}getLazyStorage(){if(this.lazyStorage===null)throw new Error("LazyStorage is not available in standard or high-concurrency mode");return this.lazyStorage}async connect(){if(!this.connected){if(this.isHighConcurrency){let t=await this.getHCStorage().listCollections();for(let e of t)this.getOrCreateCollection(e);}else if(this.isLazyLoading){let t=await this.getLazyStorage().list();for(let e of t)this.getOrCreateCollection(e);}else {let t=await this.getStorage().list();for(let e of t)this.getOrCreateCollection(e);}this.connected=true;}}async close(){if(this.connected){for(let t of this.collections.values())await t.flush();this.isHighConcurrency&&this.hcStorage&&await this.hcStorage.shutdown(),this.collections.clear(),this.storage&&this.storage.clearCache(),this.hcStorage&&this.hcStorage.clearCache(),this.lazyStorage&&this.lazyStorage.clearCache(),this.connected=false;}}collection(t,e){if(!t||typeof t!="string")throw new C("Collection name must be a non-empty string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(t))throw new C("Collection name must start with a letter or underscore and contain only letters, numbers, underscores, and hyphens");return this.getOrCreateCollection(t,e)}getOrCreateCollection(t,e){if(this.collections.has(t))return this.collections.get(t);if(this.isHighConcurrency){let i=new Q(t,this.getHCStorage(),{schema:e?.schema});this.collections.set(t,i);}else if(this.isLazyLoading){let i=new j(t,this.getLazyStorage(),{schema:e?.schema});this.collections.set(t,i);}else {let i=new $(t,this.getStorage(),{autoSave:this.options.autoSave,saveDebounce:this.options.saveDebounce,schema:e?.schema});this.collections.set(t,i);}return this.collections.get(t)}async hasCollection(t){return this.isHighConcurrency?this.getHCStorage().exists(t):this.getStorage().exists(t)}async listCollections(){return this.isHighConcurrency?this.getHCStorage().listCollections():this.getStorage().list()}async dropCollection(t){let e=this.collections.get(t);e?(await e.drop(),this.collections.delete(t)):this.isHighConcurrency?await this.getHCStorage().deleteCollection(t):await this.getStorage().delete(t);}async drop(){if(this.isHighConcurrency){let t=this.getHCStorage(),e=await t.listCollections();for(let i of e)await t.deleteCollection(i);}else {let t=this.getStorage(),e=await t.list();for(let i of e)await t.delete(i);}this.collections.clear(),this.storage?.clearCache(),this.hcStorage?.clearCache();}getDataDir(){return this.isHighConcurrency?this.options.dataDir:this.getStorage().getDataDir()}isConnected(){return this.connected}isHighConcurrencyMode(){return this.isHighConcurrency}getStats(){return !this.isHighConcurrency||!this.hcStorage?null:this.hcStorage.getStats()}async flush(){for(let t of this.collections.values())await t.flush();}};export{$ as Collection,C as CollectionError,R as DocumentNotFoundError,w as DuplicateKeyError,Q as HighConcurrencyCollection,_ as HighConcurrencyStorage,J as JsonDB,P as JsonDBError,E as PartitionManager,f as StorageError,T as ValidationError,I as WorkerPool,A as WriteQueue,v as generateId,U as isValidId,W as parallelLimit};
1
+ import*as d from'fs';import*as x from'path';import {ObjectId}from'bson';var P=class extends Error{constructor(t){super(t),this.name="JsonDBError",Error.captureStackTrace?.(this,this.constructor);}},R=class extends P{constructor(t,e){super(e?`Document with id "${e}" not found in collection "${t}"`:`Document not found in collection "${t}"`),this.name="DocumentNotFoundError";}},w=class extends P{constructor(t,e){super(`Duplicate key error: document with id "${e}" already exists in collection "${t}"`),this.name="DuplicateKeyError";}},T=class extends P{collectionName;issues;field;value;constructor(t,e,i,s){let n=e.map(r=>`${r.path.join(".")}: ${r.message}`).join("; ");super(`Validation failed for collection "${t}": ${n}`),this.name="ValidationError",this.collectionName=t,this.issues=e,this.field=i,this.value=s;}},f=class extends P{cause;constructor(t,e){super(t),this.name="StorageError",this.cause=e;}},C=class extends P{constructor(t){super(t),this.name="CollectionError";}};var M=class{dataDir;fileExtension;prettyPrint;cache=new Map;locks=new Map;constructor(t){this.dataDir=x.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.ensureDirectory();}ensureDirectory(){try{d.existsSync(this.dataDir)||d.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t){return x.join(this.dataDir,`${t}${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async read(t){if(this.cache.has(t))return this.cache.get(t);let e=this.getFilePath(t);try{if(!d.existsSync(e))return null;let i=await d.promises.readFile(e,"utf-8"),s=JSON.parse(i);return this.cache.set(t,s),s}catch(i){throw new f(`Failed to read collection "${t}"`,i)}}async write(t,e){let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`,n=await this.acquireLock(t);try{e.updatedAt=new Date().toISOString();let r=this.prettyPrint?JSON.stringify(e,null,2):JSON.stringify(e);await d.promises.writeFile(s,r,"utf-8"),await d.promises.rename(s,i),this.cache.set(t,e);}catch(r){try{d.existsSync(s)&&await d.promises.unlink(s);}catch{}throw new f(`Failed to write collection "${t}"`,r)}finally{n();}}async exists(t){let e=this.getFilePath(t);return d.existsSync(e)}async delete(t){let e=this.getFilePath(t),i=await this.acquireLock(t);try{d.existsSync(e)&&await d.promises.unlink(e),this.cache.delete(t);}catch(s){throw new f(`Failed to delete collection "${t}"`,s)}finally{i();}}async list(){try{return (await d.promises.readdir(this.dataDir)).filter(e=>e.endsWith(this.fileExtension)).map(e=>e.slice(0,-this.fileExtension.length))}catch(t){throw new f("Failed to list collections",t)}}clearCache(t){t?this.cache.delete(t):this.cache.clear();}getDataDir(){return this.dataDir}};function v(c){return new ObjectId().toHexString()}function U(c){return typeof c!="string"||c.length===0||c.length>64?false:c.length===24?ObjectId.isValid(c):true}function h(c){if(c===null||typeof c!="object")return c;if(c instanceof Date)return new Date(c.getTime());if(c instanceof RegExp)return new RegExp(c.source,c.flags);if(Array.isArray(c))return c.map(e=>h(e));let t={};for(let e in c)Object.prototype.hasOwnProperty.call(c,e)&&(t[e]=h(c[e]));return t}function V(c,t){let e=t.split("."),i=c;for(let s of e){if(i==null||typeof i!="object")return;i=i[s];}return i}function k(c,t,e){let i=t.split("."),s=c;for(let n=0;n<i.length-1;n++){let r=i[n];(!(r in s)||typeof s[r]!="object"||s[r]===null)&&(s[r]={}),s=s[r];}s[i[i.length-1]]=e;}function b(c,t){let e=t.split("."),i=c;for(let n=0;n<e.length-1;n++){let r=e[n];if(!(r in i)||typeof i[r]!="object"||i[r]===null)return false;i=i[r];}let s=e[e.length-1];return s in i?(delete i[s],true):false}function J(c){return typeof c=="object"&&c!==null&&!Array.isArray(c)&&!(c instanceof Date)&&!(c instanceof RegExp)}function O(c,t){if(!t||Object.keys(t).length===0)return c;let e=Object.entries(t).filter(([a])=>a!=="_id"),i=t._id,s=e.some(([,a])=>a===1||a===true),n=e.some(([,a])=>a===0||a===false);if(s&&n)throw new Error("Cannot mix inclusion and exclusion in projection");let r=s,o={};if(r){i!==0&&i!==false&&"_id"in c&&(o._id=c._id);for(let[l,u]of e)(u===1||u===true)&&l in c&&(o[l]=c[l]);}else {let a=new Set(e.filter(([,u])=>u===0||u===false).map(([u])=>u));(i===0||i===false)&&a.add("_id");for(let u of Object.keys(c))a.has(u)||(o[u]=c[u]);}return o}var D=class{filter(t,e){return !e||Object.keys(e).length===0?t:t.filter(i=>this.matches(i,e))}matches(t,e){if("$and"in e&&e.$and)return e.$and.every(i=>this.matches(t,i));if("$or"in e&&e.$or)return e.$or.some(i=>this.matches(t,i));if("$not"in e&&e.$not)return !this.matches(t,e.$not);for(let[i,s]of Object.entries(e)){if(i.startsWith("$"))continue;let n=V(t,i);if(!this.matchesCondition(n,s))return false}return true}matchesCondition(t,e){if(!J(e)||!this.hasOperators(e))return this.isEqual(t,e);let i=e;if("$eq"in i&&!this.isEqual(t,i.$eq)||"$ne"in i&&this.isEqual(t,i.$ne)||"$gt"in i&&!this.compareValues(t,i.$gt,">")||"$gte"in i&&!this.compareValues(t,i.$gte,">=")||"$lt"in i&&!this.compareValues(t,i.$lt,"<")||"$lte"in i&&!this.compareValues(t,i.$lte,"<=")||"$in"in i&&Array.isArray(i.$in)&&!i.$in.some(s=>this.isEqual(t,s))||"$nin"in i&&Array.isArray(i.$nin)&&i.$nin.some(s=>this.isEqual(t,s)))return false;if("$exists"in i){let s=t!=null;if(i.$exists!==s)return false}if("$regex"in i&&(typeof t!="string"||!(i.$regex instanceof RegExp?i.$regex:new RegExp(i.$regex)).test(t))||"$startsWith"in i&&(typeof t!="string"||typeof i.$startsWith!="string"||!t.startsWith(i.$startsWith))||"$endsWith"in i&&(typeof t!="string"||typeof i.$endsWith!="string"||!t.endsWith(i.$endsWith))||"$contains"in i&&(!Array.isArray(t)||!t.some(s=>this.isEqual(s,i.$contains)))||"$all"in i&&Array.isArray(i.$all)&&(!Array.isArray(t)||!i.$all.every(s=>t.some(n=>this.isEqual(n,s)))))return false;if("$elemMatch"in i&&i.$elemMatch){if(!Array.isArray(t))return false;let s=i.$elemMatch;if(!t.some(r=>typeof r!="object"||r===null?false:Object.entries(s).every(([o,a])=>{let l=r[o];return this.matchesCondition(l,a)})))return false}if("$size"in i&&typeof i.$size=="number"&&(!Array.isArray(t)||t.length!==i.$size))return false;if("$type"in i&&i.$type){let s=i.$type,n;if(t===null?n="null":t===void 0?n="undefined":Array.isArray(t)?n="array":n=typeof t,n!==s)return false}if("$mod"in i&&Array.isArray(i.$mod)&&i.$mod.length===2){if(typeof t!="number")return false;let[s,n]=i.$mod;if(t%s!==n)return false}return true}hasOperators(t){return Object.keys(t).some(e=>e.startsWith("$"))}isEqual(t,e){if(t===e)return true;if(t===null||e===null||t===void 0||e===void 0)return t===e;if(typeof t!=typeof e)return false;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?false:t.every((i,s)=>this.isEqual(i,e[s]));if(typeof t=="object"&&typeof e=="object"){let i=Object.keys(t),s=Object.keys(e);return i.length!==s.length?false:i.every(n=>this.isEqual(t[n],e[n]))}return false}compareValues(t,e,i){if(typeof t=="number"&&typeof e=="number")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(typeof t=="string"&&typeof e=="string")switch(i){case ">":return t>e;case ">=":return t>=e;case "<":return t<e;case "<=":return t<=e}if(t instanceof Date&&e instanceof Date)switch(i){case ">":return t.getTime()>e.getTime();case ">=":return t.getTime()>=e.getTime();case "<":return t.getTime()<e.getTime();case "<=":return t.getTime()<=e.getTime()}return false}};var $=class{name;storage;queryEngine;autoSave;saveDebounce;idGenerator;schema;saveTimeout=null;pendingSave=null;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new D,this.autoSave=i.autoSave??true,this.saveDebounce=i.saveDebounce??0,this.idGenerator=i.idGenerator??v,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new T(this.name,e.error.issues);return e.data}async getData(){let t=await this.storage.read(this.name);if(!t){let e={name:this.name,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return await this.storage.write(this.name,e),e}return t}async save(t){if(this.autoSave){if(this.saveDebounce>0)return this.saveTimeout&&clearTimeout(this.saveTimeout),new Promise(e=>{this.saveTimeout=setTimeout(async()=>{await this.storage.write(this.name,t),this.saveTimeout=null,e();},this.saveDebounce);});await this.storage.write(this.name,t);}}async flush(){this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.pendingSave&&await this.pendingSave;let t=await this.getData();await this.storage.write(this.name,t);}async insert(t){let e=await this.getData(),i=t._id||this.idGenerator();if(e.documents.some(r=>r._id===i))throw new w(this.name,i);let s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertFast(t){let e=await this.getData(),i=t._id||this.idGenerator(),s={...h(t),_id:i},n=this.validate(s);return e.documents.push(n),await this.save(e),h(n)}async insertMany(t){if(t.length===0)return [];let e=await this.getData(),i=[],s=new Set(e.documents.map(n=>n._id));for(let n of t){let r=n._id||this.idGenerator();if(s.has(r))throw new w(this.name,r);s.add(r);let o={...h(n),_id:r},a=this.validate(o);e.documents.push(a),i.push(h(a));}return await this.save(e),i}async find(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>O(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){return this.findOne({_id:t})}async count(t){let e=await this.getData();return this.queryEngine.filter(e.documents,t).length}async update(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e);return await this.save(i),s.length}async updateOne(t,e){let i=await this.getData(),s=this.queryEngine.filter(i.documents,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.save(i),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.getData(),i=e.documents.length;e.documents=e.documents.filter(n=>!this.queryEngine.matches(n,t));let s=i-e.documents.length;return s>0&&await this.save(e),s}async deleteOne(t){let e=await this.getData(),i=e.documents.findIndex(n=>this.queryEngine.matches(n,t));if(i===-1)return null;let[s]=e.documents.splice(i,1);return await this.save(e),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){let t=await this.getData();t.documents=[],await this.save(t);}async drop(){await this.storage.delete(this.name);}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&k(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&b(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var A=class{batchSize;flushInterval;coalesceWrites;batchProcessor;queue=new Map;flushTimer=null;pendingFlush=null;totalQueued=0;isShuttingDown=false;constructor(t,e={}){this.batchSize=e.batchSize??1e3,this.flushInterval=e.flushInterval??100,this.coalesceWrites=e.coalesceWrites??true,this.batchProcessor=t;}async enqueue(t){if(this.isShuttingDown)throw new Error("WriteQueue is shutting down, no new writes accepted");return new Promise((e,i)=>{let s={operation:t,resolve:e,reject:i,timestamp:Date.now()},n=t.collectionName,r=this.queue.get(n);r||(r=[],this.queue.set(n,r)),!(this.coalesceWrites&&this.tryCoalesce(n,s))&&(r.push(s),this.totalQueued++,this.scheduleFlush(),this.totalQueued>=this.batchSize&&this.flush().catch(i));})}tryCoalesce(t,e){let i=this.queue.get(t);if(!i||i.length===0)return false;let s=e.operation;if(s.type==="update")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;if(r.type==="update"&&r.documentId===s.documentId){r.changes={...r.changes,...s.changes};let o=i[n].resolve;return i[n].resolve=()=>{o(),e.resolve();},true}}if(s.type==="delete")for(let n=i.length-1;n>=0;n--){let r=i[n].operation;(r.type==="insert"&&r.document._id===s.documentId||r.type==="update"&&r.documentId===s.documentId)&&(i.splice(n,1),this.totalQueued--);}if(s.type==="clear"||s.type==="fullWrite"){for(let n of i)n.resolve();i.length=0,this.totalQueued-=i.length;}return false}scheduleFlush(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(t=>{console.error("WriteQueue flush error:",t);});},this.flushInterval));}async flush(){if(this.pendingFlush)return this.pendingFlush;if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.totalQueued===0)return;let t=this.queue;this.queue=new Map,this.totalQueued=0;let e=new Map;for(let[i,s]of t)e.set(i,s.map(n=>n.operation));this.pendingFlush=this.processBatch(t,e),await this.pendingFlush,this.pendingFlush=null;}async processBatch(t,e){try{await this.batchProcessor(e);for(let i of t.values())for(let s of i)s.resolve();}catch(i){for(let s of t.values())for(let n of s)n.reject(i);}}async shutdown(){this.isShuttingDown=true,await this.flush();}pending(){return this.totalQueued}isEmpty(){return this.totalQueued===0}isClosing(){return this.isShuttingDown}};var E=class{dataDir;partitionCount;prettyPrint;fileExtension;cache=new Map;locks=new Map;constructor(t,e={}){this.dataDir=x.resolve(t),this.partitionCount=e.partitionCount??16,this.prettyPrint=e.prettyPrint??true,this.fileExtension=e.fileExtension??".json",this.ensureDirectory();}ensureDirectory(){try{d.existsSync(this.dataDir)||d.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getPartitionIndex(t){let e=0;for(let i=0;i<t.length;i++){let s=t.charCodeAt(i);e=(e<<5)-e+s,e=e&e;}return Math.abs(e)%this.partitionCount}getPartitionFileName(t,e){return `${t}_p${e.toString().padStart(3,"0")}${this.fileExtension}`}getPartitionFilePath(t,e){return x.join(this.dataDir,this.getPartitionFileName(t,e))}getCacheKey(t,e){return `${t}:${e}`}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}async readPartition(t,e){let i=this.getCacheKey(t,e);if(this.cache.has(i))return this.cache.get(i);let s=this.getPartitionFilePath(t,e);try{if(!d.existsSync(s))return null;let n=await d.promises.readFile(s,"utf-8"),r=JSON.parse(n);return this.cache.set(i,r),r}catch(n){throw new f(`Failed to read partition ${e} for collection "${t}"`,n)}}async writePartition(t,e,i){let s=this.getPartitionFilePath(t,e),n=`${s}.tmp.${Date.now()}`,r=this.getCacheKey(t,e),o=await this.acquireLock(r);try{i.updatedAt=new Date().toISOString();let a=this.prettyPrint?JSON.stringify(i,null,2):JSON.stringify(i);await d.promises.writeFile(n,a,"utf-8"),await d.promises.rename(n,s),this.cache.set(r,i);}catch(a){try{d.existsSync(n)&&await d.promises.unlink(n);}catch{}throw new f(`Failed to write partition ${e} for collection "${t}"`,a)}finally{o();}}async readAllPartitions(t){let e=new Map,i=[];for(let s=0;s<this.partitionCount;s++)i.push(this.readPartition(t,s).then(n=>{n&&e.set(s,n);}));return await Promise.all(i),e}async writePartitions(t,e){let i=[];for(let[s,n]of e)i.push(this.writePartition(t,s,n));await Promise.all(i);}async initializePartitions(t){let e=[];for(let i=0;i<this.partitionCount;i++)if(!d.existsSync(this.getPartitionFilePath(t,i))){let n={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};e.push(this.writePartition(t,i,n));}await Promise.all(e);}async getPartitionInfo(t){let e=await this.readAllPartitions(t),i=[];for(let s=0;s<this.partitionCount;s++){let n=e.get(s);i.push({name:this.getPartitionFileName(t,s),partitionIndex:s,documentCount:n?.documents.length??0});}return i}async getAllDocuments(t){let e=await this.readAllPartitions(t),i=[];for(let s of e.values())i.push(...s.documents);return i}async findById(t,e){let i=this.getPartitionIndex(e),s=await this.readPartition(t,i);return s?s.documents.find(n=>n._id===e)??null:null}async deleteCollection(t){let e=[];for(let i=0;i<this.partitionCount;i++){let s=this.getPartitionFilePath(t,i),n=this.getCacheKey(t,i);e.push((async()=>{let r=await this.acquireLock(n);try{d.existsSync(s)&&await d.promises.unlink(s),this.cache.delete(n);}finally{r();}})());}await Promise.all(e);}clearCache(t){if(t)for(let e=0;e<this.partitionCount;e++)this.cache.delete(this.getCacheKey(t,e));else this.cache.clear();}getPartitionCount(){return this.partitionCount}async listCollections(){try{let t=await d.promises.readdir(this.dataDir),e=new Set,i=new RegExp(`^(.+)_p\\d{3}\\${this.fileExtension}$`);for(let s of t){let n=s.match(i);n&&e.add(n[1]);}return Array.from(e)}catch(t){throw new f("Failed to list partitioned collections",t)}}};var I=class{maxConcurrent;maxQueueSize;queue=[];activeCount=0;completedCount=0;failedCount=0;isShuttingDown=false;constructor(t={}){this.maxConcurrent=t.maxConcurrent??4,this.maxQueueSize=t.maxQueueSize??1e4;}async submit(t,e=0){if(this.isShuttingDown)throw new Error("WorkerPool is shutting down, no new tasks accepted");if(this.queue.length>=this.maxQueueSize)throw new Error("WorkerPool queue is full, task rejected (backpressure)");return new Promise((i,s)=>{let n={task:t,resolve:i,reject:s,priority:e},r=false;for(let o=0;o<this.queue.length;o++)if(e>this.queue[o].priority){this.queue.splice(o,0,n),r=true;break}r||this.queue.push(n),this.processNext();})}async submitAll(t,e=0){let i=t.map(s=>this.submit(s,e));return Promise.all(i)}async*submitStream(t,e=0){let i=t.map(s=>this.submit(s,e));for(let s of i)yield await s;}processNext(){if(this.activeCount>=this.maxConcurrent||this.queue.length===0)return;let t=this.queue.shift();t&&(this.activeCount++,t.task().then(e=>{this.completedCount++,t.resolve(e);}).catch(e=>{this.failedCount++,t.reject(e);}).finally(()=>{this.activeCount--,this.processNext();}));}async drain(){return new Promise(t=>{let e=()=>{this.activeCount===0&&this.queue.length===0?t():setImmediate(e);};e();})}async shutdown(){this.isShuttingDown=true,await this.drain();}getStats(){return {activeWorkers:this.activeCount,queuedTasks:this.queue.length,completedTasks:this.completedCount,failedTasks:this.failedCount}}isIdle(){return this.activeCount===0&&this.queue.length===0}isClosing(){return this.isShuttingDown}queueSize(){return this.queue.length}activeWorkers(){return this.activeCount}};async function L(c,t,e){let i=[],s=0;async function n(){let o=s++;o>=c.length||(i[o]=await e(c[o],o),await n());}let r=Array(Math.min(t,c.length)).fill(null).map(()=>n());return await Promise.all(r),i}var K={partitions:16,batchSize:1e3,flushInterval:100,maxConcurrentIO:4,coalesceWrites:true},_=class{partitionManager;writeQueue;workerPool;options;constructor(t){let e=t.highConcurrency;this.options={...K,...e},this.partitionManager=new E(t.dataDir,{partitionCount:this.options.partitions,prettyPrint:t.prettyPrint??true,fileExtension:t.fileExtension??".json"}),this.workerPool=new I({maxConcurrent:this.options.maxConcurrentIO});let i=this.processBatch.bind(this);this.writeQueue=new A(i,{batchSize:this.options.batchSize,flushInterval:this.options.flushInterval,coalesceWrites:this.options.coalesceWrites});}async processBatch(t){let e=Array.from(t.entries());await L(e,this.options.maxConcurrentIO,async([i,s])=>{await this.processCollectionOperations(i,s);});}async processCollectionOperations(t,e){let i=new Map,s=n=>{let r=i.get(n);return r||(r=[],i.set(n,r)),r};for(let n of e)if(n.type==="fullWrite"||n.type==="clear")for(let r=0;r<this.partitionManager.getPartitionCount();r++)s(r).push(n);else if(n.type==="insert"){let r=this.partitionManager.getPartitionIndex(n.document._id);s(r).push(n);}else if(n.type==="update"||n.type==="delete"){let r=this.partitionManager.getPartitionIndex(n.documentId);s(r).push(n);}else if(n.type==="bulkInsert")for(let r of n.documents){let o=this.partitionManager.getPartitionIndex(r._id);s(o).push({type:"insert",collectionName:t,document:r});}else if(n.type==="bulkUpdate"||n.type==="bulkDelete")for(let r of n.documentIds){let o=this.partitionManager.getPartitionIndex(r);n.type==="bulkUpdate"?s(o).push({type:"update",collectionName:t,documentId:r,changes:n.changes}):s(o).push({type:"delete",collectionName:t,documentId:r});}await L(Array.from(i.entries()),this.options.maxConcurrentIO,async([n,r])=>{await this.processPartitionOperations(t,n,r);});}async processPartitionOperations(t,e,i){let s=await this.partitionManager.readPartition(t,e);s||(s={name:t,documents:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});for(let n of i)switch(n.type){case "insert":s.documents.push(n.document);break;case "update":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&Object.assign(s.documents[r],n.changes);break}case "delete":{let r=s.documents.findIndex(o=>o._id===n.documentId);r!==-1&&s.documents.splice(r,1);break}case "clear":s.documents=[];break;case "fullWrite":{let r=n.data.documents.filter(o=>this.partitionManager.getPartitionIndex(o._id)===e);s.documents=r;break}}await this.partitionManager.writePartition(t,e,s);}async insert(t,e){await this.writeQueue.enqueue({type:"insert",collectionName:t,document:e});}async insertMany(t,e){await this.writeQueue.enqueue({type:"bulkInsert",collectionName:t,documents:e});}async update(t,e,i){await this.writeQueue.enqueue({type:"update",collectionName:t,documentId:e,changes:i});}async delete(t,e){await this.writeQueue.enqueue({type:"delete",collectionName:t,documentId:e});}async clear(t){await this.writeQueue.enqueue({type:"clear",collectionName:t});}async findById(t,e){return await this.writeQueue.flush(),this.partitionManager.findById(t,e)}async readAll(t){return await this.writeQueue.flush(),this.partitionManager.getAllDocuments(t)}async exists(t){return (await this.partitionManager.listCollections()).includes(t)}async initializeCollection(t){await this.partitionManager.initializePartitions(t);}async deleteCollection(t){await this.writeQueue.flush(),await this.partitionManager.deleteCollection(t);}async listCollections(){return this.partitionManager.listCollections()}async flush(){await this.writeQueue.flush();}async shutdown(){await this.writeQueue.shutdown(),await this.workerPool.shutdown();}pendingWrites(){return this.writeQueue.pending()}getStats(){return {pendingWrites:this.writeQueue.pending(),workerPool:this.workerPool.getStats(),partitions:this.options.partitions}}clearCache(t){this.partitionManager.clearCache(t);}};var Q=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new D,this.idGenerator=i.idGenerator??v,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new T(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(await this.storage.findById(this.name,e))throw new w(this.name,e);let s={...h(t),_id:e},n=this.validate(s);return await this.storage.insert(this.name,n),n}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insert(this.name,s),s}async insertMany(t){if(t.length===0)return [];let e=[],i=[];for(let s of t){let n=s._id||this.idGenerator(),r={...h(s),_id:n},o=this.validate(r);i.push(o),e.push(h(o));}return await this.storage.insertMany(this.name,i),e}async find(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.findById(this.name,t);return e?h(e):null}async count(t){let e=await this.storage.readAll(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s){let r=this.getUpdateChanges(n,e);await this.storage.update(this.name,n._id,r);}return s.length}async updateOne(t,e){let i=await this.storage.readAll(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0],r=this.getUpdateChanges(n,e);return await this.storage.update(this.name,n._id,r),Object.assign(n,r),h(n)}async updateById(t,e){return this.updateOne({_id:t},e)}async delete(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;for(let s of i)await this.storage.delete(this.name,s._id);return i.length}async deleteOne(t){let e=await this.storage.readAll(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.delete(this.name,s._id),h(s)}async deleteById(t){return this.deleteOne({_id:t})}async getAll(){return this.find()}async clear(){await this.storage.clear(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}getUpdateChanges(t,e){if(!Object.keys(e).some(r=>r.startsWith("$")))return e;let s=e,n={};if(s.$set)for(let[r,o]of Object.entries(s.$set))r!=="_id"&&(n[r]=o);if(s.$inc)for(let[r,o]of Object.entries(s.$inc)){let a=t[r];typeof a=="number"&&typeof o=="number"&&(n[r]=a+o);}if(s.$push)for(let[r,o]of Object.entries(s.$push)){let a=t[r];Array.isArray(a)&&(n[r]=[...a,o]);}if(s.$pull)for(let[r,o]of Object.entries(s.$pull)){let a=t[r];Array.isArray(a)&&(n[r]=a.filter(l=>JSON.stringify(l)!==JSON.stringify(o)));}if(s.$addToSet)for(let[r,o]of Object.entries(s.$addToSet)){let a=t[r];Array.isArray(a)&&(a.some(u=>JSON.stringify(u)===JSON.stringify(o))?n[r]=a:n[r]=[...a,o]);}return n}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var S=class{capacity;cache;constructor(t){this.capacity=t,this.cache=new Map;}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);if(e!==void 0)return this.cache.delete(t),this.cache.set(t,e),e}set(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.capacity){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(t,e);}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear();}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}forEach(t){this.cache.forEach(t);}};var j=class{dataDir;fileExtension;prettyPrint;cacheSize;chunkSize;documentCache;collections;locks;constructor(t){this.dataDir=x.resolve(t.dataDir),this.fileExtension=t.fileExtension||".json",this.prettyPrint=t.prettyPrint??true,this.cacheSize=t.lazyLoading?.cacheSize??1e3,this.chunkSize=t.lazyLoading?.chunkSize??1e4,this.documentCache=new Map,this.collections=new Map,this.locks=new Map,this.ensureDirectory();}ensureDirectory(){try{d.existsSync(this.dataDir)||d.mkdirSync(this.dataDir,{recursive:!0});}catch(t){throw new f(`Failed to create data directory: ${this.dataDir}`,t)}}getFilePath(t,e){return e!==void 0&&this.chunkSize>0?x.join(this.dataDir,`${t}_chunk${e}${this.fileExtension}`):x.join(this.dataDir,`${t}${this.fileExtension}`)}getIndexFilePath(t){return x.join(this.dataDir,`${t}.index${this.fileExtension}`)}async acquireLock(t){for(;this.locks.has(t);)await this.locks.get(t);let e=()=>{},i=new Promise(s=>{e=s;});return this.locks.set(t,i),()=>{this.locks.delete(t),e();}}getCollectionData(t){let e=this.collections.get(t),i=this.documentCache.get(t);if(!e||!i)throw new f(`Collection "${t}" is not initialized`,new Error("Not initialized"));return {meta:e,cache:i}}async initCollection(t){if(this.collections.has(t))return;let e=this.getFilePath(t),i=this.getIndexFilePath(t);if(d.existsSync(i))try{let s=await d.promises.readFile(i,"utf-8"),n=JSON.parse(s),r={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:new Map(n.ids.map((o,a)=>[o,{id:o,offset:a}])),count:n.ids.length,dirty:!1};this.collections.set(t,r),this.documentCache.set(t,new S(this.cacheSize));return}catch{}if(d.existsSync(e))try{let s=await d.promises.readFile(e,"utf-8"),n=JSON.parse(s),r=new Map;n.documents.forEach((u,z)=>{r.set(u._id,{id:u._id,offset:z});});let o={name:t,createdAt:n.createdAt,updatedAt:n.updatedAt,index:r,count:n.documents.length,dirty:!1};this.collections.set(t,o),this.documentCache.set(t,new S(this.cacheSize));let{cache:a}=this.getCollectionData(t),l=Math.min(n.documents.length,this.cacheSize);for(let u=0;u<l;u++)a.set(n.documents[u]._id,n.documents[u]);await this.saveIndex(t);}catch(s){throw new f(`Failed to initialize collection "${t}"`,s)}else {let s={name:t,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),index:new Map,count:0,dirty:false};this.collections.set(t,s),this.documentCache.set(t,new S(this.cacheSize));}}async saveIndex(t){let e=this.collections.get(t);if(!e)return;let i=this.getIndexFilePath(t),s={name:t,createdAt:e.createdAt,updatedAt:e.updatedAt,ids:Array.from(e.index.keys())},n=this.prettyPrint?JSON.stringify(s,null,2):JSON.stringify(s);await d.promises.writeFile(i,n,"utf-8");}getCount(t){return this.collections.get(t)?.count??0}hasDocument(t,e){return this.collections.get(t)?.index.has(e)??false}getDocumentIds(t){let e=this.collections.get(t);return e?Array.from(e.index.keys()):[]}async getDocument(t,e){await this.initCollection(t);let i=this.collections.get(t);if(!i||!i.index.has(e))return null;let{cache:s}=this.getCollectionData(t),n=s.get(e);if(n)return n;let r=await this.loadDocumentFromDisk(t,e);return r&&s.set(e,r),r}async loadDocumentFromDisk(t,e){let i=this.getFilePath(t);try{let s=await d.promises.readFile(i,"utf-8");return JSON.parse(s).documents.find(r=>r._id===e)??null}catch{return null}}async getDocuments(t,e){await this.initCollection(t);let{cache:i}=this.getCollectionData(t),s=[],n=[];for(let r of e){let o=i.get(r);o?s.push(o):n.push(r);}if(n.length>0){let r=await this.loadDocumentsFromDisk(t,n);for(let o of r)i.set(o._id,o),s.push(o);}return s}async loadDocumentsFromDisk(t,e){let i=this.getFilePath(t),s=new Set(e);try{let n=await d.promises.readFile(i,"utf-8");return JSON.parse(n).documents.filter(o=>s.has(o._id))}catch{return []}}async getAllDocuments(t){await this.initCollection(t);let e=this.getFilePath(t);try{if(!d.existsSync(e))return [];let i=await d.promises.readFile(e,"utf-8"),s=JSON.parse(i),{cache:n}=this.getCollectionData(t);for(let r of s.documents)n.set(r._id,r);return s.documents}catch{return []}}async insertDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);s.index.set(e._id,{id:e._id,offset:s.count}),s.count++,s.updatedAt=new Date().toISOString(),s.dirty=!0,n.set(e._id,e),await this.persistCollection(t);}finally{i();}}async insertDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);for(let r of e)s.index.set(r._id,{id:r._id,offset:s.count}),s.count++,n.set(r._id,r);s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async updateDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);if(!s.index.has(e._id))return;n.set(e._id,e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocument(t,e){await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);if(!s.index.has(e))return;s.index.delete(e),s.count--,n.delete(e),s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async deleteDocuments(t,e){if(e.length===0)return;await this.initCollection(t);let i=await this.acquireLock(t);try{let{meta:s,cache:n}=this.getCollectionData(t);for(let r of e)s.index.has(r)&&(s.index.delete(r),s.count--,n.delete(r));s.updatedAt=new Date().toISOString(),s.dirty=!0,await this.persistCollection(t);}finally{i();}}async clearCollection(t){await this.initCollection(t);let e=await this.acquireLock(t);try{let{meta:i,cache:s}=this.getCollectionData(t);i.index.clear(),i.count=0,s.clear(),i.updatedAt=new Date().toISOString(),i.dirty=!0,await this.persistCollection(t);}finally{e();}}async persistCollection(t){let e=this.collections.get(t);if(!e)return;let i=this.getFilePath(t),s=`${i}.tmp.${Date.now()}`;try{let n=await this.buildDocumentArray(t),r={name:t,documents:n,createdAt:e.createdAt,updatedAt:e.updatedAt},o=this.prettyPrint?JSON.stringify(r,null,2):JSON.stringify(r);await d.promises.writeFile(s,o,"utf-8"),await d.promises.rename(s,i),await this.saveIndex(t),e.dirty=!1;}catch(n){try{d.existsSync(s)&&await d.promises.unlink(s);}catch{}throw new f(`Failed to persist collection "${t}"`,n)}}async buildDocumentArray(t){let e=this.collections.get(t);if(!e||e.count===0)return [];let i=this.getFilePath(t),s=[];try{if(d.existsSync(i)){let a=await d.promises.readFile(i,"utf-8");s=JSON.parse(a).documents;}}catch{}let n=new Map;for(let a of s)n.set(a._id,a);let{cache:r}=this.getCollectionData(t);r.forEach((a,l)=>{n.set(l,a);});let o=[];for(let a of e.index.keys()){let l=n.get(a);l&&o.push(l);}return o}async deleteCollection(t){let e=await this.acquireLock(t);try{this.collections.delete(t),this.documentCache.delete(t);let i=this.getFilePath(t),s=this.getIndexFilePath(t);d.existsSync(i)&&await d.promises.unlink(i),d.existsSync(s)&&await d.promises.unlink(s);}finally{e();}}async exists(t){if(this.collections.has(t))return true;let e=this.getFilePath(t);return d.existsSync(e)}async list(){try{let t=await d.promises.readdir(this.dataDir),e=new Set;for(let i of t)i.includes(".index")||i.includes("_chunk")||i.endsWith(this.fileExtension)&&e.add(i.slice(0,-this.fileExtension.length));return Array.from(e)}catch{return []}}getStats(){let t=0;for(let e of this.documentCache.values())t+=e.size;return {collections:this.collections.size,cachedDocuments:t,cacheSize:this.cacheSize}}clearCache(t){if(t)this.documentCache.get(t)?.clear();else for(let e of this.documentCache.values())e.clear();}async flush(){for(let[t,e]of this.collections.entries())e.dirty&&await this.persistCollection(t);}getDataDir(){return this.dataDir}};var F=class{name;storage;queryEngine;idGenerator;schema;constructor(t,e,i={}){this.name=t,this.storage=e,this.queryEngine=new D,this.idGenerator=i.idGenerator??v,this.schema=i.schema;}validate(t){if(!this.schema)return t;let e=this.schema.safeParse(t);if(!e.success)throw new T(this.name,e.error.issues);return e.data}async insert(t){let e=t._id||this.idGenerator();if(this.storage.hasDocument(this.name,e))throw new w(this.name,e);let i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertFast(t){let e=t._id||this.idGenerator(),i={...h(t),_id:e},s=this.validate(i);return await this.storage.insertDocument(this.name,s),h(s)}async insertMany(t){if(t.length===0)return [];let e=new Set(this.storage.getDocumentIds(this.name)),i=[];for(let s of t){let n=s._id||this.idGenerator();if(e.has(n))throw new w(this.name,n);e.add(n);let r={...h(s),_id:n},o=this.validate(r);i.push(o);}return await this.storage.insertDocuments(this.name,i),i.map(s=>h(s))}async find(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);return e?.sort&&(s=this.sortDocuments(s,e.sort)),e?.skip&&e.skip>0&&(s=s.slice(e.skip)),e?.limit&&e.limit>0&&(s=s.slice(0,e.limit)),e?.projection?s.map(n=>O(h(n),e.projection)):s.map(n=>h(n))}async findOne(t){let e=await this.find(t,{limit:1});return e.length>0?e[0]:null}async findById(t){let e=await this.storage.getDocument(this.name,t);return e?h(e):null}async count(t){if(!t||Object.keys(t).length===0)return this.storage.getCount(this.name);let e=await this.storage.getAllDocuments(this.name);return this.queryEngine.filter(e,t).length}async update(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return 0;for(let n of s)this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n);return s.length}async updateOne(t,e){let i=await this.storage.getAllDocuments(this.name),s=this.queryEngine.filter(i,t);if(s.length===0)return null;let n=s[0];return this.applyUpdate(n,e),await this.storage.updateDocument(this.name,n),h(n)}async updateById(t,e){let i=await this.storage.getDocument(this.name,t);return i?(this.applyUpdate(i,e),await this.storage.updateDocument(this.name,i),h(i)):null}async delete(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return 0;let s=i.map(n=>n._id);return await this.storage.deleteDocuments(this.name,s),i.length}async deleteOne(t){let e=await this.storage.getAllDocuments(this.name),i=this.queryEngine.filter(e,t);if(i.length===0)return null;let s=i[0];return await this.storage.deleteDocument(this.name,s._id),h(s)}async deleteById(t){let e=await this.storage.getDocument(this.name,t);return e?(await this.storage.deleteDocument(this.name,t),h(e)):null}async getAll(){return this.find()}async clear(){await this.storage.clearCollection(this.name);}async drop(){await this.storage.deleteCollection(this.name);}async flush(){await this.storage.flush();}getName(){return this.name}applyUpdate(t,e){if(!Object.keys(e).some(n=>n.startsWith("$"))){Object.assign(t,e);return}let s=e;if(s.$set)for(let[n,r]of Object.entries(s.$set))n!=="_id"&&k(t,n,r);if(s.$unset)for(let n of Object.keys(s.$unset))n!=="_id"&&b(t,n);if(s.$inc)for(let[n,r]of Object.entries(s.$inc)){let o=t[n];typeof o=="number"&&typeof r=="number"&&(t[n]=o+r);}if(s.$push)for(let[n,r]of Object.entries(s.$push)){let o=t[n];Array.isArray(o)&&o.push(r);}if(s.$pull)for(let[n,r]of Object.entries(s.$pull)){let o=t[n];if(Array.isArray(o)){let a=o.findIndex(l=>JSON.stringify(l)===JSON.stringify(r));a!==-1&&o.splice(a,1);}}if(s.$addToSet)for(let[n,r]of Object.entries(s.$addToSet)){let o=t[n];Array.isArray(o)&&(o.some(l=>JSON.stringify(l)===JSON.stringify(r))||o.push(r));}}sortDocuments(t,e){let i=Object.entries(e);return [...t].sort((s,n)=>{for(let[r,o]of i){let a=s[r],l=n[r],u=0;if(a===l?u=0:a==null?u=1:l==null?u=-1:typeof a=="number"&&typeof l=="number"?u=a-l:typeof a=="string"&&typeof l=="string"?u=a.localeCompare(l):a instanceof Date&&l instanceof Date?u=a.getTime()-l.getTime():u=String(a).localeCompare(String(l)),u!==0)return u*(o===-1||o==="desc"?-1:1)}return 0})}};var G={autoSave:true,saveDebounce:0,prettyPrint:true,fileExtension:".json"},H=class{options;storage;hcStorage;lazyStorage;collections=new Map;isHighConcurrency;isLazyLoading;connected=false;constructor(t){if(this.options={...G,...t},this.isHighConcurrency=t.highConcurrency?.enabled??false,this.isLazyLoading=t.lazyLoading?.enabled??false,this.isHighConcurrency&&this.isLazyLoading)throw new Error("Cannot enable both highConcurrency and lazyLoading modes simultaneously");this.isHighConcurrency?(this.storage=null,this.hcStorage=new _(this.options),this.lazyStorage=null):this.isLazyLoading?(this.storage=null,this.hcStorage=null,this.lazyStorage=new j(this.options)):(this.storage=new M(this.options),this.hcStorage=null,this.lazyStorage=null);}getStorage(){if(this.storage===null)throw new Error("Storage is not available in high-concurrency or lazy loading mode");return this.storage}getHCStorage(){if(this.hcStorage===null)throw new Error("HighConcurrencyStorage is not available in standard or lazy loading mode");return this.hcStorage}getLazyStorage(){if(this.lazyStorage===null)throw new Error("LazyStorage is not available in standard or high-concurrency mode");return this.lazyStorage}async connect(){if(!this.connected){if(this.isHighConcurrency){let t=await this.getHCStorage().listCollections();for(let e of t)this.getOrCreateCollection(e);}else if(this.isLazyLoading){let t=await this.getLazyStorage().list();for(let e of t)this.getOrCreateCollection(e);}else {let t=await this.getStorage().list();for(let e of t)this.getOrCreateCollection(e);}this.connected=true;}}async close(){if(this.connected){for(let t of this.collections.values())await t.flush();this.isHighConcurrency&&this.hcStorage&&await this.hcStorage.shutdown(),this.collections.clear(),this.storage&&this.storage.clearCache(),this.hcStorage&&this.hcStorage.clearCache(),this.lazyStorage&&this.lazyStorage.clearCache(),this.connected=false;}}collection(t,e){if(!t||typeof t!="string")throw new C("Collection name must be a non-empty string");if(!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(t))throw new C("Collection name must start with a letter or underscore and contain only letters, numbers, underscores, and hyphens");return this.getOrCreateCollection(t,e)}getOrCreateCollection(t,e){if(this.collections.has(t))return this.collections.get(t);if(this.isHighConcurrency){let i=new Q(t,this.getHCStorage(),{schema:e?.schema});this.collections.set(t,i);}else if(this.isLazyLoading){let i=new F(t,this.getLazyStorage(),{schema:e?.schema});this.collections.set(t,i);}else {let i=new $(t,this.getStorage(),{autoSave:this.options.autoSave,saveDebounce:this.options.saveDebounce,schema:e?.schema});this.collections.set(t,i);}return this.collections.get(t)}async hasCollection(t){return this.isHighConcurrency?this.getHCStorage().exists(t):this.getStorage().exists(t)}async listCollections(){return this.isHighConcurrency?this.getHCStorage().listCollections():this.getStorage().list()}async dropCollection(t){let e=this.collections.get(t);e?(await e.drop(),this.collections.delete(t)):this.isHighConcurrency?await this.getHCStorage().deleteCollection(t):await this.getStorage().delete(t);}async drop(){if(this.isHighConcurrency){let t=this.getHCStorage(),e=await t.listCollections();for(let i of e)await t.deleteCollection(i);}else {let t=this.getStorage(),e=await t.list();for(let i of e)await t.delete(i);}this.collections.clear(),this.storage?.clearCache(),this.hcStorage?.clearCache();}getDataDir(){return this.isHighConcurrency?this.options.dataDir:this.getStorage().getDataDir()}isConnected(){return this.connected}isHighConcurrencyMode(){return this.isHighConcurrency}getStats(){return !this.isHighConcurrency||!this.hcStorage?null:this.hcStorage.getStats()}async flush(){for(let t of this.collections.values())await t.flush();}};export{$ as Collection,C as CollectionError,R as DocumentNotFoundError,w as DuplicateKeyError,Q as HighConcurrencyCollection,_ as HighConcurrencyStorage,H as JsonDB,P as JsonDBError,F as LazyCollection,E as PartitionManager,f as StorageError,T as ValidationError,I as WorkerPool,A as WriteQueue,v as generateId,U as isValidId,L as parallelLimit};
package/package.json CHANGED
@@ -1,97 +1,97 @@
1
- {
2
- "name": "nodejs-json-db",
3
- "version": "0.0.2",
4
- "description": "A production-ready, lightweight JSON-based database for Node.js and Electron applications",
5
- "main": "./dist/index.js",
6
- "types": "./dist/index.d.ts",
7
- "module": "./dist/index.mjs",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "require": "./dist/index.js",
12
- "import": "./dist/index.mjs",
13
- "default": "./dist/index.js"
14
- }
15
- },
16
- "sideEffects": false,
17
- "scripts": {
18
- "build": "tsup",
19
- "test": "vitest run",
20
- "test:watch": "vitest",
21
- "test:coverage": "vitest run --coverage",
22
- "dev": "tsup --watch",
23
- "lint": "eslint src --ext .ts",
24
- "format": "prettier --write \"src/**/*.ts\"",
25
- "typecheck": "tsc --noEmit",
26
- "prepublishOnly": "npm run build && npm run test",
27
- "benchmark": "tsx examples/benchmark.ts",
28
- "prepare": "husky"
29
- },
30
- "files": [
31
- "dist",
32
- "README.md",
33
- "LICENSE"
34
- ],
35
- "repository": {
36
- "type": "git",
37
- "url": "https://github.com/iqbal-rashed/nodejs-json-db.git"
38
- },
39
- "keywords": [
40
- "json",
41
- "database",
42
- "db",
43
- "nosql",
44
- "document",
45
- "storage",
46
- "electron",
47
- "nodejs",
48
- "typescript",
49
- "esm",
50
- "cjs",
51
- "lightweight",
52
- "file-based",
53
- "local-storage"
54
- ],
55
- "author": "Rashed Iqbal",
56
- "license": "MIT",
57
- "bugs": {
58
- "url": "https://github.com/iqbal-rashed/nodejs-json-db/issues"
59
- },
60
- "homepage": "https://github.com/iqbal-rashed/nodejs-json-db#readme",
61
- "engines": {
62
- "node": ">=18.0.0"
63
- },
64
- "devDependencies": {
65
- "@eslint/js": "^9.18.0",
66
- "@types/node": "^22.10.5",
67
- "@vitest/coverage-v8": "^4.0.16",
68
- "eslint": "^9.18.0",
69
- "globals": "^15.14.0",
70
- "husky": "^9.1.7",
71
- "lint-staged": "^16.2.7",
72
- "prettier": "^3.4.2",
73
- "tsup": "^8.5.1",
74
- "tsx": "^4.21.0",
75
- "typescript": "^5.9.3",
76
- "typescript-eslint": "^8.19.1",
77
- "vitest": "^4.0.16",
78
- "zod": "^4.2.1"
79
- },
80
- "dependencies": {
81
- "bson": "^7.0.0"
82
- },
83
- "peerDependencies": {
84
- "zod": "^3.0.0 || ^4.0.0"
85
- },
86
- "peerDependenciesMeta": {
87
- "zod": {
88
- "optional": true
89
- }
90
- },
91
- "lint-staged": {
92
- "*.ts": [
93
- "eslint --fix",
94
- "prettier --write"
95
- ]
96
- }
97
- }
1
+ {
2
+ "name": "nodejs-json-db",
3
+ "version": "0.0.3",
4
+ "description": "A production-ready, lightweight JSON-based database for Node.js and Electron applications",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "module": "./dist/index.mjs",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "import": "./dist/index.mjs",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "sideEffects": false,
17
+ "scripts": {
18
+ "build": "tsup",
19
+ "test": "vitest run",
20
+ "test:watch": "vitest",
21
+ "test:coverage": "vitest run --coverage",
22
+ "dev": "tsup --watch",
23
+ "lint": "eslint src --ext .ts",
24
+ "format": "prettier --write \"src/**/*.ts\"",
25
+ "typecheck": "tsc --noEmit",
26
+ "prepublishOnly": "npm run build && npm run test",
27
+ "benchmark": "tsx examples/benchmark.ts",
28
+ "prepare": "husky"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/iqbal-rashed/nodejs-json-db.git"
38
+ },
39
+ "keywords": [
40
+ "json",
41
+ "database",
42
+ "db",
43
+ "nosql",
44
+ "document",
45
+ "storage",
46
+ "electron",
47
+ "nodejs",
48
+ "typescript",
49
+ "esm",
50
+ "cjs",
51
+ "lightweight",
52
+ "file-based",
53
+ "local-storage"
54
+ ],
55
+ "author": "Rashed Iqbal",
56
+ "license": "MIT",
57
+ "bugs": {
58
+ "url": "https://github.com/iqbal-rashed/nodejs-json-db/issues"
59
+ },
60
+ "homepage": "https://github.com/iqbal-rashed/nodejs-json-db#readme",
61
+ "engines": {
62
+ "node": ">=18.0.0"
63
+ },
64
+ "devDependencies": {
65
+ "@eslint/js": "^9.18.0",
66
+ "@types/node": "^22.10.5",
67
+ "@vitest/coverage-v8": "^4.0.16",
68
+ "eslint": "^9.18.0",
69
+ "globals": "^15.14.0",
70
+ "husky": "^9.1.7",
71
+ "lint-staged": "^16.2.7",
72
+ "prettier": "^3.4.2",
73
+ "tsup": "^8.5.1",
74
+ "tsx": "^4.21.0",
75
+ "typescript": "^5.9.3",
76
+ "typescript-eslint": "^8.19.1",
77
+ "vitest": "^4.0.16",
78
+ "zod": "^4.2.1"
79
+ },
80
+ "dependencies": {
81
+ "bson": "^7.0.0"
82
+ },
83
+ "peerDependencies": {
84
+ "zod": "^3.0.0 || ^4.0.0"
85
+ },
86
+ "peerDependenciesMeta": {
87
+ "zod": {
88
+ "optional": true
89
+ }
90
+ },
91
+ "lint-staged": {
92
+ "*.ts": [
93
+ "eslint --fix",
94
+ "prettier --write"
95
+ ]
96
+ }
97
+ }