@asaidimu/utils-database 3.1.10 → 3.1.11

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/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SystemError } from "@asaidimu/utils-error";
1
+ import { Mutex } from "@asaidimu/utils-sync";
2
2
  import { EventBus } from "@asaidimu/utils-events";
3
3
 
4
4
  //#region node_modules/.bun/@asaidimu+query@1.1.2/node_modules/@asaidimu/query/index.d.ts
@@ -11703,74 +11703,6 @@ declare class Pipeline {
11703
11703
  wrap<T extends object>(target: T, baseContext: Partial<MiddlewareContext>): T;
11704
11704
  }
11705
11705
  //#endregion
11706
- //#region src/sync/mutex.d.ts
11707
- interface MutexOptions {
11708
- /**
11709
- * Maximum number of pending requests allowed in the queue.
11710
- * If exceeded, tryLock/lock will fail.
11711
- * @default Infinity
11712
- */
11713
- capacity?: number;
11714
- /**
11715
- * Controls how lock handoff is scheduled when a waiter is unblocked.
11716
- *
11717
- * - `"macrotask"` (default): Uses setTimeout(fn, 0) to yield to the event
11718
- * loop between handoffs. Prevents microtask starvation under heavy
11719
- * contention — I/O, rendering, and other macrotasks can run between
11720
- * lock acquisitions. Use for Serializer and other coarse-grained
11721
- * serializers.
11722
- *
11723
- * - `"microtask"`: Uses queueMicrotask(fn) for handoff. Near-zero latency
11724
- * between acquisitions — no macrotask delay. Safe when you need
11725
- * back-to-back operations to complete as fast as possible and starvation
11726
- * is not a concern (e.g. Once, Semaphore where builds are infrequent
11727
- * and latency matters more than fairness).
11728
- */
11729
- yieldMode?: "macrotask" | "microtask";
11730
- }
11731
- /**
11732
- * A mutual exclusion lock.
11733
- * Allows only one execution context to access a resource at a time.
11734
- *
11735
- * Yield mode is configurable per instance:
11736
- * - "macrotask" (default): yields between handoffs, preventing microtask starvation.
11737
- * - "microtask": zero-delay handoff for latency-sensitive paths.
11738
- */
11739
- declare class Mutex {
11740
- private _locked;
11741
- private _capacity;
11742
- private _yieldMode;
11743
- private waiters;
11744
- constructor(options?: MutexOptions);
11745
- /**
11746
- * Acquires the lock. If already held, waits until released or timeout reached.
11747
- *
11748
- * @param timeout - Optional maximum wait time in milliseconds.
11749
- * @throws {TimeoutError} If the lock cannot be acquired within the timeout.
11750
- * @throws {Error} If the wait queue is full (backpressure).
11751
- */
11752
- lock(timeout?: number): Promise<void>;
11753
- /**
11754
- * Attempts to acquire the lock without waiting.
11755
- * @returns `true` if the lock was acquired, `false` otherwise.
11756
- */
11757
- tryLock(): boolean;
11758
- /**
11759
- * Releases the lock, scheduling the next waiter according to yieldMode.
11760
- *
11761
- * When a waiter exists, `_locked` intentionally remains `true` — ownership
11762
- * transfers directly to the next waiter without ever clearing the flag.
11763
- * Only when the queue is empty is `_locked` set to false.
11764
- *
11765
- * @throws {Error} If the mutex is not currently locked.
11766
- */
11767
- unlock(): void;
11768
- /** Returns true if the mutex is currently locked. */
11769
- locked(): boolean;
11770
- /** Returns the number of operations waiting for the lock. */
11771
- pending(): number;
11772
- }
11773
- //#endregion
11774
11706
  //#region src/database/document.d.ts
11775
11707
  interface DocumentOptions<T extends Record<string, any>> {
11776
11708
  /**
package/index.js CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);let t=require("@asaidimu/utils-error"),n=require("buffer"),r=require("@asaidimu/utils-events"),i=require("uuid"),a=function(e){return e.SCHEMA_NOT_FOUND=`SCHEMA_NOT_FOUND`,e.SCHEMA_ALREADY_EXISTS=`SCHEMA_ALREADY_EXISTS`,e.INVALID_SCHEMA_NAME=`INVALID_SCHEMA_NAME`,e.INVALID_SCHEMA_DEFINITION=`INVALID_SCHEMA_DEFINITION`,e.SUBSCRIPTION_FAILED=`SUBSCRIPTION_FAILED`,e.INTERNAL_ERROR=`INTERNAL_ERROR`,e.INVALID_DATA=`INVALID_DATA`,e.CONFLICT=`CONFLICT`,e.TRANSIENT_ERROR=`TRANSIENT_ERROR`,e.TRANSACTION_FAILED=`TRANSACTION_FAILED`,e.CONNECTION_FAILED=`CONNECTION_FAILED`,e.INVALID_OPERATION=`INVALID_OPERATION`,e}({});var o=class extends Error{type;schema;issues;constructor(e,t,n,r,i){super(t,{cause:r}),this.name=`DatabaseError`,this.type=e,this.schema=n,this.issues=i}};function s(e){if(typeof e!=`object`||!e||Array.isArray(e))return[e,{}];let t={};return[Object.entries(e).reduce((e,[n,r])=>(n.startsWith(`$`)?t[n]=r:e[n]=r,e),{}),t]}function c(e,t){if(!(!e||e.$version===void 0||t.$version===void 0)&&t.$version<=e.$version)throw new o(`CONFLICT`,`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function l(e,t){let n=[];for(let r of t.fields){let t=e[r];if(t==null)return null;n.push(String(t))}return n.join(`\0`)}function u(e,t){if(!t.partial)return!0;let{field:n,value:r}=t.partial;return e[n]===r}var d=class{storeName;keyPath;data=new Map;indexes=new Map;nextId=1;constructor(e,t=`$id`,n=[]){this.storeName=e,this.keyPath=t;for(let e of n)this.indexes.set(e.name,{definition:e,map:new Map})}name(){return this.storeName}async open(){}_snapshotMemory(){let e=new Map;for(let[t,n]of this.data)e.set(t,{...n});let t=new Map;for(let[e,n]of this.indexes){let r=new Map;for(let[e,t]of n.map)r.set(e,new Set(t));t.set(e,{definition:n.definition,map:r})}return{data:e,indexes:t,nextId:this.nextId}}_rollbackMemory(e){this.data=e.data,this.indexes=e.indexes,this.nextId=e.nextId}async createIndex(e){if(this.indexes.has(e.name))return;let t={definition:e,map:new Map};this.indexes.set(e.name,t);for(let e of this.data.values())this.indexOne(t,e)}async dropIndex(e){this.indexes.delete(e)}async getByIndex(e,t){return(await this.findByIndex(e,t))[0]}async findByIndex(e,t){let n=this.indexes.get(e);if(!n)throw new o(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=String(t),i=n.map.get(r);if(!i||i.size===0)return[];let a=[];for(let e of i){let t=this.data.get(e);t&&a.push(this.clone(t))}return a}async getByKeyRange(e,t){let n=this.indexes.get(e);if(!n)throw new o(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=[];for(let[e,i]of n.map.entries())if(this.isInKeyRange(e,t))for(let e of i){let t=this.data.get(e);t&&r.push(this.clone(t))}return r}async add(e){let t=Array.isArray(e)?e:[e],n=[];for(let e of t){let t=e[this.keyPath];if((t===void 0||t===``)&&(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new o(`CONFLICT`,`Duplicate key ${t}`);this.enforceUniqueIndexes(e,void 0);let r=Object.freeze(this.clone(e));this.data.set(t,r),this.indexDocument(r),n.push(t)}return Array.isArray(e)?n:n[0]}async put(e){let t=this.getKey(e),n=this.data.get(t);c(n,e),this.enforceUniqueIndexes(e,n),n&&this.unindexDocument(n);let r=Object.freeze(this.clone(e));return this.data.set(t,r),this.indexDocument(r),t}async batch(e){let t=new Map,n=e=>t.has(e)?t.get(e):this.data.get(e);for(let r of e)if(r.type===`add`||r.type===`put`){let e=Array.isArray(r.data)?r.data:[r.data];for(let i of e){let e;if(r.type===`add`){if(e=i[this.keyPath],(e===void 0||e===``)&&(e=String(this.nextId++),i[this.keyPath]=e),n(e)!=null)throw new o(`CONFLICT`,`Duplicate key ${e}`)}else e=this.getKey(i);c(n(e)??void 0,i),t.set(e,Object.freeze(this.clone(i)))}}else{let e=Array.isArray(r.data)?r.data:[r.data];for(let n of e)t.set(n,null)}for(let[e,n]of t.entries()){let t=this.data.get(e);t&&this.unindexDocument(t),n===null?this.data.delete(e):(this.enforceUniqueIndexes(n,t),this.data.set(e,n),this.indexDocument(n))}}async delete(e){let t=Array.isArray(e)?e:[e];for(let e of t){let t=this.data.get(e);t&&this.unindexDocument(t),this.data.delete(e)}}async clear(){this.data.clear();for(let e of this.indexes.values())e.map.clear()}async executeInTransaction(e,t){if(t!==null)throw new o(`INTERNAL_ERROR`,`executeInTransaction called on MemoryStore '${this.storeName}' with a non-null sharedTx`);for(let t of e)if(t.type===`add`)await this.add(t.data);else if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.put(t)}else await this.delete(t.data)}async getById(e){let t=this.data.get(e);return t?this.clone(t):void 0}async getAll(){return Array.from(this.data.values()).map(e=>this.clone(e))}async count(){return this.data.size}async cursor(e,t=`forward`,n){let r=Array.from(this.data.entries());n&&(r=r.filter(([e])=>this.isInKeyRange(e,n)));let i=r.sort(([e],[t])=>e>t?1:e<t?-1:0);t===`backward`&&i.reverse();let a=null,o=0;for(;o<i.length;){let[t,n]=i[o],{value:r,done:s,offset:c}=await e(this.clone(n),t,null);if(a=r,s)break;o+=c&&c>0?c:1}return a}getKey(e){let t=e[this.keyPath];if(t==null)throw new o(`INVALID_DATA`,`Record must have a '${this.keyPath}' property`);return t}clone(e){return{...e}}indexDocument(e){for(let t of this.indexes.values())this.indexOne(t,e)}indexOne(e,t){if(!u(t,e.definition))return;let n=l(t,e.definition);if(n===null)return;let r=t[this.keyPath];if(r===void 0)return;let i=e.map.get(n);i||(i=new Set,e.map.set(n,i)),i.add(r)}unindexDocument(e){let t=e[this.keyPath];if(t!==void 0)for(let n of this.indexes.values()){let r=l(e,n.definition);if(r===null)continue;let i=n.map.get(r);i&&(i.delete(t),i.size===0&&n.map.delete(r))}}enforceUniqueIndexes(e,t){let n=e[this.keyPath],r=t?t[this.keyPath]:void 0;for(let t of this.indexes.values()){if(!t.definition.unique||!u(e,t.definition))continue;let i=l(e,t.definition);if(i===null)continue;let a=t.map.get(i);if(!(!a||a.size===0)){for(let e of a)if(!(e===n||e===r))throw new o(`CONFLICT`,`Unique index '${t.definition.name}' violation: value already exists for field(s) [${t.definition.fields.join(`, `)}]`)}}}isInKeyRange(e,t){if(!t)return!0;let{lower:n,upper:r,lowerOpen:i=!1,upperOpen:a=!1}=t;return(n===void 0||(i?e>n:e>=n))&&(r===void 0||(a?e<r:e<=r))}};function f(e){return new d(e.database,e.keyPath)}var p=class e extends t.SystemError{constructor(t,n){super({code:`SYNC_ERROR`,message:t,cause:n}),this.name=`SyncError`,Object.setPrototypeOf(this,e.prototype)}},m=class e extends p{constructor(t){super(`[ArtifactContainer] Operation timed out: ${t}`),this.name=`TimeoutError`,Object.setPrototypeOf(this,e.prototype)}},h=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??`macrotask`}async lock(e){if(!this._locked){this._locked=!0;return}if(this.waiters.length>=this._capacity)throw Error(`Mutex queue is full (capacity: ${this._capacity})`);let t,n=new Promise(e=>t=e);if(this.waiters.push(t),e==null){await n;return}let r;await Promise.race([n.then(()=>clearTimeout(r)),new Promise((n,i)=>{r=setTimeout(()=>{let e=this.waiters.indexOf(t);e!==-1&&this.waiters.splice(e,1),i(new m(`Mutex lock timed out`))},e)})])}tryLock(){return this._locked?!1:(this._locked=!0,!0)}unlock(){if(!this._locked)throw Error(`Mutex is not locked`);let e=this.waiters.shift();e?this._yieldMode===`microtask`?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},g=class{mutex=new h({yieldMode:`microtask`});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=!!e,this.throws=!!t}resolve(e){if(this._done)throw Error(`Cannot resolve: operation is already completed.`);if(this.running())throw Error(`Cannot resolve: operation is currently running.`);this._value=e,this._done=!0}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,`Once do() timed out`):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,`Once do() timed out`)):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,`Once do() timed out`)))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){let e=Error(`Cannot execute doSync while an async operation is pending.`);if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){let e=Error(`Cannot execute doSync: lock is currently held.`);if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}let e=Error(`Cannot execute doSync while an async operation is pending.`);if(this.throws)throw e;return{value:null,error:e}}try{let t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return this.promise!==null&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw Error(`Once operation is not yet complete`);if(this._error)throw this._error;return this._value}reset(){if(this.running())throw Error(`Cannot reset Once while an operation is in progress.`);this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,n=`Operation timed out`){if(t==null)return e;let r;return Promise.race([e.then(e=>(clearTimeout(r),e)),new Promise((e,i)=>{r=setTimeout(()=>i(new m(n)),t)})])}},_=class{config;connectionInitializer=new g({retry:!0,throws:!0});schemasStoreName;constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||`schemas`}async openDatabase(){return new Promise((e,t)=>{let n=indexedDB.open(this.config.database);n.onerror=()=>t(Error(`Failed to open database: ${n.error?.message}`)),n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:`name`})},n.onsuccess=()=>e(n.result)})}async upgradeDatabase(e,t){let n=e.version+1;return e.close(),new Promise((e,r)=>{let i=indexedDB.open(this.config.database,n);i.onerror=()=>r(Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{let n=e.target.result,r=e.target.transaction;t(n,r)},i.onsuccess=()=>e(i.result)})}async ensureStore(e,t=`$id`,n=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade(r=>{if(r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:`name`}),!r.objectStoreNames.contains(e)){let i=r.createObjectStore(e,{keyPath:t});for(let e of n){let t=e.fields.length===1?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}})}async createStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);if(i.indexNames.contains(t.name))return;let a=t.fields.length===1?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})})}async dropStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)})}getConnection=async()=>{let e=await this.connectionInitializer.do(async()=>{let e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e});if(e.error)throw new o(`CONNECTION_FAILED`,`Failed to open database: ${this.config.database}`,void 0,e.error);return e.value};async openTransaction(e,t=`readwrite`){return(await this.getConnection()).transaction(e,t)}async upgrade(e){let t=await this.getConnection();this.connectionInitializer.reset();let n=await this.connectionInitializer.do(async()=>await this.upgradeDatabase(t,e));if(n.error)throw new o(`INTERNAL_ERROR`,`Database upgrade failed for ${this.config.database}`,void 0,n.error);return n.value}close(){let e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function v(e){if(e){if(e.lower!==void 0&&e.upper!==void 0)return IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen);if(e.lower!==void 0)return IDBKeyRange.lowerBound(e.lower,e.lowerOpen);if(e.upper!==void 0)return IDBKeyRange.upperBound(e.upper,e.upperOpen)}}var y=class{connectionManager;collection;keyPath;indexes;constructor(e,t,n=`$id`,r=[]){this.connectionManager=e,this.collection=t,this.keyPath=n,this.indexes=r}name(){return this.collection}async _getIDBConnection(){return this.connectionManager.getConnection()}async open(){await this.connectionManager.ensureStore(this.collection,this.keyPath,this.indexes)}async createIndex(e){await this.connectionManager.createStoreIndex(this.collection,e)}async dropIndex(e){await this.connectionManager.dropStoreIndex(this.collection,e)}async getByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.get(t))})}async getByKeyRange(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.getAll(v(t)))})}async findByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))})}async put(e){return this.withTx(`readwrite`,async t=>{let n=e[this.keyPath];return n!==void 0&&c(await this.requestToPromise(t.get(n)),e),this.requestToPromise(t.put(e))})}async add(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e],r=[];for(let e of n){let n=await this.requestToPromise(t.add(e));r.push(n)}return Array.isArray(e)?r:r[0]})}async batch(e){return this.withTx(`readwrite`,async t=>{for(let n of e)if(n.type===`put`||n.type===`add`){let e=Array.isArray(n.data)?n.data:[n.data];for(let r of e)if(n.type===`put`){let e=r[this.keyPath];e!==void 0&&c(await this.requestToPromise(t.get(e)),r),await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{let e=Array.isArray(n.data)?n.data:[n.data];for(let n of e)await this.requestToPromise(t.delete(n))}})}async delete(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e];for(let e of n)await this.requestToPromise(t.delete(e))})}async clear(){return this.withTx(`readwrite`,async e=>{await this.requestToPromise(e.clear())})}async executeInTransaction(e,t){if(!t)throw new o(`INTERNAL_ERROR`,`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);let n=t.objectStore(this.collection);for(let t of e)if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e){let e=t[this.keyPath];e!==void 0&&c(await this.requestToPromise(n.get(e)),t),await this.requestToPromise(n.put(t))}}else if(t.type===`add`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.add(t))}else{let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.delete(t))}}async getById(e){return this.withTx(`readonly`,async t=>this.requestToPromise(t.get(e)))}async getAll(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.getAll()))}async count(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.count()))}async cursor(e,t=`forward`,n){return this.withTx(`readonly`,async r=>{let i=t===`forward`?`next`:`prev`,a=r.openCursor(v(n),i);return new Promise((t,n)=>{let r=null;a.onsuccess=async i=>{let a=i.target.result;if(!a)return t(r);try{let{value:n,done:i,offset:o}=await e(a.value,a.key,a);r=n,i?t(r):o&&o>0?a.advance(o):a.continue()}catch(e){n(e)}},a.onerror=()=>n(this.mapError(a.error))})})}mapError(e){if(e instanceof o)return e;let t=e?.message||`Unknown IndexedDB Error`,n=e?.name||``;return n===`QuotaExceededError`?new o(`INTERNAL_ERROR`,`Storage quota exceeded`):n===`VersionError`?new o(`CONFLICT`,t):n===`InvalidStateError`||n===`TransactionInactiveError`?new o(`TRANSIENT_ERROR`,t):new o(`INTERNAL_ERROR`,t)}async withTx(e,t){let n=await this.connectionManager.getConnection();return new Promise(async(r,i)=>{let a=n.transaction(this.collection,e),o=a.objectStore(this.collection),s,c;a.oncomplete=()=>{c?i(c):r(s)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{let e=t(o,a);s=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch{}}})}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}};const b=new Map,ee=e=>{let t=b.get(e.database);t||(t=new g({retry:!0,throws:!0}),b.set(e.database,t));try{let{value:n,error:r}=t.doSync(()=>new _(e));if(r)throw new o(`CONNECTION_FAILED`,`Failed to initialize connection for database: ${e.database}`,void 0,r);return new y(n,e.collection,e.keyPath)}catch(e){throw e instanceof o?e:new o(`CONNECTION_FAILED`,e instanceof Error?e.message:`An unexpected connection error occurred`,void 0,e)}};var x=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{createEventBus:()=>u}),t.exports=c(l);var u=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error(`EventBus Error:`,e),crossTab:!1,channelName:`event-bus-channel`})=>{let t=new Map,n=[],r=0,i=0,a=new Map,o=new Map,s=null;e.crossTab&&typeof BroadcastChannel<`u`?s=new BroadcastChannel(e.channelName):e.crossTab&&console.warn(`BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.`);let c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{let t=n;n=[],t.forEach(({name:t,payload:n})=>{let r=performance.now();try{(o.get(t)||[]).forEach(e=>e(n))}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-r)})},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{let n=t.get(e);n?o.set(e,Array.from(n)):o.delete(e)};return s&&(s.onmessage=e=>{let{name:t,payload:n}=e.data;(o.get(t)||[]).forEach(e=>e(n))}),{subscribe:(e,n)=>{t.has(e)||t.set(e,new Set);let r=t.get(e);return r.add(n),d(e),()=>{r.delete(n),r.size===0?(t.delete(e),o.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async){n.push({name:t,payload:r}),n.length>=e.batchSize?l():u(),s&&s.postMessage({name:t,payload:r});return}let i=performance.now();try{(o.get(t)||[]).forEach(e=>e(r)),s&&s.postMessage({name:t,payload:r})}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:r,activeSubscriptions:Array.from(t.values()).reduce((e,t)=>e+t.size,0),eventCounts:a,averageEmitDuration:r>0?i/r:0}),clear:()=>{t.clear(),o.clear(),n=[],r=0,i=0,a.clear(),s&&=(s.close(),null)}}};0&&(t.exports={createEventBus:u})})),te=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{QueryBuilder:()=>u,createJoiner:()=>ae,createMatcher:()=>v,createPaginator:()=>ue,createProjector:()=>ce,createSorter:()=>O}),t.exports=c(l);var u=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:`offset`,offset:e,limit:t},this}cursor(e,t,n){return this.query.pagination={type:`cursor`,cursor:e,limit:t,direction:n},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`computed`,expression:e,alias:t}),this}case(e,t,n){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`case`,conditions:e,else:t,alias:n}),this}join(e,t,n){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:n,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function d(e){function t(e,t){return f(t)?e[t.field]:p(t)?t.value:g(t)?i(t,e):m(t)?i(t.expression,e):h(t)?a(e,t):t}let n=new Map([[`and`,(e,t)=>t.every(t=>o(e,t))],[`or`,(e,t)=>t.some(t=>o(e,t))],[`not`,(e,t)=>!t.every(t=>o(e,t))],[`nor`,(e,t)=>!t.some(t=>o(e,t))],[`xor`,(e,t)=>t.filter(t=>o(e,t)).length===1]]);function r(e,t){let{operator:r,conditions:i}=t,a=n.get(r);if(a)return a(e,i);throw Error(`Unsupported logical operator: ${r}`)}function i(n,r){let i=n.arguments.map(e=>t(r,e));if(e[n.function])return e[n.function](...i);throw Error(`Function ${n.function} not found!`)}function a(e,t){for(let n of t.conditions)if(o(e,n.when))return n.then;return t.else}function o(n,i){if(_(i))return r(n,i);if(!i||!i.field)return!1;let{field:a,operator:o,value:s}=i,c=n[a],l=t(n,s),u=new Map([[`eq`,(e,t)=>e===t],[`neq`,(e,t)=>e!==t],[`lt`,(e,t)=>e<t],[`lte`,(e,t)=>e<=t],[`gt`,(e,t)=>e>t],[`gte`,(e,t)=>e>=t],[`in`,(e,t)=>Array.isArray(t)&&t.includes(e)],[`nin`,(e,t)=>Array.isArray(t)&&!t.includes(e)],[`contains`,(e,t)=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.includes(s):!1],[`ncontains`,(e,t)=>typeof e==`string`&&!e.includes(t)],[`startswith`,(e,t)=>typeof e==`string`&&e.startsWith(t)],[`endswith`,(e,t)=>typeof e==`string`&&e.endsWith(t)],[`exists`,e=>e!=null],[`nexists`,e=>e==null]]),d=e[o]||u.get(o);if(d)return d(c,l);throw Error(`Unsupported comparison operator: ${o}`)}return{resolve:t,evaluate:o}}function f(e){return e?.type===`field`}function p(e){return e?.type===`value`}function m(e){return e?.type===`computed`}function h(e){return e?.type===`case`}function g(e){return e?.type===`function`}function _(e){return e?e.conditions!==void 0:!1}function v(e){let{evaluate:t}=d(e),n=new WeakMap;function r(e,r){let i=n.get(e);i||(i=new Map,n.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let o=t(e,r);return i.set(a,o),o}return{matcher:r,match:r}}var y=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`JoinError`}},b=e=>e&&`field`in e&&`operator`in e&&`value`in e,ee=e=>`operator`in e&&`conditions`in e,x=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`field`,te=(e,t)=>{if(!e.relation)throw new y(`Join configuration must specify a relation`,`INVALID_CONFIG`);if(!t[e.relation])throw new y(`Collection "${e.relation}" not found in database`,`COLLECTION_NOT_FOUND`);if(e.alias&&typeof e.alias!=`string`)throw new y(`Join alias must be a string`,`INVALID_ALIAS`)},ne=(e,t)=>t.split(`.`).reduce((e,t)=>e?.[t],e),S=(e,t)=>{if(e){if(b(e)&&e){let n=x(e.value)?ne(t,e.value.field):e.value;return{...e,value:n}}if(ee(e)){let n={...e};return e.conditions&&(n.conditions=e.conditions.map(e=>S(e,t))),n}return e}},re=(e,t)=>{if(!e)return{};let n=S(e.filters,t);return{...e,filters:n}},C=(e,t,n)=>{let r=n.alias||n.relation;return[{...e,[r]:t}]},w=(e,t)=>{let n=new Map;return e.forEach(e=>{let r=e[t];n.has(r)||n.set(r,[]),n.get(r).push(e)}),n},ie=async(e,t,n,r)=>{try{if(te(n,e),!Array.isArray(t))throw new y(`Source data must be an array`,`INVALID_SOURCE_DATA`);let i=e[n.relation],a;return n.query?.filters&&b(n.query.filters)&&(a=w(i,n.query.filters.field)),(await Promise.all(t.map(async e=>{let t=re(n.query,e),o;return o=t.filters&&b(t.filters)&&a?.has(t.filters.value)?a.get(t.filters.value)||[]:i.filter(e=>r.matcher(e,t.filters)),C(e,await[e=>t.sort?r.sorter(e,t.sort):e,e=>t.projection?r.projector(e,t.projection):e,async e=>t.pagination?await r.paginator(e,t.pagination):e].reduce(async(e,t)=>t(await e),Promise.resolve(o)),n)}))).flat()}catch(e){throw e instanceof y?e:new y(`Join operation failed: ${e.message}`,`JOIN_EXECUTION_ERROR`)}},T=async(e,t,n,r)=>n.reduce(async(t,n)=>ie(e,await t,n,r),Promise.resolve(t));function ae(){return{join:T}}var E=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name=`UnsupportedComparisonError`}},D=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name=`InvalidSortDirectionError`}};function oe(e,t,n){if(e===t)return 0;if(e==null||t==null)return e==null?n===`asc`?-1:1:n===`asc`?1:-1;if(typeof e==`string`&&typeof t==`string`)return n===`asc`?e.localeCompare(t):t.localeCompare(e);if(typeof e==`number`&&typeof t==`number`)return n===`asc`?e-t:t-e;throw new E(e,t)}function se(e,t){let n=Array.from(e);return t.length===0?n:n.sort((e,n)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],o=n[t];try{if(i!==`asc`&&i!==`desc`)throw new D(i);let e=oe(a,o,i);if(e!==0)return e}catch(e){throw e instanceof E||e instanceof D?e:Error(`Error comparing field '${t}': ${e.message}`)}}return 0})}function O(){return{sort:se}}function ce(e){let{resolve:t}=d(e);function n(e,t,n){for(let r of t){if(typeof r==`string`){let t=r;n[t]=e[t];continue}for(let[t,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=a(e[t],i))}}function r(e,t,n){Object.keys(n).length===0&&Object.assign(n,e);for(let e of t){if(typeof e==`string`){let t=e;delete n[t];continue}for(let[t,r]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&typeof e==`object`?n[t]=a(e,r):delete n[t]}}}function i(e,n,r){for(let i of n)r[i.alias]=t(e,i)}function a(e,t){let a={};return t.include?.length&&n(e,t.include,a),t.exclude?.length&&r(e,t.exclude,a),t.computed?.length&&i(e,t.computed,a),a}return{project:a}}async function*le(e,t,n=e=>String(e)){t.type===`offset`?yield*k(e,t):yield*A(e,t,n)}function ue(){return{paginate:le}}async function*k(e,t){let{offset:n,limit:r}=t,i=0,a=r,o=[];for await(let t of e){if(a<=0&&(yield o,o=[],a=r),i<n){i++;continue}o.push(t),a--}o.length>0&&(yield o)}async function*A(e,t,n){let{cursor:r,limit:i,direction:a}=t,o=i,s=r===void 0,c=[];if(a===`forward`)for await(let t of e){if(o<=0&&(yield c,c=[],o=i),!s){s=n(t)===r;continue}c.push(t),o--}else{let t=[];for await(let n of e)t.push(n);for(let e=t.length-1;e>=0;e--){let a=t[e];if(!s){s=n(a)===r;continue}c.push(a),o--,o<=0&&(yield c,c=[],o=i)}}c.length>0&&(yield c)}0&&(t.exports={QueryBuilder,createJoiner,createMatcher,createPaginator,createProjector,createSorter})})),ne=e(((e,t)=>{t.exports=n;function n(e){var t,n;if(typeof e!=`function`)throw Error(`expected a function but got `+e);return function(){return t?n:(t=!0,n=e.apply(this,arguments),n)}}})),S=e(((e,t)=>{t.exports={encode:e=>new Uint8Array(Buffer.from(e,`utf8`)),decode:e=>Buffer.from(e).toString(`utf8`)}})),re=e(((e,t)=>{t.exports=n;function n(e,t,n){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,o=n&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!o)return e.apply(i,a)},t),o)return e.apply(this,arguments)}}})),C=e(((e,t)=>{function n(e){if(e.length===0)return`.`;let t=a(e);return t=t.reduce(c,[]),i(...t)}function r(...e){let t=``;for(let r of e)t=r.startsWith(`/`)?r:n(i(t,r));return t}function i(...e){if(e.length===0)return``;let t=e.join(`/`);return t=t.replace(/\/{2,}/g,`/`),t}function a(e){if(e.length===0)return[];if(e===`/`)return[`/`];let t=e.split(`/`);return t[t.length-1]===``&&t.pop(),e[0]===`/`?t[0]=`/`:t[0]!==`.`&&t.unshift(`.`),t}function o(e){let t=e.lastIndexOf(`/`);if(t===-1)throw Error(`Cannot get dirname of "${e}"`);return t===0?`/`:e.slice(0,t)}function s(e){if(e===`/`)throw Error(`Cannot get basename of "${e}"`);let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function c(e,t){if(e.length===0)return e.push(t),e;if(t===`.`)return e;if(t===`..`){if(e.length===1){if(e[0]===`/`)throw Error(`Unable to normalize path - traverses above root directory`);if(e[0]===`.`)return e.push(t),e}return e[e.length-1]===`..`?(e.push(`..`),e):(e.pop(),e)}return e.push(t),e}t.exports={join:i,normalize:n,split:a,basename:s,dirname:o,resolve:r}})),w=e(((e,t)=>{function n(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+`: `+this.message:this.message=e}}}t.exports={EEXIST:n(`EEXIST`),ENOENT:n(`ENOENT`),ENOTDIR:n(`ENOTDIR`),ENOTEMPTY:n(`ENOTEMPTY`),ETIMEDOUT:n(`ETIMEDOUT`),EISDIR:n(`EISDIR`)}})),ie=e(((e,t)=>{let n=C(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:o,EISDIR:s}=w();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:`dir`,size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){e===null?this._root=new Map([[`/`,this._makeRoot()]]):typeof e==`string`?this._root=new Map([[`/`,this._makeRoot(this.parse(e))]]):this._root=e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get(`/`))-1}_countInodes(e){let t=1;for(let[n,r]of e)n!==0&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get(`/`))+1}_maxInode(e){let t=e.get(0).ino;for(let[n,r]of e)n!==0&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get(`/`)){let t=``,n=(e,r)=>{for(let[i,a]of e){if(i===0)continue;let e=a.get(0),o=e.mode.toString(8);t+=`${` `.repeat(r)}${i}\t${o}`,e.type===`file`?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);let t=require("@asaidimu/utils-sync"),n=require("buffer"),r=require("@asaidimu/utils-events"),i=require("uuid"),a=function(e){return e.SCHEMA_NOT_FOUND=`SCHEMA_NOT_FOUND`,e.SCHEMA_ALREADY_EXISTS=`SCHEMA_ALREADY_EXISTS`,e.INVALID_SCHEMA_NAME=`INVALID_SCHEMA_NAME`,e.INVALID_SCHEMA_DEFINITION=`INVALID_SCHEMA_DEFINITION`,e.SUBSCRIPTION_FAILED=`SUBSCRIPTION_FAILED`,e.INTERNAL_ERROR=`INTERNAL_ERROR`,e.INVALID_DATA=`INVALID_DATA`,e.CONFLICT=`CONFLICT`,e.TRANSIENT_ERROR=`TRANSIENT_ERROR`,e.TRANSACTION_FAILED=`TRANSACTION_FAILED`,e.CONNECTION_FAILED=`CONNECTION_FAILED`,e.INVALID_OPERATION=`INVALID_OPERATION`,e}({});var o=class extends Error{type;schema;issues;constructor(e,t,n,r,i){super(t,{cause:r}),this.name=`DatabaseError`,this.type=e,this.schema=n,this.issues=i}};function s(e){if(typeof e!=`object`||!e||Array.isArray(e))return[e,{}];let t={};return[Object.entries(e).reduce((e,[n,r])=>(n.startsWith(`$`)?t[n]=r:e[n]=r,e),{}),t]}function c(e,t){if(!(!e||e.$version===void 0||t.$version===void 0)&&t.$version<=e.$version)throw new o(`CONFLICT`,`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function l(e,t){let n=[];for(let r of t.fields){let t=e[r];if(t==null)return null;n.push(String(t))}return n.join(`\0`)}function u(e,t){if(!t.partial)return!0;let{field:n,value:r}=t.partial;return e[n]===r}var d=class{storeName;keyPath;data=new Map;indexes=new Map;nextId=1;constructor(e,t=`$id`,n=[]){this.storeName=e,this.keyPath=t;for(let e of n)this.indexes.set(e.name,{definition:e,map:new Map})}name(){return this.storeName}async open(){}_snapshotMemory(){let e=new Map;for(let[t,n]of this.data)e.set(t,{...n});let t=new Map;for(let[e,n]of this.indexes){let r=new Map;for(let[e,t]of n.map)r.set(e,new Set(t));t.set(e,{definition:n.definition,map:r})}return{data:e,indexes:t,nextId:this.nextId}}_rollbackMemory(e){this.data=e.data,this.indexes=e.indexes,this.nextId=e.nextId}async createIndex(e){if(this.indexes.has(e.name))return;let t={definition:e,map:new Map};this.indexes.set(e.name,t);for(let e of this.data.values())this.indexOne(t,e)}async dropIndex(e){this.indexes.delete(e)}async getByIndex(e,t){return(await this.findByIndex(e,t))[0]}async findByIndex(e,t){let n=this.indexes.get(e);if(!n)throw new o(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=String(t),i=n.map.get(r);if(!i||i.size===0)return[];let a=[];for(let e of i){let t=this.data.get(e);t&&a.push(this.clone(t))}return a}async getByKeyRange(e,t){let n=this.indexes.get(e);if(!n)throw new o(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=[];for(let[e,i]of n.map.entries())if(this.isInKeyRange(e,t))for(let e of i){let t=this.data.get(e);t&&r.push(this.clone(t))}return r}async add(e){let t=Array.isArray(e)?e:[e],n=[];for(let e of t){let t=e[this.keyPath];if((t===void 0||t===``)&&(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new o(`CONFLICT`,`Duplicate key ${t}`);this.enforceUniqueIndexes(e,void 0);let r=Object.freeze(this.clone(e));this.data.set(t,r),this.indexDocument(r),n.push(t)}return Array.isArray(e)?n:n[0]}async put(e){let t=this.getKey(e),n=this.data.get(t);c(n,e),this.enforceUniqueIndexes(e,n),n&&this.unindexDocument(n);let r=Object.freeze(this.clone(e));return this.data.set(t,r),this.indexDocument(r),t}async batch(e){let t=new Map,n=e=>t.has(e)?t.get(e):this.data.get(e);for(let r of e)if(r.type===`add`||r.type===`put`){let e=Array.isArray(r.data)?r.data:[r.data];for(let i of e){let e;if(r.type===`add`){if(e=i[this.keyPath],(e===void 0||e===``)&&(e=String(this.nextId++),i[this.keyPath]=e),n(e)!=null)throw new o(`CONFLICT`,`Duplicate key ${e}`)}else e=this.getKey(i);c(n(e)??void 0,i),t.set(e,Object.freeze(this.clone(i)))}}else{let e=Array.isArray(r.data)?r.data:[r.data];for(let n of e)t.set(n,null)}for(let[e,n]of t.entries()){let t=this.data.get(e);t&&this.unindexDocument(t),n===null?this.data.delete(e):(this.enforceUniqueIndexes(n,t),this.data.set(e,n),this.indexDocument(n))}}async delete(e){let t=Array.isArray(e)?e:[e];for(let e of t){let t=this.data.get(e);t&&this.unindexDocument(t),this.data.delete(e)}}async clear(){this.data.clear();for(let e of this.indexes.values())e.map.clear()}async executeInTransaction(e,t){if(t!==null)throw new o(`INTERNAL_ERROR`,`executeInTransaction called on MemoryStore '${this.storeName}' with a non-null sharedTx`);for(let t of e)if(t.type===`add`)await this.add(t.data);else if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.put(t)}else await this.delete(t.data)}async getById(e){let t=this.data.get(e);return t?this.clone(t):void 0}async getAll(){return Array.from(this.data.values()).map(e=>this.clone(e))}async count(){return this.data.size}async cursor(e,t=`forward`,n){let r=Array.from(this.data.entries());n&&(r=r.filter(([e])=>this.isInKeyRange(e,n)));let i=r.sort(([e],[t])=>e>t?1:e<t?-1:0);t===`backward`&&i.reverse();let a=null,o=0;for(;o<i.length;){let[t,n]=i[o],{value:r,done:s,offset:c}=await e(this.clone(n),t,null);if(a=r,s)break;o+=c&&c>0?c:1}return a}getKey(e){let t=e[this.keyPath];if(t==null)throw new o(`INVALID_DATA`,`Record must have a '${this.keyPath}' property`);return t}clone(e){return{...e}}indexDocument(e){for(let t of this.indexes.values())this.indexOne(t,e)}indexOne(e,t){if(!u(t,e.definition))return;let n=l(t,e.definition);if(n===null)return;let r=t[this.keyPath];if(r===void 0)return;let i=e.map.get(n);i||(i=new Set,e.map.set(n,i)),i.add(r)}unindexDocument(e){let t=e[this.keyPath];if(t!==void 0)for(let n of this.indexes.values()){let r=l(e,n.definition);if(r===null)continue;let i=n.map.get(r);i&&(i.delete(t),i.size===0&&n.map.delete(r))}}enforceUniqueIndexes(e,t){let n=e[this.keyPath],r=t?t[this.keyPath]:void 0;for(let t of this.indexes.values()){if(!t.definition.unique||!u(e,t.definition))continue;let i=l(e,t.definition);if(i===null)continue;let a=t.map.get(i);if(!(!a||a.size===0)){for(let e of a)if(!(e===n||e===r))throw new o(`CONFLICT`,`Unique index '${t.definition.name}' violation: value already exists for field(s) [${t.definition.fields.join(`, `)}]`)}}}isInKeyRange(e,t){if(!t)return!0;let{lower:n,upper:r,lowerOpen:i=!1,upperOpen:a=!1}=t;return(n===void 0||(i?e>n:e>=n))&&(r===void 0||(a?e<r:e<=r))}};function f(e){return new d(e.database,e.keyPath)}var p=class{config;connectionInitializer=new t.Once({retry:!0,throws:!0});schemasStoreName;constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||`schemas`}async openDatabase(){return new Promise((e,t)=>{let n=indexedDB.open(this.config.database);n.onerror=()=>t(Error(`Failed to open database: ${n.error?.message}`)),n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:`name`})},n.onsuccess=()=>e(n.result)})}async upgradeDatabase(e,t){let n=e.version+1;return e.close(),new Promise((e,r)=>{let i=indexedDB.open(this.config.database,n);i.onerror=()=>r(Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{let n=e.target.result,r=e.target.transaction;t(n,r)},i.onsuccess=()=>e(i.result)})}async ensureStore(e,t=`$id`,n=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade(r=>{if(r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:`name`}),!r.objectStoreNames.contains(e)){let i=r.createObjectStore(e,{keyPath:t});for(let e of n){let t=e.fields.length===1?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}})}async createStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);if(i.indexNames.contains(t.name))return;let a=t.fields.length===1?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})})}async dropStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)})}getConnection=async()=>{let e=await this.connectionInitializer.do(async()=>{let e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e});if(e.error)throw new o(`CONNECTION_FAILED`,`Failed to open database: ${this.config.database}`,void 0,e.error);return e.value};async openTransaction(e,t=`readwrite`){return(await this.getConnection()).transaction(e,t)}async upgrade(e){let t=await this.getConnection();this.connectionInitializer.reset();let n=await this.connectionInitializer.do(async()=>await this.upgradeDatabase(t,e));if(n.error)throw new o(`INTERNAL_ERROR`,`Database upgrade failed for ${this.config.database}`,void 0,n.error);return n.value}close(){let e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function m(e){if(e){if(e.lower!==void 0&&e.upper!==void 0)return IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen);if(e.lower!==void 0)return IDBKeyRange.lowerBound(e.lower,e.lowerOpen);if(e.upper!==void 0)return IDBKeyRange.upperBound(e.upper,e.upperOpen)}}var h=class{connectionManager;collection;keyPath;indexes;constructor(e,t,n=`$id`,r=[]){this.connectionManager=e,this.collection=t,this.keyPath=n,this.indexes=r}name(){return this.collection}async _getIDBConnection(){return this.connectionManager.getConnection()}async open(){await this.connectionManager.ensureStore(this.collection,this.keyPath,this.indexes)}async createIndex(e){await this.connectionManager.createStoreIndex(this.collection,e)}async dropIndex(e){await this.connectionManager.dropStoreIndex(this.collection,e)}async getByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.get(t))})}async getByKeyRange(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.getAll(m(t)))})}async findByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))})}async put(e){return this.withTx(`readwrite`,async t=>{let n=e[this.keyPath];return n!==void 0&&c(await this.requestToPromise(t.get(n)),e),this.requestToPromise(t.put(e))})}async add(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e],r=[];for(let e of n){let n=await this.requestToPromise(t.add(e));r.push(n)}return Array.isArray(e)?r:r[0]})}async batch(e){return this.withTx(`readwrite`,async t=>{for(let n of e)if(n.type===`put`||n.type===`add`){let e=Array.isArray(n.data)?n.data:[n.data];for(let r of e)if(n.type===`put`){let e=r[this.keyPath];e!==void 0&&c(await this.requestToPromise(t.get(e)),r),await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{let e=Array.isArray(n.data)?n.data:[n.data];for(let n of e)await this.requestToPromise(t.delete(n))}})}async delete(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e];for(let e of n)await this.requestToPromise(t.delete(e))})}async clear(){return this.withTx(`readwrite`,async e=>{await this.requestToPromise(e.clear())})}async executeInTransaction(e,t){if(!t)throw new o(`INTERNAL_ERROR`,`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);let n=t.objectStore(this.collection);for(let t of e)if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e){let e=t[this.keyPath];e!==void 0&&c(await this.requestToPromise(n.get(e)),t),await this.requestToPromise(n.put(t))}}else if(t.type===`add`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.add(t))}else{let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.delete(t))}}async getById(e){return this.withTx(`readonly`,async t=>this.requestToPromise(t.get(e)))}async getAll(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.getAll()))}async count(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.count()))}async cursor(e,t=`forward`,n){return this.withTx(`readonly`,async r=>{let i=t===`forward`?`next`:`prev`,a=r.openCursor(m(n),i);return new Promise((t,n)=>{let r=null;a.onsuccess=async i=>{let a=i.target.result;if(!a)return t(r);try{let{value:n,done:i,offset:o}=await e(a.value,a.key,a);r=n,i?t(r):o&&o>0?a.advance(o):a.continue()}catch(e){n(e)}},a.onerror=()=>n(this.mapError(a.error))})})}mapError(e){if(e instanceof o)return e;let t=e?.message||`Unknown IndexedDB Error`,n=e?.name||``;return n===`QuotaExceededError`?new o(`INTERNAL_ERROR`,`Storage quota exceeded`):n===`VersionError`?new o(`CONFLICT`,t):n===`InvalidStateError`||n===`TransactionInactiveError`?new o(`TRANSIENT_ERROR`,t):new o(`INTERNAL_ERROR`,t)}async withTx(e,t){let n=await this.connectionManager.getConnection();return new Promise(async(r,i)=>{let a=n.transaction(this.collection,e),o=a.objectStore(this.collection),s,c;a.oncomplete=()=>{c?i(c):r(s)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{let e=t(o,a);s=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch{}}})}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}};const g=new Map,_=e=>{let n=g.get(e.database);n||(n=new t.Once({retry:!0,throws:!0}),g.set(e.database,n));try{let{value:t,error:r}=n.doSync(()=>new p(e));if(r)throw new o(`CONNECTION_FAILED`,`Failed to initialize connection for database: ${e.database}`,void 0,r);return new h(t,e.collection,e.keyPath)}catch(e){throw e instanceof o?e:new o(`CONNECTION_FAILED`,e instanceof Error?e.message:`An unexpected connection error occurred`,void 0,e)}};var v=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{createEventBus:()=>u}),t.exports=c(l);var u=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error(`EventBus Error:`,e),crossTab:!1,channelName:`event-bus-channel`})=>{let t=new Map,n=[],r=0,i=0,a=new Map,o=new Map,s=null;e.crossTab&&typeof BroadcastChannel<`u`?s=new BroadcastChannel(e.channelName):e.crossTab&&console.warn(`BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.`);let c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{let t=n;n=[],t.forEach(({name:t,payload:n})=>{let r=performance.now();try{(o.get(t)||[]).forEach(e=>e(n))}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-r)})},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{let n=t.get(e);n?o.set(e,Array.from(n)):o.delete(e)};return s&&(s.onmessage=e=>{let{name:t,payload:n}=e.data;(o.get(t)||[]).forEach(e=>e(n))}),{subscribe:(e,n)=>{t.has(e)||t.set(e,new Set);let r=t.get(e);return r.add(n),d(e),()=>{r.delete(n),r.size===0?(t.delete(e),o.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async){n.push({name:t,payload:r}),n.length>=e.batchSize?l():u(),s&&s.postMessage({name:t,payload:r});return}let i=performance.now();try{(o.get(t)||[]).forEach(e=>e(r)),s&&s.postMessage({name:t,payload:r})}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:r,activeSubscriptions:Array.from(t.values()).reduce((e,t)=>e+t.size,0),eventCounts:a,averageEmitDuration:r>0?i/r:0}),clear:()=>{t.clear(),o.clear(),n=[],r=0,i=0,a.clear(),s&&=(s.close(),null)}}};0&&(t.exports={createEventBus:u})})),y=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{QueryBuilder:()=>u,createJoiner:()=>ae,createMatcher:()=>v,createPaginator:()=>A,createProjector:()=>k,createSorter:()=>O}),t.exports=c(l);var u=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:`offset`,offset:e,limit:t},this}cursor(e,t,n){return this.query.pagination={type:`cursor`,cursor:e,limit:t,direction:n},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`computed`,expression:e,alias:t}),this}case(e,t,n){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`case`,conditions:e,else:t,alias:n}),this}join(e,t,n){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:n,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function d(e){function t(e,t){return f(t)?e[t.field]:p(t)?t.value:g(t)?i(t,e):m(t)?i(t.expression,e):h(t)?a(e,t):t}let n=new Map([[`and`,(e,t)=>t.every(t=>o(e,t))],[`or`,(e,t)=>t.some(t=>o(e,t))],[`not`,(e,t)=>!t.every(t=>o(e,t))],[`nor`,(e,t)=>!t.some(t=>o(e,t))],[`xor`,(e,t)=>t.filter(t=>o(e,t)).length===1]]);function r(e,t){let{operator:r,conditions:i}=t,a=n.get(r);if(a)return a(e,i);throw Error(`Unsupported logical operator: ${r}`)}function i(n,r){let i=n.arguments.map(e=>t(r,e));if(e[n.function])return e[n.function](...i);throw Error(`Function ${n.function} not found!`)}function a(e,t){for(let n of t.conditions)if(o(e,n.when))return n.then;return t.else}function o(n,i){if(_(i))return r(n,i);if(!i||!i.field)return!1;let{field:a,operator:o,value:s}=i,c=n[a],l=t(n,s),u=new Map([[`eq`,(e,t)=>e===t],[`neq`,(e,t)=>e!==t],[`lt`,(e,t)=>e<t],[`lte`,(e,t)=>e<=t],[`gt`,(e,t)=>e>t],[`gte`,(e,t)=>e>=t],[`in`,(e,t)=>Array.isArray(t)&&t.includes(e)],[`nin`,(e,t)=>Array.isArray(t)&&!t.includes(e)],[`contains`,(e,t)=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.includes(s):!1],[`ncontains`,(e,t)=>typeof e==`string`&&!e.includes(t)],[`startswith`,(e,t)=>typeof e==`string`&&e.startsWith(t)],[`endswith`,(e,t)=>typeof e==`string`&&e.endsWith(t)],[`exists`,e=>e!=null],[`nexists`,e=>e==null]]),d=e[o]||u.get(o);if(d)return d(c,l);throw Error(`Unsupported comparison operator: ${o}`)}return{resolve:t,evaluate:o}}function f(e){return e?.type===`field`}function p(e){return e?.type===`value`}function m(e){return e?.type===`computed`}function h(e){return e?.type===`case`}function g(e){return e?.type===`function`}function _(e){return e?e.conditions!==void 0:!1}function v(e){let{evaluate:t}=d(e),n=new WeakMap;function r(e,r){let i=n.get(e);i||(i=new Map,n.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let o=t(e,r);return i.set(a,o),o}return{matcher:r,match:r}}var y=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`JoinError`}},b=e=>e&&`field`in e&&`operator`in e&&`value`in e,ee=e=>`operator`in e&&`conditions`in e,x=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`field`,S=(e,t)=>{if(!e.relation)throw new y(`Join configuration must specify a relation`,`INVALID_CONFIG`);if(!t[e.relation])throw new y(`Collection "${e.relation}" not found in database`,`COLLECTION_NOT_FOUND`);if(e.alias&&typeof e.alias!=`string`)throw new y(`Join alias must be a string`,`INVALID_ALIAS`)},C=(e,t)=>t.split(`.`).reduce((e,t)=>e?.[t],e),w=(e,t)=>{if(e){if(b(e)&&e){let n=x(e.value)?C(t,e.value.field):e.value;return{...e,value:n}}if(ee(e)){let n={...e};return e.conditions&&(n.conditions=e.conditions.map(e=>w(e,t))),n}return e}},T=(e,t)=>{if(!e)return{};let n=w(e.filters,t);return{...e,filters:n}},te=(e,t,n)=>{let r=n.alias||n.relation;return[{...e,[r]:t}]},ne=(e,t)=>{let n=new Map;return e.forEach(e=>{let r=e[t];n.has(r)||n.set(r,[]),n.get(r).push(e)}),n},re=async(e,t,n,r)=>{try{if(S(n,e),!Array.isArray(t))throw new y(`Source data must be an array`,`INVALID_SOURCE_DATA`);let i=e[n.relation],a;return n.query?.filters&&b(n.query.filters)&&(a=ne(i,n.query.filters.field)),(await Promise.all(t.map(async e=>{let t=T(n.query,e),o;return o=t.filters&&b(t.filters)&&a?.has(t.filters.value)?a.get(t.filters.value)||[]:i.filter(e=>r.matcher(e,t.filters)),te(e,await[e=>t.sort?r.sorter(e,t.sort):e,e=>t.projection?r.projector(e,t.projection):e,async e=>t.pagination?await r.paginator(e,t.pagination):e].reduce(async(e,t)=>t(await e),Promise.resolve(o)),n)}))).flat()}catch(e){throw e instanceof y?e:new y(`Join operation failed: ${e.message}`,`JOIN_EXECUTION_ERROR`)}},ie=async(e,t,n,r)=>n.reduce(async(t,n)=>re(e,await t,n,r),Promise.resolve(t));function ae(){return{join:ie}}var E=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name=`UnsupportedComparisonError`}},D=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name=`InvalidSortDirectionError`}};function oe(e,t,n){if(e===t)return 0;if(e==null||t==null)return e==null?n===`asc`?-1:1:n===`asc`?1:-1;if(typeof e==`string`&&typeof t==`string`)return n===`asc`?e.localeCompare(t):t.localeCompare(e);if(typeof e==`number`&&typeof t==`number`)return n===`asc`?e-t:t-e;throw new E(e,t)}function se(e,t){let n=Array.from(e);return t.length===0?n:n.sort((e,n)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],o=n[t];try{if(i!==`asc`&&i!==`desc`)throw new D(i);let e=oe(a,o,i);if(e!==0)return e}catch(e){throw e instanceof E||e instanceof D?e:Error(`Error comparing field '${t}': ${e.message}`)}}return 0})}function O(){return{sort:se}}function k(e){let{resolve:t}=d(e);function n(e,t,n){for(let r of t){if(typeof r==`string`){let t=r;n[t]=e[t];continue}for(let[t,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=a(e[t],i))}}function r(e,t,n){Object.keys(n).length===0&&Object.assign(n,e);for(let e of t){if(typeof e==`string`){let t=e;delete n[t];continue}for(let[t,r]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&typeof e==`object`?n[t]=a(e,r):delete n[t]}}}function i(e,n,r){for(let i of n)r[i.alias]=t(e,i)}function a(e,t){let a={};return t.include?.length&&n(e,t.include,a),t.exclude?.length&&r(e,t.exclude,a),t.computed?.length&&i(e,t.computed,a),a}return{project:a}}async function*ce(e,t,n=e=>String(e)){t.type===`offset`?yield*le(e,t):yield*j(e,t,n)}function A(){return{paginate:ce}}async function*le(e,t){let{offset:n,limit:r}=t,i=0,a=r,o=[];for await(let t of e){if(a<=0&&(yield o,o=[],a=r),i<n){i++;continue}o.push(t),a--}o.length>0&&(yield o)}async function*j(e,t,n){let{cursor:r,limit:i,direction:a}=t,o=i,s=r===void 0,c=[];if(a===`forward`)for await(let t of e){if(o<=0&&(yield c,c=[],o=i),!s){s=n(t)===r;continue}c.push(t),o--}else{let t=[];for await(let n of e)t.push(n);for(let e=t.length-1;e>=0;e--){let a=t[e];if(!s){s=n(a)===r;continue}c.push(a),o--,o<=0&&(yield c,c=[],o=i)}}c.length>0&&(yield c)}0&&(t.exports={QueryBuilder,createJoiner,createMatcher,createPaginator,createProjector,createSorter})})),b=e(((e,t)=>{t.exports=n;function n(e){var t,n;if(typeof e!=`function`)throw Error(`expected a function but got `+e);return function(){return t?n:(t=!0,n=e.apply(this,arguments),n)}}})),ee=e(((e,t)=>{t.exports={encode:e=>new Uint8Array(Buffer.from(e,`utf8`)),decode:e=>Buffer.from(e).toString(`utf8`)}})),x=e(((e,t)=>{t.exports=n;function n(e,t,n){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,o=n&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!o)return e.apply(i,a)},t),o)return e.apply(this,arguments)}}})),S=e(((e,t)=>{function n(e){if(e.length===0)return`.`;let t=a(e);return t=t.reduce(c,[]),i(...t)}function r(...e){let t=``;for(let r of e)t=r.startsWith(`/`)?r:n(i(t,r));return t}function i(...e){if(e.length===0)return``;let t=e.join(`/`);return t=t.replace(/\/{2,}/g,`/`),t}function a(e){if(e.length===0)return[];if(e===`/`)return[`/`];let t=e.split(`/`);return t[t.length-1]===``&&t.pop(),e[0]===`/`?t[0]=`/`:t[0]!==`.`&&t.unshift(`.`),t}function o(e){let t=e.lastIndexOf(`/`);if(t===-1)throw Error(`Cannot get dirname of "${e}"`);return t===0?`/`:e.slice(0,t)}function s(e){if(e===`/`)throw Error(`Cannot get basename of "${e}"`);let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function c(e,t){if(e.length===0)return e.push(t),e;if(t===`.`)return e;if(t===`..`){if(e.length===1){if(e[0]===`/`)throw Error(`Unable to normalize path - traverses above root directory`);if(e[0]===`.`)return e.push(t),e}return e[e.length-1]===`..`?(e.push(`..`),e):(e.pop(),e)}return e.push(t),e}t.exports={join:i,normalize:n,split:a,basename:s,dirname:o,resolve:r}})),C=e(((e,t)=>{function n(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+`: `+this.message:this.message=e}}}t.exports={EEXIST:n(`EEXIST`),ENOENT:n(`ENOENT`),ENOTDIR:n(`ENOTDIR`),ENOTEMPTY:n(`ENOTEMPTY`),ETIMEDOUT:n(`ETIMEDOUT`),EISDIR:n(`EISDIR`)}})),w=e(((e,t)=>{let n=S(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:o,EISDIR:s}=C();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:`dir`,size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){e===null?this._root=new Map([[`/`,this._makeRoot()]]):typeof e==`string`?this._root=new Map([[`/`,this._makeRoot(this.parse(e))]]):this._root=e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get(`/`))-1}_countInodes(e){let t=1;for(let[n,r]of e)n!==0&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get(`/`))+1}_maxInode(e){let t=e.get(0).ino;for(let[n,r]of e)n!==0&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get(`/`)){let t=``,n=(e,r)=>{for(let[i,a]of e){if(i===0)continue;let e=a.get(0),o=e.mode.toString(8);t+=`${` `.repeat(r)}${i}\t${o}`,e.type===`file`?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+=`
2
2
  `,n(a,r+1))}};return n(e,0),t}parse(e){let t=0;function n(e){let n=++t,r=e.length===1?`dir`:`file`,[i,a,o]=e;return i=parseInt(i,8),a=a?parseInt(a):0,o=o?parseInt(o):Date.now(),new Map([[0,{mode:i,type:r,size:a,mtimeMs:o,ino:n}]])}let r=e.trim().split(`
3
- `),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of r){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[r,...i]=e.split(` `),o=n(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:o}),a[a.length-2].node.set(r,o)}return i}_lookup(e,t=!0){let r=this._root,a=`/`,o=n.split(e);for(let s=0;s<o.length;++s){let c=o[s];if(r=r.get(c),!r)throw new i(e);if(t||s<o.length-1){let e=r.get(0);if(e.type===`symlink`){let t=n.resolve(a,e.target);r=this._lookup(t)}a=a?n.join(a,c):c}}return r}mkdir(e,{mode:t}){if(e===`/`)throw new r;let i=this._lookup(n.dirname(e)),a=n.basename(e);if(i.has(a))throw new r;let o=new Map,s={mode:t,type:`dir`,size:0,mtimeMs:Date.now(),ino:this.autoinc()};o.set(0,s),i.set(a,o)}rmdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;if(t.size>1)throw new o;let r=this._lookup(n.dirname(e)),i=n.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;return[...t.keys()].filter(e=>typeof e==`string`)}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch{}if(a!==void 0){if(a.type===`dir`)throw new s;r??=a.mode,i=a.ino}r??=438,i??=this.autoinc();let o=this._lookup(n.dirname(e)),c=n.basename(e),l={mode:r,type:`file`,size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,l),o.set(c,u),l}unlink(e){let t=this._lookup(n.dirname(e)),r=n.basename(e);t.delete(r)}rename(e,t){let r=n.basename(t),i=this._lookup(e);this._lookup(n.dirname(t)).set(r,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let r,i;try{let e=this.stat(t);i===null&&(i=e.mode),r=e.ino}catch{}i??=40960,r??=this.autoinc();let a=this._lookup(n.dirname(t)),o=n.basename(t),s={mode:i,type:`symlink`,target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,s),a.set(o,c),s}_du(e){let t=0;for(let[n,r]of e.entries())n===0?t+=r.size:t+=this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}})),T=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class{constructor(e=`keyval-store`,t=`keyval`){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||=new Promise((e,t)=>{let n=indexedDB.open(this._dbName);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=()=>{n.result.createObjectStore(this._storeName)}})}_withIDBStore(e,t){return this._init(),this._dbp.then(n=>new Promise((r,i)=>{let a=n.transaction(this.storeName,e);a.oncomplete=()=>r(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(e=>{e.close(),this._dbp=void 0})}};let n;function r(){return n||=new t,n}function i(e,t=r()){let n;return t._withIDBStore(`readwrite`,t=>{n=t.get(e)}).then(()=>n.result)}function a(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{n.put(t,e)})}function o(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{let r=n.get(e);r.onsuccess=()=>{n.put(t(r.result),e)}})}function s(e,t=r()){return t._withIDBStore(`readwrite`,t=>{t.delete(e)})}function c(e=r()){return e._withIDBStore(`readwrite`,e=>{e.clear()})}function l(e=r()){let t=[];return e._withIDBStore(`readwrite`,e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function u(e=r()){return e._close()}e.Store=t,e.get=i,e.set=a,e.update=o,e.del=s,e.clear=c,e.keys=l,e.close=u})),ae=e(((e,t)=>{let n=T();t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename)}saveSuperblock(e){return n.set(`!root`,e,this._store)}loadSuperblock(){return n.get(`!root`,this._store)}readFile(e){return n.get(e,this._store)}writeFile(e,t){return n.set(e,t,this._store)}unlink(e){return n.del(e,this._store)}wipe(){return n.clear(this._store)}close(){return n.close(this._store)}}})),E=e(((e,t)=>{t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+`/.superblock.txt`).then(e=>e.ok?e.text():null)}async readFile(e){let t=await fetch(this._url+e);if(t.status===200)return t.arrayBuffer();throw Error(`ENOENT`)}async sizeFile(e){let t=await fetch(this._url+e,{method:`HEAD`});if(t.status===200)return t.headers.get(`content-length`);throw Error(`ENOENT`)}}})),D=e(((e,t)=>{let n=T(),r=e=>new Promise(t=>setTimeout(t,e));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){let t=Date.now();return this._lock.expires>t+e?!0:await this.renew()}else return!1}async renew({ttl:e=5e3}={}){let t;return await n.update(`lock`,n=>{let r=Date.now()+e;return t=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:r}:n,this._lock},this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await n.update(`lock`,n=>{let a=Date.now(),o=a+e;return r=n&&n.expires<a,t=n===void 0||r,i=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:o}:n,this._lock},this._store),i)throw Error(`Mutex double-locked`);return t}async wait({interval:e=100,limit:t=6e3,ttl:n}={}){for(;t--;){if(await this.acquire({ttl:n}))return!0;await r(e)}throw Error(`Mutex timeout`)}async release({force:e=!1}={}){let t,r,i;if(await n.update(`lock`,n=>(t=e||n&&n.holder===this._id,r=n===void 0,i=n&&n.holder!==this._id,this._lock=t?void 0:n,this._lock),this._store),await n.close(this._store),!t&&!e){if(r)throw Error(`Mutex double-freed`);if(i)throw Error(`Mutex lost ownership`)}return t}}})),oe=e(((e,t)=>{t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(e=>{navigator.locks.request(this._database+`_lock`,{ifAvailable:!0},t=>(this._has=!!t,e(!!t),new Promise(e=>{this._release=e})))})}async wait({timeout:e=6e5}={}){return new Promise((t,n)=>{let r=new AbortController;setTimeout(()=>{r.abort(),n(Error(`Mutex timeout`))},e),navigator.locks.request(this._database+`_lock`,{signal:r.signal},e=>(this._has=!!e,t(!!e),new Promise(e=>{this._release=e})))})}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+`_lock`,{steal:!0},e=>!0)}}})),se=e(((e,t)=>{let{encode:n,decode:r}=S(),i=re(),a=ie(),{ENOENT:o,ENOTEMPTY:s,ETIMEDOUT:c}=w(),l=ae(),u=E(),d=D(),f=oe(),p=C();t.exports=class{constructor(){this.saveSuperblock=i(()=>{this.flush()},500)}async init(e,{wipe:t,url:n,urlauto:r,fileDbName:i=e,db:o=null,fileStoreName:s=e+`_files`,lockDbName:c=e+`_lock`,lockStoreName:p=e+`_lock`}={}){this._name=e,this._idb=o||new l(i,s),this._mutex=navigator.locks?new f(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:n},this._needsWipe=!!t,n&&(this._http=new u(n),this._urlauto=!!r)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();let e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){let e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,n){let r=p.split(p.dirname(e)),i=r.shift();for(let e of r){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch{}}return this._cache.writeStat(e,t,n)}async readFile(e,t){let n=typeof t==`string`?t:t&&t.encoding;if(n&&n!==`utf8`)throw Error(`Only "utf8" encoding is supported in readFile`);let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;t.type===`symlink`;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&((!a||a.size!=i.byteLength)&&(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),n===`utf8`?i=r(i):i.toString=()=>r(i)),!a)throw new o(e);return i}async writeFile(e,t,r){let{mode:i,encoding:a=`utf8`}=r;if(typeof t==`string`){if(a!==`utf8`)throw Error(`Only "utf8" encoding is supported in writeFile`);t=n(t)}let o=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(o.ino,t)}async unlink(e,t){let n=this._cache.lstat(e);this._cache.unlink(e),n.type!==`symlink`&&await this._idb.unlink(n.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){let{mode:n=511}=t;this._cache.mkdir(e,{mode:n})}rmdir(e,t){if(e===`/`)throw new s;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let n=await this._http.sizeFile(e);await this._writeStat(e,n,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}})),O=e(((e,t)=>{t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return this.type===`file`}isDirectory(){return this.type===`dir`}isSymbolicLink(){return this.type===`symlink`}}})),ce=e(((e,t)=>{let n=se(),r=O(),i=C();function a(e,t,...n){return e=i.normalize(e),(t===void 0||typeof t==`function`)&&(t={}),typeof t==`string`&&(t={encoding:t}),[e,t,...n]}function o(e,t,n,...r){return e=i.normalize(e),(n===void 0||typeof n==`function`)&&(n={}),typeof n==`string`&&(n={encoding:n}),[e,t,n,...r]}function s(e,t,...n){return[i.normalize(e),i.normalize(t),...n]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,o,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,s,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,s,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new n,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&=(this._initPromiseResolve(),null),t.defer||this.stat(`/`)}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(e=>this._gracefulShutdownResolve=e),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,n){return async(...r)=>{r=t(...r);let i={name:e.name,args:r};this._operations.add(i);try{return await this._activate(),await e.apply(this,r)}finally{this._operations.delete(i),n&&this._backend.saveSuperblock(),this._operations.size===0&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&=(clearTimeout(this._deactivationTimeout),null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||=this._backend.activate?this._backend.activate():Promise.resolve(),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||=this._backend.deactivate?this._backend.deactivate():Promise.resolve(),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,n){return await this._backend.writeFile(e,t,n),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){return new r(await this._backend.stat(e,t))}async lstat(e,t){return new r(await this._backend.lstat(e,t))}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}})),le=e(((e,t)=>{let n=ne(),r=ce();function i(e,t){return typeof e==`function`&&(t=e),t=n(t),[(...e)=>t(null,...e),t]}t.exports=class{constructor(...e){this.promises=new r(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,n){let[r,a]=i(t,n);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,n,r){let[a,o]=i(n,r);this.promises.writeFile(e,t,n).then(a).catch(o)}unlink(e,t,n){let[r,a]=i(t,n);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,n){let[r,a]=i(t,n);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,n){let[r,a]=i(t,n);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,n){let[r,a]=i(t,n);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,n){let[r,a]=i(n);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,n){let[r,a]=i(t,n);this.promises.stat(e).then(r).catch(a)}lstat(e,t,n){let[r,a]=i(t,n);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,n){let[r,a]=i(t,n);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,n){let[r,a]=i(n);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,n){let[r,a]=i(t,n);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){let[n,r]=i(t);this.promises.du(e).then(n).catch(r)}flush(e){let[t,n]=i(e);this.promises.flush().then(t).catch(n)}}}));x();var ue=te();le();var k=class extends Error{constructor(e,t){super(e),this.operation=t,this.name=`JsonPatchError`}};function A(e){let t=de(e);return t===``?[]:t.substring(1).split(`/`).map(pe)}function de(e){return e===``||e===`/`?``:e.startsWith(`/`)?`/`+e.substring(1).split(`/`).map(fe).join(`/`):`/`+e.split(`.`).map(fe).join(`/`)}function fe(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function pe(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}var j=new Map;function M(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)throw new k(`Invalid path - parent not found at ${e}`);if(Array.isArray(n)){let t=e===`-`?n.length:parseInt(e);if(isNaN(t)||t<0||t>n.length)throw new k(`Invalid array index: ${e}`);n=n[t]}else{if(!n.hasOwnProperty(e))throw new k(`Property ${e} not found`);n=n[e]}}return n}function N(e,t){let n=j.get(t)||A(t);if(j.set(t,n),n.length===0)return e;let r=M(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new k(`Invalid array index: ${i}`);return r[e]}return r[i]}function me(e,t,n){let r=j.get(t)||A(t);j.set(t,r);let i=M(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter(e=>e!==n)):i[a]===n&&delete i[a],e}function P(e,t,n){let r=j.get(t)||A(t);if(j.set(t,r),r.length===0)return n;let i=r.slice(0,-1),a=r[r.length-1],o=M(e,i);if(Array.isArray(o))if(a===`-`)o.push(n);else{let e=parseInt(a);if(e<0||e>o.length)throw new k(`Invalid array index: ${a}`);o.splice(e,0,n)}else o[a]=n;return e}function F(e,t){let n=j.get(t)||A(t);if(j.set(t,n),n.length===0)return;let r=M(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);r.splice(e,1)}else delete r[i];return e}function he(e,t){let n=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case`add`:n=P(n,e.path,e.value);break;case`remove`:n=F(n,e.path);break;case`removeValue`:n=me(n,e.path,e.value);break;case`replace`:n=P(F(n,e.path),e.path,e.value);break;case`copy`:{let t=N(n,e.from);n=P(n,e.path,JSON.parse(JSON.stringify(t)));break}case`move`:{let t=N(n,e.from);n=P(n,e.path,t),n=F(n,e.from);break}case`test`:{let t=N(n,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new k(`Test operation failed`);break}default:throw new k(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof k&&(t.operation=e),t}return n}function ge(e,t){let n=[];switch(e.type){case`addField`:n.push({op:`add`,path:`/fields/${e.id}`,value:e.definition});break;case`removeField`:n.push({op:`remove`,path:`/fields/${e.id}`});break;case`modifyField`:{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach(([e,r])=>{n.push({op:`replace`,path:`${t}/${e}`,value:r})});break}case`deprecateField`:n.push({op:`add`,path:`/fields/${e.id}/deprecated`,value:!0});break;case`addIndex`:t.indexes||n.push({op:`add`,path:`/indexes`,value:[]}),n.push({op:`add`,path:`/indexes/-`,value:e.definition});break;case`removeIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/indexes/${r}`});break}case`modifyIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`/indexes/${r}/${e}`,value:t})});break}case`addConstraint`:t.constraints||n.push({op:`add`,path:`/constraints`,value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(e=>{n.push({op:`add`,path:`/constraints/-`,value:e})}):n.push({op:`add`,path:`/constraints/-`,value:e.constraint});break;case`removeConstraint`:{let r=t.constraints?.findIndex(t=>Array.isArray(t)?t.some(t=>t.name===e.name):t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/constraints/${r}`});break}case`modifyConstraint`:{let r=_e(t,e.name);r&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`${r}/${e}`,value:t})});break}}return n}function _e(e,t){if(!e.constraints)return null;for(let n=0;n<e.constraints.length;n++){let r=e.constraints[n];if(r.name===t)return`/constraints/${n}`;if(ve(r)){let e=ye(r.rules,t);if(e)return`/constraints/${n}${e}`}}return null}function ve(e){return e&&`operator`in e&&`rules`in e}function ye(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(`name`in r&&r.name===t)return`/rules/${n}`;if(ve(r)){let e=ye(r.rules,t);if(e)return`/rules/${n}${e}`}}return null}var I=new Map;function L(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function be(e,t){let n=e=>({value:e}),r=e=>({issues:e}),i=(e,t,n,r)=>{switch(t){case`string`:return typeof e==`string`?[]:[{message:`Expected string, got ${typeof e}`,path:n}];case`number`:return typeof e!=`number`||isNaN(e)?[{message:`Expected number, got ${typeof e}`,path:n}]:[];case`boolean`:return typeof e==`boolean`?[]:[{message:`Expected boolean, got ${typeof e}`,path:n}];case`array`:return Array.isArray(e)?[]:[{message:`Expected array, got ${typeof e}`,path:n}];case`set`:return!Array.isArray(e)||new Set(e).size!==e.length?[{message:`Expected unique array, got ${typeof e}`,path:n}]:[];case`enum`:return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:n}]:[{message:`Enum type requires 'values' definition`,path:n}];case`object`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected object, got ${typeof e}`,path:n}]:[];case`record`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];case`union`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected union (object), got ${typeof e}`,path:n}]:[];case`dynamic`:return console.warn(`Deprecated: 'dynamic' type used. Use 'record' instead.`),typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];default:return[{message:`Unknown type '${t}'`,path:n}]}};function a(e,t,n,r,i){let o=[],s=e.rules.map((e,s)=>{let c=[...r,`rules[${s}]`],l=`${e.name}@${c.join(`.`)}`;if(`rules`in e){if(i.has(l))return!0;i.add(l);let r=a(e,t,n,c,i);return o.push(...r),i.delete(l),r.length===0}else{let r=n[e.predicate];if(!r)return o.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(I.has(i)){let t=I.get(i);return t||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return I.set(i,a),a||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:c}),a}});return(()=>{switch(e.operator){case`and`:return s.every(e=>e);case`or`:return s.some(e=>e);case`not`:return!s.every(e=>e);case`nor`:return!s.some(e=>e);case`xor`:return s.filter(e=>e).length===1}})()||o.push({message:`Constraint group '${e.name}' failed`,path:r}),o}function o(e,t,n,r,s,c=new Set){let l=[];if(`type`in t&&!(`fields`in t)){let o=r.length>0?e[r[r.length-1]]:e;return l.push(...i(o,t.type,r,{values:t.values})),t.constraints&&t.constraints.forEach((e,t)=>{if(`rules`in e)l.push(...a(e,{value:o},n,[...r,`constraints[${t}]`],c));else{let i=n[e.predicate];i?i({data:{value:o},field:`value`,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:[...r,`constraints[${t}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...r,`constraints[${t}]`]})}}),l}let u={};if(`concrete`in t)if(t.concrete===!0||!Array.isArray(t.fields))u=t.fields;else{let n=t.fields,i=n.find(e=>!e.when);i&&Object.assign(u,i.fields);let a=n.find(t=>t.when&&e[t.when.field]!==void 0&&e[t.when.field]===t.when.value);if(a)Object.assign(u,a.fields);else if(!i)return l.push({message:`No matching field set found for discriminated schema`,path:r}),l}else u=t.fields;let d=new Set(Object.values(u).map(e=>e.name));Object.entries(u).forEach(([t,u])=>{let d=[...r,u.name],f=Object.hasOwnProperty.call(e,u.name)?e[u.name]:u.default===void 0?void 0:u.default;u.required&&f==null&&l.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if(u.type===`object`&&p&&!Array.isArray(p)){let e=s[p.id];if(e)if(c.has(p.id))l.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=f&&typeof f==`object`&&!Array.isArray(f)?f:{};l.push(...o(t,e,n,d,s,c)),p.constraints?.forEach((e,r)=>{if(`rules`in e)l.push(...a(e,t,n,[...d,`constraints[${r}]`],c));else{let i=n[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}),c.delete(p.id)}else l.push({message:`Nested schema '${p.id}' not found`,path:d})}if(u.type===`union`&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach((r,i)=>{let l=s[r.id];if(l)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,i.toString()]});else{c.add(r.id);let i=f&&typeof f==`object`&&!Array.isArray(f)?f:{},u=o(i,l,n,d,s,new Set(c));u.length===0&&f!==void 0?(e=!0,r.constraints?.forEach((r,o)=>{if(`rules`in r){let s=a(r,i,n,[...d,`constraints[${o}]`],c);s.length>0&&(e=!1,t.push(...s))}else{let a=n[r.predicate];a&&!a({data:i,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${o}]`]}))}})):f===void 0&&t.push(...u.filter(e=>e.message.includes(`is required`))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,i.toString()]})}),!e&&f!==void 0?(l.push({message:`Value does not match any union schema`,path:d}),l.push(...t)):f===void 0&&l.push(...t)}f!==void 0&&(l.push(...i(f,u.type,d,{values:u.values})),(u.type===`array`||u.type===`set`)&&Array.isArray(f)&&(u.constraints?.forEach((e,t)=>{let r=n[e.predicate];r&&!r({data:{[u.name]:f},field:u.name,arguments:e.parameters})&&l.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})}),u.itemsType&&f.forEach((e,t)=>l.push(...i(e,u.itemsType,[...d,t.toString()]))),p&&!Array.isArray(p)&&(s[p.id]?f.forEach((e,t)=>{typeof e==`object`&&e&&(c.has(p.id)?l.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),l.push(...o(e,s[p.id],n,[...d,t.toString()],s,c)),c.delete(p.id)))}):l.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach((t,r)=>{if(`rules`in t)l.push(...a(t,e,n,[...d,`constraints[${r}]`],c));else{let i=n[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${L(t.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}))});for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&l.push({message:`Unexpected field '${t}'`,path:[...r,t]});return t.constraints?.forEach((t,i)=>{if(`rules`in t)l.push(...a(t,e,n,[...r,`constraints[${i}]`],c));else{let a=n[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${L(t.parameters)}`,path:[...r,`constraints[${i}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...r,`constraints[${i}]`]})}}),l}return e.version!==`1.0.0`&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:i=>{if(typeof i!=`object`||!i)return r([{message:`Input must be an object`,path:[]}]);let a=i,s=o(a,e,t,[],e.nestedSchemas||{});return s.length>0?r(s):n(a)},types:{input:{},output:{}}}}}var R=class extends Error{constructor(e,t){super(e),this.errors=t,this.name=`SchemaValidationError`}},z=e=>({value:e}),B=e=>({issues:e}),V=(e,t,n=!0)=>e===void 0&&!n?[]:typeof e!=`string`||e.trim()===``?[{message:`Must be a non-empty string`,path:[t]}]:[],H=(e,t)=>{let n=[`string`,`number`,`boolean`,`array`,`set`,`enum`,`object`,`record`,`union`,`dynamic`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:e===`dynamic`?[{message:`Field type 'dynamic' is deprecated; use 'record' instead`,path:[t]}]:[]},xe=(e,t)=>{let n=[`normal`,`unique`,`btree`,`hash`,`spatial`,`fulltext`,`gi`,`expression`,`composite`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},Se=(e,t)=>{let n=[`and`,`or`,`not`,`nor`,`xor`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},U=(e,t,n=!1)=>e===void 0&&!n||typeof e==`boolean`?[]:[{message:`Must be a boolean`,path:[t]}],Ce=(e,t,n)=>[],W=(e,t,n)=>{let r=[],i=[`predicate`,`name`],a=[`type`,`predicate`,`field`,`parameters`,`name`,`description`,`errorMessage`],o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...V(e.name,`${n}.name`)),r.push(...V(e.predicate,`${n}.predicate`)),e.field!==void 0&&typeof e.field!=`string`&&r.push({message:`Field must be a string`,path:[`${n}.field`]}),e.parameters!==void 0&&r.push(...Ce(e.parameters,t,`${n}.parameters`)),r.push(...V(e.description,`${n}.description`,!1)),r.push(...V(e.errorMessage,`${n}.errorMessage`,!1)),r},G=(e,t,n)=>{let r=[],i=[`name`,`operator`,`rules`],a=i,o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...V(e.name,`${n}.name`)),r.push(...Se(e.operator,`${n}.operator`)),!Array.isArray(e.rules)||e.rules.length===0?r.push({message:`Rules must be a non-empty array`,path:[`${n}.rules`]}):e.rules.forEach((e,i)=>{`rules`in e?r.push(...G(e,t,`${n}.rules[${i}]`)):r.push(...W(e,t,`${n}.rules[${i}]`))}),r},K=(e,t,n)=>{if(!Array.isArray(e))return[{message:`Must be an array`,path:[n]}];let r=[];return e.forEach((e,i)=>{`rules`in e?r.push(...G(e,t,`${n}[${i}]`)):r.push(...W(e,t,`${n}[${i}]`))}),r},we=(e,t)=>{let n=[],r=[`operator`,`field`],i=[`operator`,`field`,`value`,`conditions`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...Se(e.operator,`${t}.operator`)),n.push(...V(e.field,`${t}.field`)),e.conditions!==void 0&&(Array.isArray(e.conditions)?e.conditions.forEach((e,r)=>n.push(...we(e,`${t}.conditions[${r}]`))):n.push({message:`Conditions must be an array`,path:[`${t}.conditions`]})),n},Te=(e,t)=>{let n=[],r=[`fields`,`type`,`name`],i=[`fields`,`type`,`unique`,`partial`,`description`,`order`,`name`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`)),n.push(...xe(e.type,`${t}.type`)),(!Array.isArray(e.fields)||e.fields.length===0||!e.fields.every(e=>typeof e==`string`))&&n.push({message:`Fields must be a non-empty array of strings`,path:[`${t}.fields`]}),n.push(...U(e.unique,`${t}.unique`,!1)),e.partial&&n.push(...we(e.partial,`${t}.partial`)),n.push(...V(e.description,`${t}.description`,!1)),e.order!==void 0&&![`asc`,`desc`].includes(e.order)&&n.push({message:`Order must be 'asc' or 'desc'`,path:[`${t}.order`]}),n},q=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e))return[{message:`Must be an array`,path:[t]}];let n=[];return e.forEach((e,r)=>n.push(...Te(e,`${t}[${r}]`))),n},Ee=(e,t,n,r,i)=>{let a=[];return e===void 0?[]:(n===`union`&&Array.isArray(e)?(e.length===0&&a.push({message:`Schema array must not be empty for union type`,path:[t]}),e.forEach((e,n)=>{let i=`${t}[${n}]`;a.push(...V(e.id,`${i}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...K(e.constraints,`dynamic`,`${i}.constraints`)),e.indexes&&a.push(...q(e.indexes,`${i}.indexes`))})):(n===`object`||n===`array`&&i===`object`)&&!Array.isArray(e)?(a.push(...V(e.id,`${t}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...K(e.constraints,`dynamic`,`${t}.constraints`)),e.indexes&&a.push(...q(e.indexes,`${t}.indexes`))):a.push({message:`Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'`,path:[t]}),a)},De=(e,t,n)=>{if(e===void 0)return[];switch(t){case`string`:if(typeof e!=`string`)return[{message:`Default must be a string`,path:[n]}];break;case`number`:if(typeof e!=`number`)return[{message:`Default must be a number`,path:[n]}];break;case`boolean`:if(typeof e!=`boolean`)return[{message:`Default must be a boolean`,path:[n]}];break;case`array`:case`set`:if(!Array.isArray(e))return[{message:`Default must be an array`,path:[n]}];break;case`enum`:if(!Array.isArray(e)||!e.every(e=>typeof e==`string`||typeof e==`number`))return[{message:`Default must be an array of strings or numbers`,path:[n]}];break;case`object`:case`record`:if(typeof e!=`object`||!e)return[{message:`Default must be an object`,path:[n]}];break;case`union`:case`dynamic`:return[]}return[]},Oe=(e,t)=>e===void 0?[]:typeof e!=`object`||!e?[{message:`Hint must be an object`,path:[t]}]:`input`in e&&typeof e.input!=`object`?[{message:`Hint.input must be an object`,path:[`${t}.input`]}]:[],J=(e,t,n)=>{let r=[],i=[`name`,`type`],a=[`name`,`type`,`required`,`constraints`,`default`,`values`,`schema`,`itemsType`,`nestedSchema`,`deprecated`,`reference`,`description`,`unique`,`hint`],o=e;if(i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...V(e.name,`${t}.name`)),r.push(...H(e.type,`${t}.type`)),r.push(...U(e.required,`${t}.required`,!1)),e.constraints&&r.push(...K(e.constraints,e.type,`${t}.constraints`)),r.push(...De(e.default,e.type,`${t}.default`)),e.values!==void 0&&(e.type===`enum`?(!Array.isArray(e.values)||e.values.length===0||!e.values.every(e=>typeof e==`string`||typeof e==`number`))&&r.push({message:`Values must be a non-empty array of strings or numbers`,path:[`${t}.values`]}):r.push({message:`Values is only valid for 'enum' type`,path:[`${t}.values`]})),e.schema!==void 0&&r.push(...Ee(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...H(e.itemsType,`${t}.itemsType`)),e.nestedSchema){r.push({message:`nestedSchema is deprecated; use schema instead`,path:[`${t}.nestedSchema`]});let i=[`id`],a=[`id`,`constraints`,`indexes`],o=e.nestedSchema;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})}),r.push(...V(e.nestedSchema.id,`${t}.nestedSchema.id`)),n.includes(e.nestedSchema.id)||r.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&r.push(...K(e.nestedSchema.constraints,`dynamic`,`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...q(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...U(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:`reference is deprecated`,path:[`${t}.reference`]});let n=[`schema`,`field`],i=[`schema`,`field`],a=e.reference;n.forEach(e=>{a[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})}),r.push(...V(e.reference.schema,`${t}.reference.schema`)),r.push(...V(e.reference.field,`${t}.reference.field`))}return r.push(...V(e.description,`${t}.description`,!1)),r.push(...U(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...Oe(e.hint,`${t}.hint`)),r},ke=(e,t,n)=>{let r=[];if(`type`in e&&[`string`,`number`,`boolean`,`array`,`set`,`enum`,`record`].includes(e.type)){let i=[`name`,`type`],a=[`name`,`type`,`default`,`schema`,`itemsType`,`constraints`,`description`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...V(e.name,`${t}.name`)),r.push(...H(e.type,`${t}.type`)),r.push(...De(e.default,e.type,`${t}.default`)),e.schema&&r.push(...Ee(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...H(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...K(e.constraints,e.type,`${t}.constraints`)),r.push(...V(e.description,`${t}.description`,!1)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}else{let i=[`name`],a=[`name`,`description`,`concrete`,`fields`,`indexes`,`constraints`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...V(e.name,`${t}.name`)),r.push(...U(o.concrete,`${t}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&r.push({message:`Fields must be an object when concrete is true`,path:[`${t}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&r.push({message:`Fields array must not be empty`,path:[`${t}.fields`]}),o.fields.forEach((e,i)=>{let a=`${t}.fields[${i}]`;if(typeof e!=`object`||!e||!(`fields`in e))r.push({message:`Each variant must have a 'fields' property`,path:[a]});else{let t=e.fields;typeof t!=`object`||!t?r.push({message:`Fields must be a non-empty object`,path:[`${a}.fields`]}):Object.entries(t).forEach(([e,t])=>{r.push(...J(t,`${a}.fields.${e}`,n))}),e.when!==void 0&&(typeof e.when!=`object`||e.when===null?r.push({message:`When must be an object`,path:[`${a}.when`]}):r.push(...V(e.when.field,`${a}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!=`object`||o.fields===null?r.push({message:`Fields must be a non-empty object`,path:[`${t}.fields`]}):Object.entries(o.fields).forEach(([e,i])=>{r.push(...J(i,`${t}.fields.${e}`,n))})),r.push(...V(e.description,`${t}.description`,!1)),e.indexes&&r.push(...q(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...K(o.constraints,`dynamic`,`${t}.constraints`)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}return r},Ae=e=>{if(typeof e!=`object`||!e)return B([{message:`Schema must be an object`,path:[]}]);let t=e,n=[],r=[`name`,`version`,`fields`],i=[`name`,`version`,`description`,`fields`,`nestedSchemas`,`indexes`,`constraints`,`metadata`,`dependencies`,`migrations`,`mock`,`hint`],a=t;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[e]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[e]})}),n.push(...V(t.name,`name`)),n.push(...V(t.version,`version`)),typeof t.fields!=`object`||t.fields===null)n.push({message:`Fields must be a non-empty object`,path:[`fields`]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach(([t,r])=>{n.push(...J(r,`fields.${t}`,e))})}if(t.nestedSchemas!==void 0)if(typeof t.nestedSchemas!=`object`||t.nestedSchemas===null)n.push({message:`NestedSchemas must be an object`,path:[`nestedSchemas`]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach(([t,r])=>n.push(...ke(r,`nestedSchemas.${t}`,e)))}return n.push(...V(t.description,`description`,!1)),t.indexes&&n.push(...q(t.indexes,`indexes`)),t.constraints&&n.push(...K(t.constraints,`dynamic`,`constraints`)),t.metadata!==void 0&&(typeof t.metadata!=`object`||t.metadata===null)&&n.push({message:`Metadata must be an object`,path:[`metadata`]}),t.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`dependencies`]})),t.migrations!==void 0&&(Array.isArray(t.migrations)?t.migrations.forEach((e,t)=>n.push(...Me(e,`migrations[${t}]`))):n.push({message:`Migrations must be an array`,path:[`migrations`]})),t.mock!==void 0&&typeof t.mock!=`function`&&n.push({message:`Mock must be a function`,path:[`mock`]}),t.hint&&n.push(...Oe(t.hint,`hint`)),n.length>0?B(n):z(t)},Y=(e,t)=>{let n=[];switch(e.type||n.push({message:`type is required`,path:[`${t}.type`]}),e.type){case`modifyProperty`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),(e.changes===void 0||typeof e.changes!=`object`)&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addField`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),n.push(...J(e.definition,`${t}.definition`,[]));break}case`removeField`:case`deprecateField`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`));break}case`modifyField`:{let r=[`type`,`id`,`changes`],i=[`type`,`id`,`changes`,`nestedSchemaChanges`],a=e;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]}),e.nestedSchemaChanges){let r=[`id`,`constraints`,`indexes`],i=e.nestedSchemaChanges;Object.keys(i).forEach(e=>{r.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})}),n.push(...V(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&n.push(...K(i.constraints,`dynamic`,`${t}.nestedSchemaChanges.constraints`)),i.indexes&&n.push(...q(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case`addIndex`:{let r=[`type`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...Te(e.definition,`${t}.definition`));break}case`removeIndex`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`));break}case`modifyIndex`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addConstraint`:{let r=[`type`,`constraint`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),`rules`in e.constraint?n.push(...G(e.constraint,`dynamic`,`${t}.constraint`)):n.push(...W(e.constraint,`dynamic`,`${t}.constraint`));break}case`removeConstraint`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`));break}case`modifyConstraint`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addNestedSchema`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),n.push(...ke(e.definition,`${t}.definition`,[]));break}case`removeNestedSchema`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`));break}case`modifyNestedSchema`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}default:n.push({message:`Unknown schema change type`,path:[`${t}.type`]})}return n},je=(e,t)=>{let n=[],r=[`forward`,`backward`],i=r,a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),typeof e.forward!=`function`&&n.push({message:`Forward must be a function`,path:[`${t}.forward`]}),typeof e.backward!=`function`&&n.push({message:`Backward must be a function`,path:[`${t}.backward`]}),n},Me=(e,t)=>{let n=[],r=[`id`,`schemaVersion`,`changes`,`description`,`status`,`transform`,`createdAt`,`checksum`],i=[...r,`rollback`,`dependencies`],a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),n.push(...V(e.schemaVersion,`${t}.schemaVersion`)),n.push(...V(e.description,`${t}.description`));let o=[`pending`,`applied`,`failed`];return o.includes(e.status)||n.push({message:`Status must be one of ${o.join(`, `)}`,path:[`${t}.status`]}),!Array.isArray(e.changes)||e.changes.length===0?n.push({message:`Changes must be a non-empty array`,path:[`${t}.changes`]}):e.changes.forEach((e,r)=>{n.push(...Y(e,`${t}.changes[${r}]`))}),e.rollback!==void 0&&(Array.isArray(e.rollback)?e.rollback.forEach((e,r)=>n.push(...Y(e,`${t}.rollback[${r}]`))):n.push({message:`Rollback must be an array`,path:[`${t}.rollback`]})),typeof e.transform==`string`?n.push(...V(e.transform,`${t}.transform`)):typeof e.transform==`object`&&e.transform!==null?n.push(...je(e.transform,`${t}.transform`)):n.push({message:`Transform must be a string or object`,path:[`${t}.transform`]}),n.push(...V(e.createdAt,`${t}.createdAt`)),n.push(...V(e.checksum,`${t}.checksum`)),e.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`${t}.dependencies`]})),n},Ne={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:Ae,types:{input:{},output:{}}}},Pe={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(typeof e!=`object`||!e)return B([{message:`Migration must be an object`,path:[]}]);let t=e,n=Me(t,``);return n.length>0?B(n):z(t)},types:{input:{},output:{}}}},Fe={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(!Array.isArray(e))return B([{message:`SchemaChanges must be an array`,path:[]}]);let t=e,n=[];return t.forEach((e,t)=>n.push(...Y(e,`[${t}]`))),n.length>0?B(n):z(t)},types:{input:[],output:[]}}};function Ie(e){try{return!Pe[`~standard`].validate(e).issues}catch(e){throw new R(`Invalid migration definition`,e instanceof Error?e:Error(String(e)))}}function Le(e){try{return!Fe[`~standard`].validate(e).issues}catch(e){throw new R(`Invalid schema change definition`,e instanceof Error?e:Error(String(e)))}}function Re(e){try{return!Ne[`~standard`].validate(e).issues}catch(e){throw new R(`Invalid schema definition`,e instanceof Error?e:Error(String(e)))}}var ze=async e=>{if(typeof window<`u`&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}else{let{createHash:t}=await import(`crypto`);return t(`sha256`).update(e).digest(`hex`)}};function Be(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}function Ve(e,t){if(t&&`field`in e&&e.field){let n=t.fields[e.field];if(n)return n.type}if(`parameters`in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]==`string`)return`string`;if(typeof t==`number`||Array.isArray(t)&&typeof t[0]==`number`)return`number`;if(typeof t==`boolean`)return`boolean`;if(typeof t==`object`&&t){if(`minItems`in t||`maxItems`in t)return`array`;if(`schema`in t)return`object`}}}function He(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function Ue(e,t,n){switch(n){case`string`:if(e instanceof RegExp&&t instanceof RegExp)return e.source!==t.source;if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`number`:if(typeof e==`object`&&typeof t==`object`&&`precision`in e&&`precision`in t)return t.precision<e.precision||(t.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`array`:if(typeof e==`object`&&typeof t==`object`&&`minItems`in e&&`maxItems`in e&&`minItems`in t&&`maxItems`in t)return t.minItems>e.minItems||t.maxItems<e.maxItems;break;case`object`:if(typeof e==`object`&&typeof t==`object`&&`schema`in e&&`schema`in t)return Object.keys(t.schema).length>Object.keys(e.schema).length;break}return!1}function We(e,t){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(t.operator&&n[t.operator]>n[e.operator]||t.rules&&t.rules.length>e.rules.length)}function Ge(e,t,n){if(!t)return!0;if(`rules`in t&&`rules`in e)return We(t,e);if(`predicate`in e&&e.predicate!==void 0)return!0;if(`parameters`in e&&e.parameters!==void 0){let r=Ve(t,n);return r?Ue(t.parameters,e.parameters,r):!0}return!1}function Ke(e,t){switch(e.type){case`removeField`:case`removeIndex`:return`major`;case`modifyField`:return He(e.changes)?`major`:e.changes.deprecated?`minor`:`patch`;case`modifyIndex`:return e.changes.unique!==void 0||e.changes.fields!==void 0?`major`:`minor`;case`addConstraint`:return`major`;case`removeConstraint`:return`minor`;case`modifyConstraint`:let n=t?.constraints?.find(t=>`name`in t&&t.name===e.name);return Ge(e.changes,n,t)?`major`:`minor`;case`addField`:case`addIndex`:case`deprecateField`:return`minor`;default:throw Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function qe(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case`addField`:if(n.has(a.id))throw Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case`removeField`:if(r.has(a.id))throw Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case`modifyField`:if(n.has(a.id))throw Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case`deprecateField`:if(n.has(a.id))throw Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id);break}}function Je(e){let t=new Set,n=new Set,r=new Set;for(let i of e)switch(i.type){case`addConstraint`:let e=i.constraint,a=(`name`in e,e.name);if(n.has(a))throw Error(`Cannot add previously removed constraint: ${a}`);if(t.has(a))throw Error(`Cannot add already modified constraint: ${a}`);r.add(a);break;case`removeConstraint`:if(r.has(i.name))throw Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw Error(`Cannot remove modified constraint: ${i.name}`);n.add(i.name);break;case`modifyConstraint`:if(n.has(i.name))throw Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name);break}}function Ye(e,t,n){if(t.length===0)throw Error(`No changes provided`);qe(t),Je(t);let r=Be(e),i=`patch`;for(let e of t){let t=Ke(e,n);if(t===`major`){i=`major`;break}else t===`minor`&&i===`patch`&&(i=`minor`)}switch(i){case`major`:return`${r.major+1}.0.0`;case`minor`:return`${r.major}.${r.minor+1}.0`;case`patch`:return`${r.major}.${r.minor}.${r.patch+1}`}}function X(e,t){let n=e=>e.split(`.`).map(e=>parseInt(e,10)||0),[r,i,a]=n(e),[o,s,c]=n(t);return r-o||i-s||a-c}var Z=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.migrationId=n,this.cause=r,this.name=`MigrationError`}},Xe=(e=>(e.INVALID_SCHEMA=`INVALID_SCHEMA`,e.INVALID_MIGRATION=`INVALID_MIGRATION`,e.CHECKSUM_MISMATCH=`CHECKSUM_MISMATCH`,e.TIMEOUT=`TIMEOUT`,e.MEMORY_LIMIT=`MEMORY_LIMIT`,e.CONCURRENT_OPERATION=`CONCURRENT_OPERATION`,e.TRANSFORM_ERROR=`TRANSFORM_ERROR`,e.VERSION_NOT_FOUND=`VERSION_NOT_FOUND`,e.CIRCULAR_DEPENDENCY=`CIRCULAR_DEPENDENCY`,e.STREAM_ERROR=`STREAM_ERROR`,e.ROLLBACK_ERROR=`ROLLBACK_ERROR`,e.MISSING_TRANSFORM=`MISSING_TRANSFORM`,e))(Xe||{}),Ze=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,n){try{if(!Re(e))throw new Z(`Invalid initial schema`,`INVALID_SCHEMA`);if(this.currentSchema=e,t){if(!t.every(e=>Ie(e)))throw new Z(`Invalid migration configuration`,`INVALID_MIGRATION`);this.migrations=t.sort((e,t)=>X(e.schemaVersion,t.schemaVersion))}n&&(this.history=n.sort((e,t)=>X(e.version,t.version)))}catch(e){throw e instanceof Z?e:new Z(`Failed to initialize MigrationEngine`,`INVALID_SCHEMA`,void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{return await ze(JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt}))}catch(t){throw new Z(`Checksum generation failed`,`CHECKSUM_MISMATCH`,e.id,t)}}async add(e){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);if(!e.changes?.length)throw new Z(`Migration must include changes`,`INVALID_MIGRATION`);try{e.changes.forEach(e=>Le(e))}catch(e){throw new Z(`Invalid schema changes`,`INVALID_MIGRATION`,void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:`pending`,rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:``};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,n,r){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(n,r);return{newSchema:a.reduce((e,t)=>{let r=n===`forward`?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)},i),dataPreview:await e.processMigrationList(t,n,a)}}catch(e){throw e instanceof Z?e:new Z(`Dry run failed`,`INVALID_SCHEMA`,void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(n=>{let r=e===`forward`?`pending`:`applied`,i=t?X(n.schemaVersion,t)>=0:!0;return n.status===r&&i}).sort((t,n)=>e===`forward`?t.id.localeCompare(n.id):n.id.localeCompare(t.id))}applySchemaChanges(e,t,n){try{let r=Ye(e.version,t);return t.map(t=>{try{return ge(t,e)}catch(e){throw new Z(`Invalid schema change`,`INVALID_SCHEMA`,n,e)}}).reduce((e,t)=>{try{return he(e,t)}catch(e){throw new Z(`Failed to apply patch`,`INVALID_SCHEMA`,n,e)}},{...e,version:r})}catch(e){throw e instanceof Z?e:new Z(`Schema update failed`,`INVALID_SCHEMA`,n,e)}}async prepareMigration(){let e=this.migrations.filter(e=>e.status===`pending`);return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema(`forward`);let r=await e.processMigrationList(t,`forward`,n);return this.markMigrationsApplied(n),r}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new Z(`Checksum mismatch`,`CHECKSUM_MISMATCH`,e.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(e=>e.id===t.id)?{...t,status:`applied`}:t)}async rollback(e){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);return this.migrations.filter(e=>e.status===`applied`).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,n){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);try{let r=this.history.findIndex(e=>e.version===t);if(r===-1)throw Error(`Version ${t} not found in history`);let i=this.migrations.filter(e=>e.schemaVersion===t&&e.status===`applied`).sort((e,t)=>t.id.localeCompare(e.id)),a=this.history.length-r;if(a<0)return n;for(let e=0;e<a;e++)this.transformSchema(`backward`);let o=await e.processMigrationList(n,`backward`,i);return this.migrations=this.migrations.map(e=>e.schemaVersion===t&&e.status===`applied`?{...e,status:`pending`}:e),o}finally{this.isProcessing=!1}}static async processMigrationList(e,t,n){return(await Promise.all(n.map(async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Z(`Failed to resolve transform for migration ${e.id}`,`TRANSFORM_ERROR`,e.id,t)}}))).filter(e=>!!e.transform).reduce((e,{migration:t,transform:n})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await n(e);r.enqueue(t)}catch(e){r.error(new Z(`Data transformation failed for migration ${t.id}`,`TRANSFORM_ERROR`,t.id,e))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform==`string`?e.transform.startsWith(`http://`)||e.transform.startsWith(`https://`)?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let n=await fetch(e);if(!n.ok)throw new Z(`Failed to fetch transform module: ${e}`,`TRANSFORM_ERROR`,void 0);let r=await n.text();if(typeof window<`u`){let e=new Blob([r],{type:`application/javascript`});return(await import(URL.createObjectURL(e))).default[t]}else{let{runInNewContext:n}=await import(`vm`),i={module:{exports:{}},console};return n(r,i,e),i.module.exports[t]}}catch(t){throw new Z(`Failed to load remote transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new Z(`Failed to import local transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}transformSchema(e){try{if(e===`backward`){let e=this.history.pop();if(!e)throw Error(`No previous version`);this.currentSchema=e;return}let t=this.migrations.filter(e=>e.status===`pending`).flatMap(e=>e.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((e,t)=>this.applySchemaChanges(e,[t]),this.currentSchema)}catch(e){throw e instanceof Z?e:new Z(`Schema transformation failed`,`INVALID_SCHEMA`,void 0,e)}}};typeof window<`u`&&(window.Buffer=n.Buffer);var Qe=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let n=-1,r=i=>{if(i<=n)throw Error(`next() called multiple times`);n=i;let a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,()=>r(i+1))}catch(e){return Promise.reject(e)}};return r(0)}wrap(e,t){let n=this;return new Proxy(e,{get(e,r,i){let a=Reflect.get(e,r,i);return typeof a==`function`?function(...i){let o={...t,operation:r.toString(),args:i};return n.execute(o,()=>a.apply(e,i))}:a}})}};const $e=(e=3,t=100)=>async(n,r)=>{let i=0;for(;i<e;)try{return await r()}catch(n){if(n instanceof o&&n.type===`TRANSIENT_ERROR`){if(i++,i>=e)throw n;let r=t*2**i+Math.random()*50;await new Promise(e=>setTimeout(e,r))}else throw n}},et=async(e,t)=>{let n=Date.now();try{let r=await t();return tt(e,n,r,null),r}catch(t){throw tt(e,n,void 0,t),t}};function tt(e,t,n,r){if(!e.eventBus)return;let i=Date.now()-t;e.eventBus.emit({name:`telemetry`,payload:{type:`telemetry`,method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?`document`:e.collection?`collection`:`database`,collection:e.collection,document:e.documentId},result:r?void 0:{type:Array.isArray(n)?`array`:typeof n,size:Array.isArray(n)?n.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}async function nt(e,t){let{offset:n,limit:r}=t,i=[],a=0;return await e(async e=>a<n?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,i.length>=r?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1})),i}async function rt(e,t){let{limit:n,direction:r}=t,i=[];return await e(async e=>(i.push(e),i.length>=n?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1}),r),i}const{match:it}=(0,ue.createMatcher)({});async function Q(e){let{collection:t,initial:n,validator:r,store:a,bus:c,lockManager:l}=e,[u,d]=s(n),{value:f,issues:p}=r?await r[`~standard`].validate(u):{value:n,issues:void 0};if(p)throw new o(`INVALID_DATA`,`Invalid data for ${t}`,e.schema,p,p);let m={current:Object.assign(f,d),deleted:!1};m.current.$id===void 0&&(m.current=Object.assign(m.current,{$id:(0,i.v7)(),$created:new Date().toJSON(),$version:1}));let h=e=>{let[t]=s(e);return t},g={save:async e=>{await l.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let i=await a.getById(n);if(i&&i.$version!==r)throw new o(`CONFLICT`,`Version mismatch on ${t}/${n}`);return m.current.$version=(r||0)+1,m.current.$updated=new Date().toJSON(),e?await e.addOp(a,`put`,m.current):await a.put(m.current),c.emit({name:`document:write`,payload:{type:`document:write`,data:m.current,timestamp:Date.now()}}),!0}finally{l.unlock()}},update:async(n,i)=>{let[a,l]=s(Object.assign({},m.current,n)),{value:u,issues:d}=r?await r[`~standard`].validate(a):{value:a,issues:void 0};if(d)throw new o(`INVALID_DATA`,`Invalid update for ${t}`,e.schema,d,d);m.current=Object.assign(u,l);let f=await g.save(i);return f&&c.emit({name:`document:update`,payload:{type:`document:update`,data:m.current,timestamp:Date.now()}}),f},delete:async e=>{await l.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let i=await a.getById(n);if(i&&i.$version!==r)throw new o(`CONFLICT`,`Version mismatch on delete ${t}/${n}`);return e?await e.addOp(a,`delete`,n):await a.delete(n),c.emit({name:`document:delete`,payload:{type:`document:delete`,data:m.current,timestamp:Date.now()}}),m.deleted=!0,!0}finally{l.unlock()}},read:async()=>{let e=m.current.$id,t=await a.getById(e);if(!t)throw Error(`Document not found.`);return m.current={...t},c.emit({name:`document:read`,payload:{type:`document:read`,data:m.current,timestamp:Date.now()}}),m.current},state:()=>h(m.current),$metadata:()=>s(m.current)[1],subscribe:c.subscribe};return new Proxy({},{get(e,t){if([`update`,`delete`,`subscribe`,`read`,`state`,`save`,`$metadata`].includes(t)){let e=g[t];return(...t)=>{if(m.deleted)throw new o(`INVALID_OPERATION`,`Document has been deleted`);return e(...t)}}if(m.deleted)throw new o(`INVALID_OPERATION`,`Document has been deleted`);return Reflect.get(m.current,t)}})}function at(e,t){return`field`in e&&`operator`in e&&e.operator===`eq`&&`value`in e?e.field:null}async function ot({collection:e,validator:t,bus:n,store:r,pipeline:a,validate:c,schema:l}){let u=new h,d={collection:e,validator:c?t:void 0,schema:l,store:r,bus:n,pipeline:a,lockManager:u,valid:!0},f={async validate(e){let n=t[`~standard`].validate(e);return n instanceof Promise?await n:n},create:async(a,u)=>{let[f,p]=s(a),{value:m,issues:h}=c?await t[`~standard`].validate(f):{value:f,issues:void 0};if(h)throw new o(`INVALID_DATA`,`Invalid data for collection '${e}'`,l,h,h);let g=Object.assign(m,p,{$id:(0,i.v7)(),$created:new Date().toJSON(),$version:1});u?await u.addOp(r,`add`,g):await r.add(g),n.emit({name:`document:create`,payload:{type:`document:create`,data:g,timestamp:Date.now()}});let _=await Q({...d,initial:g});return n.emit({name:`collection:read`,payload:{type:`collection:read`,model:e,timestamp:Date.now()}}),_},find:async t=>{let i,a=at(t,r);if(a)try{let e=t.value;i=(await r.findByIndex(a,e))[0]}catch{i=void 0}if(i===void 0&&(i=await r.cursor(async e=>e&&it(e,t)?{value:e,done:!0}:{value:null,done:!1})??void 0),!i)return null;let o=await Q({...d,initial:i});return n.emit({name:`collection:read`,payload:{type:`collection:read`,method:`find`,model:e,timestamp:Date.now()}}),o},filter:async t=>{let i=[],a=at(t,r);if(a)try{let e=t.value;i=await r.findByIndex(a,e)}catch{i=[]}i.length===0&&await r.cursor(async e=>(e&&it(e,t)&&i.push(e),{value:null,done:!1}));let o=await Promise.all(i.map(e=>Q({...d,initial:e})));return n.emit({name:`collection:read`,payload:{type:`collection:read`,method:`filter`,model:e,timestamp:Date.now()}}),o},update:async(i,a,s)=>{await u.lock();try{let u=await f.filter(i);if(u.length===0)return 0;let d=[];for(let n of u){let r=n.state(),i=Object.assign({},r,a);if(c){let n=await t[`~standard`].validate(i);if(n.issues)throw new o(`INVALID_DATA`,`Bulk update failed validation for ${e}`,l,n.issues,n.issues)}let s=n.$metadata(),u=Object.assign(i,n.$metadata(),{$updated:new Date().toJSON(),$version:(s.$version||0)+1});d.push(u)}return s?await s.addOp(r,`put`,d):await r.batch(d.map(e=>({type:`put`,data:e}))),d.forEach(e=>{n.emit({name:`document:update`,payload:{type:`document:update`,data:e,timestamp:Date.now()}})}),d.length}finally{u.unlock()}},delete:async(e,t)=>{await u.lock();try{let i=await f.filter(e),a=i.map(e=>e.$id);return a.length===0?0:(t?await t.addOp(r,`delete`,a):await r.delete(a),i.forEach(e=>{n.emit({name:`document:delete`,payload:{type:`document:delete`,data:e.state(),timestamp:Date.now()}})}),a.length)}finally{u.unlock()}},list:async t=>{let i={total:await r.count(),offset:t.type===`offset`?t.offset:0,limit:t.limit,cursor:t.type===`cursor`?t.cursor:void 0,count:0};return i.total===0?{async next(){return{value:[],done:!0}}}:{async next(){let a=t.type===`offset`?await nt(r.cursor.bind(r),{...t,offset:i.offset}):await rt(r.cursor.bind(r),{...t,cursor:i.cursor});i.offset+=i.limit,i.count+=a.length;let o=await Promise.all(a.map(e=>Q({...d,initial:e})));return n.emit({name:`collection:read`,payload:{type:`collection:read`,method:`list`,model:e,timestamp:Date.now()}}),{value:o,done:i.count>=i.total}}}}},p={...a.wrap(f,{collection:e,eventBus:n}),subscribe:n.subscribe,invalidate:()=>d.valid=!1};return new Proxy(p,{get(t,n,r){let i=Reflect.get(t,n,r);return typeof i==`function`?(...r)=>{if(!d.valid&&n!==`invalidate`)throw new o(`INVALID_OPERATION`,`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}function st(e){return typeof e._getIDBConnection==`function`}var ct=class{id;staged=[];done=!1;constructor(){this.id=(0,i.v7)()}async addOp(e,t,n){if(this.done)throw new o(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);this.staged.push({store:e,op:{type:t,data:n}})}async commit(){if(this.done)throw new o(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);if(this.done=!0,this.staged.length===0)return;let e=new Map,t=new Map;for(let{store:n,op:r}of this.staged)st(n)?(e.has(n)||e.set(n,[]),e.get(n).push(r)):(t.has(n)||t.set(n,[]),t.get(n).push(r));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){let t=Array.from(e.keys()).map(e=>e.name()),n=await e.keys().next().value._getIDBConnection();await new Promise((r,i)=>{let a=n.transaction(t,`readwrite`);a.oncomplete=()=>r(),a.onerror=()=>i(a.error??Error(`IDB transaction error`)),a.onabort=()=>i(a.error??Error(`IDB transaction aborted`)),(async()=>{try{for(let[t,n]of e)await t.executeInTransaction(n,a)}catch(e){try{a.abort()}catch{}i(e)}})()})}async commitMemory(e){let t=[];try{for(let[n,r]of e){let e=n._snapshotMemory();t.push({store:n,snapshot:e}),await n.executeInTransaction(r,null)}}catch(e){for(let{store:e,snapshot:n}of t)try{e._rollbackMemory(n)}catch{}throw e}}completed(){return this.done}};function lt(e,t,n){let r,i=!1;return new ReadableStream({async pull(a){if(i){a.close();return}let o=0,s=r===void 0?void 0:{lower:r,lowerOpen:!0};try{await t.cursor(async(e,t)=>(a.enqueue(e),r=t,o++,o>=n?{done:!0,value:e}:{done:!1,value:e}),`forward`,s),o<n&&(i=!0)}catch(t){a.error($(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}async function ut(e,t,n,r){let i=t.getReader(),a=[];try{for(;;){let{value:e,done:t}=await i.read();if(t)break;if(!e)continue;let{$version:o}=e;e.$version=(o||0)+1,e.$updated=new Date().toJSON(),a.push(e),a.length>=r&&(await n.batch([{type:`put`,data:a}]),a=[])}a.length>0&&await n.batch([{type:`put`,data:a}])}catch(t){throw $(t,e)}finally{i.releaseLock()}}function $(e,t){return e instanceof o?e:e instanceof Error?new o(`INTERNAL_ERROR`,`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new o(`INTERNAL_ERROR`,`An unexpected error occurred during migration of collection '${t}'`)}async function dt(e,t){let n=(0,r.createEventBus)(),i=new Map,a=new Qe;a.use($e()),e.enableTelemetry&&a.use(et);let s=new Map,c=t({...e,collection:`schemas`,keyPath:`name`},[]);await c.open();async function l(n,r=[]){let i=s.get(n);return i||(i=t({...e,collection:n,keyPath:`$id`},r),s.set(n,i)),await i.open(),i}async function u(t){if(i.has(t))return i.get(t);let r=await c.getById(t);if(!r)throw new o(`SCHEMA_NOT_FOUND`,`Collection '${t}' does not exist`);let s=await l(t,r.indexes??[]),u=await ot({collection:t,bus:n,validator:be(r,e.predicates||{}),validate:!!e.validate,store:s,pipeline:a,schema:r});return n.emit({name:`collection:read`,payload:{type:`collection:read`,schema:{name:t},timestamp:Date.now()}}),i.set(t,u),i.get(t)}async function d(e){return await c.put(e),n.emit({name:`collection:update`,payload:{type:`collection:update`,schema:e,timestamp:Date.now()}}),!0}let f={collection:u,createCollection:async e=>{if(await c.getById(e.name))throw new o(`SCHEMA_ALREADY_EXISTS`,`Collection '${e.name}' already exists`);if(!Re(e))throw new o(`INVALID_SCHEMA_DEFINITION`,`Invalid schema definition`);await c.put(e);let t=u(e.name);return n.emit({name:`collection:create`,payload:{type:`collection:create`,schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{let t=await c.getById(e);if(!t)throw new o(`SCHEMA_NOT_FOUND`,`Collection '${e}' does not exist`);return await(await l(e,t.indexes??[])).clear(),s.delete(e),await c.delete(e),i.delete(e),n.emit({name:`collection:delete`,payload:{type:`collection:delete`,schema:t,timestamp:Date.now()}}),!0},updateCollection:d,migrateCollection:async(e,t,n=100)=>{let r=i.get(e);r&&(r.invalidate(),i.delete(e));let a=await c.getById(e);if(!a)throw new o(`SCHEMA_NOT_FOUND`,`Schema for '${e}' not found`);let s=await l(e,a.indexes??[]),f=new Ze(a);await f.add(t);let p=(await f.dryRun(new ReadableStream({start(e){e.close()}}),`forward`)).newSchema,m=new Set((a.indexes??[]).map(e=>e.name)),h=p.indexes??[],g=new Set(h.map(e=>e.name)),_=h.filter(e=>!m.has(e.name)),v=(a.indexes??[]).filter(e=>!g.has(e.name));await d(p);try{let t=lt(e,s,n);await ut(e,await f.migrate(t),s,n)}catch(t){throw $(t,e)}for(let e of _)await s.createIndex(e);for(let e of v)await s.dropIndex(e.name);return await u(e)}},p=a.wrap(f,{eventBus:n}),m={...p,transaction:async e=>{let t=new ct;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:n.subscribe,close:()=>{s.clear(),n.clear()},clear:async()=>{await c.clear(),await Promise.all(s.values().map(e=>e.clear())),s.clear()},ensureCollection:async e=>{try{await p.createCollection(e)}catch(e){if(e instanceof o&&e.type===`SCHEMA_ALREADY_EXISTS`)return;throw e}},setupCollections:async e=>{for(let t of e)await m.ensureCollection(t)}};return m}exports.ConnectionManager=_,exports.DEFAULT_KEYPATH=`$id`,exports.DatabaseConnection=dt,exports.DatabaseError=o,exports.DatabaseErrorType=a,exports.IndexedDBStore=y,exports.createDocument=Q,exports.createEphemeralStore=f,exports.createIndexedDbStore=ee,exports.openCollection=ot;
3
+ `),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of r){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[r,...i]=e.split(` `),o=n(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:o}),a[a.length-2].node.set(r,o)}return i}_lookup(e,t=!0){let r=this._root,a=`/`,o=n.split(e);for(let s=0;s<o.length;++s){let c=o[s];if(r=r.get(c),!r)throw new i(e);if(t||s<o.length-1){let e=r.get(0);if(e.type===`symlink`){let t=n.resolve(a,e.target);r=this._lookup(t)}a=a?n.join(a,c):c}}return r}mkdir(e,{mode:t}){if(e===`/`)throw new r;let i=this._lookup(n.dirname(e)),a=n.basename(e);if(i.has(a))throw new r;let o=new Map,s={mode:t,type:`dir`,size:0,mtimeMs:Date.now(),ino:this.autoinc()};o.set(0,s),i.set(a,o)}rmdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;if(t.size>1)throw new o;let r=this._lookup(n.dirname(e)),i=n.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;return[...t.keys()].filter(e=>typeof e==`string`)}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch{}if(a!==void 0){if(a.type===`dir`)throw new s;r??=a.mode,i=a.ino}r??=438,i??=this.autoinc();let o=this._lookup(n.dirname(e)),c=n.basename(e),l={mode:r,type:`file`,size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,l),o.set(c,u),l}unlink(e){let t=this._lookup(n.dirname(e)),r=n.basename(e);t.delete(r)}rename(e,t){let r=n.basename(t),i=this._lookup(e);this._lookup(n.dirname(t)).set(r,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let r,i;try{let e=this.stat(t);i===null&&(i=e.mode),r=e.ino}catch{}i??=40960,r??=this.autoinc();let a=this._lookup(n.dirname(t)),o=n.basename(t),s={mode:i,type:`symlink`,target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,s),a.set(o,c),s}_du(e){let t=0;for(let[n,r]of e.entries())n===0?t+=r.size:t+=this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}})),T=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class{constructor(e=`keyval-store`,t=`keyval`){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||=new Promise((e,t)=>{let n=indexedDB.open(this._dbName);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=()=>{n.result.createObjectStore(this._storeName)}})}_withIDBStore(e,t){return this._init(),this._dbp.then(n=>new Promise((r,i)=>{let a=n.transaction(this.storeName,e);a.oncomplete=()=>r(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(e=>{e.close(),this._dbp=void 0})}};let n;function r(){return n||=new t,n}function i(e,t=r()){let n;return t._withIDBStore(`readwrite`,t=>{n=t.get(e)}).then(()=>n.result)}function a(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{n.put(t,e)})}function o(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{let r=n.get(e);r.onsuccess=()=>{n.put(t(r.result),e)}})}function s(e,t=r()){return t._withIDBStore(`readwrite`,t=>{t.delete(e)})}function c(e=r()){return e._withIDBStore(`readwrite`,e=>{e.clear()})}function l(e=r()){let t=[];return e._withIDBStore(`readwrite`,e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function u(e=r()){return e._close()}e.Store=t,e.get=i,e.set=a,e.update=o,e.del=s,e.clear=c,e.keys=l,e.close=u})),te=e(((e,t)=>{let n=T();t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename)}saveSuperblock(e){return n.set(`!root`,e,this._store)}loadSuperblock(){return n.get(`!root`,this._store)}readFile(e){return n.get(e,this._store)}writeFile(e,t){return n.set(e,t,this._store)}unlink(e){return n.del(e,this._store)}wipe(){return n.clear(this._store)}close(){return n.close(this._store)}}})),ne=e(((e,t)=>{t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+`/.superblock.txt`).then(e=>e.ok?e.text():null)}async readFile(e){let t=await fetch(this._url+e);if(t.status===200)return t.arrayBuffer();throw Error(`ENOENT`)}async sizeFile(e){let t=await fetch(this._url+e,{method:`HEAD`});if(t.status===200)return t.headers.get(`content-length`);throw Error(`ENOENT`)}}})),re=e(((e,t)=>{let n=T(),r=e=>new Promise(t=>setTimeout(t,e));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){let t=Date.now();return this._lock.expires>t+e?!0:await this.renew()}else return!1}async renew({ttl:e=5e3}={}){let t;return await n.update(`lock`,n=>{let r=Date.now()+e;return t=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:r}:n,this._lock},this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await n.update(`lock`,n=>{let a=Date.now(),o=a+e;return r=n&&n.expires<a,t=n===void 0||r,i=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:o}:n,this._lock},this._store),i)throw Error(`Mutex double-locked`);return t}async wait({interval:e=100,limit:t=6e3,ttl:n}={}){for(;t--;){if(await this.acquire({ttl:n}))return!0;await r(e)}throw Error(`Mutex timeout`)}async release({force:e=!1}={}){let t,r,i;if(await n.update(`lock`,n=>(t=e||n&&n.holder===this._id,r=n===void 0,i=n&&n.holder!==this._id,this._lock=t?void 0:n,this._lock),this._store),await n.close(this._store),!t&&!e){if(r)throw Error(`Mutex double-freed`);if(i)throw Error(`Mutex lost ownership`)}return t}}})),ie=e(((e,t)=>{t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(e=>{navigator.locks.request(this._database+`_lock`,{ifAvailable:!0},t=>(this._has=!!t,e(!!t),new Promise(e=>{this._release=e})))})}async wait({timeout:e=6e5}={}){return new Promise((t,n)=>{let r=new AbortController;setTimeout(()=>{r.abort(),n(Error(`Mutex timeout`))},e),navigator.locks.request(this._database+`_lock`,{signal:r.signal},e=>(this._has=!!e,t(!!e),new Promise(e=>{this._release=e})))})}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+`_lock`,{steal:!0},e=>!0)}}})),ae=e(((e,t)=>{let{encode:n,decode:r}=ee(),i=x(),a=w(),{ENOENT:o,ENOTEMPTY:s,ETIMEDOUT:c}=C(),l=te(),u=ne(),d=re(),f=ie(),p=S();t.exports=class{constructor(){this.saveSuperblock=i(()=>{this.flush()},500)}async init(e,{wipe:t,url:n,urlauto:r,fileDbName:i=e,db:o=null,fileStoreName:s=e+`_files`,lockDbName:c=e+`_lock`,lockStoreName:p=e+`_lock`}={}){this._name=e,this._idb=o||new l(i,s),this._mutex=navigator.locks?new f(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:n},this._needsWipe=!!t,n&&(this._http=new u(n),this._urlauto=!!r)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();let e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){let e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,n){let r=p.split(p.dirname(e)),i=r.shift();for(let e of r){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch{}}return this._cache.writeStat(e,t,n)}async readFile(e,t){let n=typeof t==`string`?t:t&&t.encoding;if(n&&n!==`utf8`)throw Error(`Only "utf8" encoding is supported in readFile`);let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;t.type===`symlink`;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&((!a||a.size!=i.byteLength)&&(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),n===`utf8`?i=r(i):i.toString=()=>r(i)),!a)throw new o(e);return i}async writeFile(e,t,r){let{mode:i,encoding:a=`utf8`}=r;if(typeof t==`string`){if(a!==`utf8`)throw Error(`Only "utf8" encoding is supported in writeFile`);t=n(t)}let o=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(o.ino,t)}async unlink(e,t){let n=this._cache.lstat(e);this._cache.unlink(e),n.type!==`symlink`&&await this._idb.unlink(n.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){let{mode:n=511}=t;this._cache.mkdir(e,{mode:n})}rmdir(e,t){if(e===`/`)throw new s;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let n=await this._http.sizeFile(e);await this._writeStat(e,n,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}})),E=e(((e,t)=>{t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return this.type===`file`}isDirectory(){return this.type===`dir`}isSymbolicLink(){return this.type===`symlink`}}})),D=e(((e,t)=>{let n=ae(),r=E(),i=S();function a(e,t,...n){return e=i.normalize(e),(t===void 0||typeof t==`function`)&&(t={}),typeof t==`string`&&(t={encoding:t}),[e,t,...n]}function o(e,t,n,...r){return e=i.normalize(e),(n===void 0||typeof n==`function`)&&(n={}),typeof n==`string`&&(n={encoding:n}),[e,t,n,...r]}function s(e,t,...n){return[i.normalize(e),i.normalize(t),...n]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,o,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,s,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,s,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new n,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&=(this._initPromiseResolve(),null),t.defer||this.stat(`/`)}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(e=>this._gracefulShutdownResolve=e),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,n){return async(...r)=>{r=t(...r);let i={name:e.name,args:r};this._operations.add(i);try{return await this._activate(),await e.apply(this,r)}finally{this._operations.delete(i),n&&this._backend.saveSuperblock(),this._operations.size===0&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&=(clearTimeout(this._deactivationTimeout),null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||=this._backend.activate?this._backend.activate():Promise.resolve(),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||=this._backend.deactivate?this._backend.deactivate():Promise.resolve(),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,n){return await this._backend.writeFile(e,t,n),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){return new r(await this._backend.stat(e,t))}async lstat(e,t){return new r(await this._backend.lstat(e,t))}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}})),oe=e(((e,t)=>{let n=b(),r=D();function i(e,t){return typeof e==`function`&&(t=e),t=n(t),[(...e)=>t(null,...e),t]}t.exports=class{constructor(...e){this.promises=new r(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,n){let[r,a]=i(t,n);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,n,r){let[a,o]=i(n,r);this.promises.writeFile(e,t,n).then(a).catch(o)}unlink(e,t,n){let[r,a]=i(t,n);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,n){let[r,a]=i(t,n);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,n){let[r,a]=i(t,n);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,n){let[r,a]=i(t,n);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,n){let[r,a]=i(n);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,n){let[r,a]=i(t,n);this.promises.stat(e).then(r).catch(a)}lstat(e,t,n){let[r,a]=i(t,n);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,n){let[r,a]=i(t,n);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,n){let[r,a]=i(n);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,n){let[r,a]=i(t,n);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){let[n,r]=i(t);this.promises.du(e).then(n).catch(r)}flush(e){let[t,n]=i(e);this.promises.flush().then(t).catch(n)}}}));v();var se=y();oe();var O=class extends Error{constructor(e,t){super(e),this.operation=t,this.name=`JsonPatchError`}};function k(e){let t=ce(e);return t===``?[]:t.substring(1).split(`/`).map(le)}function ce(e){return e===``||e===`/`?``:e.startsWith(`/`)?`/`+e.substring(1).split(`/`).map(A).join(`/`):`/`+e.split(`.`).map(A).join(`/`)}function A(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function le(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}var j=new Map;function M(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)throw new O(`Invalid path - parent not found at ${e}`);if(Array.isArray(n)){let t=e===`-`?n.length:parseInt(e);if(isNaN(t)||t<0||t>n.length)throw new O(`Invalid array index: ${e}`);n=n[t]}else{if(!n.hasOwnProperty(e))throw new O(`Property ${e} not found`);n=n[e]}}return n}function N(e,t){let n=j.get(t)||k(t);if(j.set(t,n),n.length===0)return e;let r=M(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new O(`Invalid array index: ${i}`);return r[e]}return r[i]}function ue(e,t,n){let r=j.get(t)||k(t);j.set(t,r);let i=M(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter(e=>e!==n)):i[a]===n&&delete i[a],e}function P(e,t,n){let r=j.get(t)||k(t);if(j.set(t,r),r.length===0)return n;let i=r.slice(0,-1),a=r[r.length-1],o=M(e,i);if(Array.isArray(o))if(a===`-`)o.push(n);else{let e=parseInt(a);if(e<0||e>o.length)throw new O(`Invalid array index: ${a}`);o.splice(e,0,n)}else o[a]=n;return e}function F(e,t){let n=j.get(t)||k(t);if(j.set(t,n),n.length===0)return;let r=M(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);r.splice(e,1)}else delete r[i];return e}function de(e,t){let n=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case`add`:n=P(n,e.path,e.value);break;case`remove`:n=F(n,e.path);break;case`removeValue`:n=ue(n,e.path,e.value);break;case`replace`:n=P(F(n,e.path),e.path,e.value);break;case`copy`:{let t=N(n,e.from);n=P(n,e.path,JSON.parse(JSON.stringify(t)));break}case`move`:{let t=N(n,e.from);n=P(n,e.path,t),n=F(n,e.from);break}case`test`:{let t=N(n,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new O(`Test operation failed`);break}default:throw new O(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof O&&(t.operation=e),t}return n}function fe(e,t){let n=[];switch(e.type){case`addField`:n.push({op:`add`,path:`/fields/${e.id}`,value:e.definition});break;case`removeField`:n.push({op:`remove`,path:`/fields/${e.id}`});break;case`modifyField`:{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach(([e,r])=>{n.push({op:`replace`,path:`${t}/${e}`,value:r})});break}case`deprecateField`:n.push({op:`add`,path:`/fields/${e.id}/deprecated`,value:!0});break;case`addIndex`:t.indexes||n.push({op:`add`,path:`/indexes`,value:[]}),n.push({op:`add`,path:`/indexes/-`,value:e.definition});break;case`removeIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/indexes/${r}`});break}case`modifyIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`/indexes/${r}/${e}`,value:t})});break}case`addConstraint`:t.constraints||n.push({op:`add`,path:`/constraints`,value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(e=>{n.push({op:`add`,path:`/constraints/-`,value:e})}):n.push({op:`add`,path:`/constraints/-`,value:e.constraint});break;case`removeConstraint`:{let r=t.constraints?.findIndex(t=>Array.isArray(t)?t.some(t=>t.name===e.name):t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/constraints/${r}`});break}case`modifyConstraint`:{let r=pe(t,e.name);r&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`${r}/${e}`,value:t})});break}}return n}function pe(e,t){if(!e.constraints)return null;for(let n=0;n<e.constraints.length;n++){let r=e.constraints[n];if(r.name===t)return`/constraints/${n}`;if(me(r)){let e=he(r.rules,t);if(e)return`/constraints/${n}${e}`}}return null}function me(e){return e&&`operator`in e&&`rules`in e}function he(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(`name`in r&&r.name===t)return`/rules/${n}`;if(me(r)){let e=he(r.rules,t);if(e)return`/rules/${n}${e}`}}return null}var I=new Map;function L(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ge(e,t){let n=e=>({value:e}),r=e=>({issues:e}),i=(e,t,n,r)=>{switch(t){case`string`:return typeof e==`string`?[]:[{message:`Expected string, got ${typeof e}`,path:n}];case`number`:return typeof e!=`number`||isNaN(e)?[{message:`Expected number, got ${typeof e}`,path:n}]:[];case`boolean`:return typeof e==`boolean`?[]:[{message:`Expected boolean, got ${typeof e}`,path:n}];case`array`:return Array.isArray(e)?[]:[{message:`Expected array, got ${typeof e}`,path:n}];case`set`:return!Array.isArray(e)||new Set(e).size!==e.length?[{message:`Expected unique array, got ${typeof e}`,path:n}]:[];case`enum`:return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:n}]:[{message:`Enum type requires 'values' definition`,path:n}];case`object`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected object, got ${typeof e}`,path:n}]:[];case`record`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];case`union`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected union (object), got ${typeof e}`,path:n}]:[];case`dynamic`:return console.warn(`Deprecated: 'dynamic' type used. Use 'record' instead.`),typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];default:return[{message:`Unknown type '${t}'`,path:n}]}};function a(e,t,n,r,i){let o=[],s=e.rules.map((e,s)=>{let c=[...r,`rules[${s}]`],l=`${e.name}@${c.join(`.`)}`;if(`rules`in e){if(i.has(l))return!0;i.add(l);let r=a(e,t,n,c,i);return o.push(...r),i.delete(l),r.length===0}else{let r=n[e.predicate];if(!r)return o.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(I.has(i)){let t=I.get(i);return t||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return I.set(i,a),a||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:c}),a}});return(()=>{switch(e.operator){case`and`:return s.every(e=>e);case`or`:return s.some(e=>e);case`not`:return!s.every(e=>e);case`nor`:return!s.some(e=>e);case`xor`:return s.filter(e=>e).length===1}})()||o.push({message:`Constraint group '${e.name}' failed`,path:r}),o}function o(e,t,n,r,s,c=new Set){let l=[];if(`type`in t&&!(`fields`in t)){let o=r.length>0?e[r[r.length-1]]:e;return l.push(...i(o,t.type,r,{values:t.values})),t.constraints&&t.constraints.forEach((e,t)=>{if(`rules`in e)l.push(...a(e,{value:o},n,[...r,`constraints[${t}]`],c));else{let i=n[e.predicate];i?i({data:{value:o},field:`value`,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:[...r,`constraints[${t}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...r,`constraints[${t}]`]})}}),l}let u={};if(`concrete`in t)if(t.concrete===!0||!Array.isArray(t.fields))u=t.fields;else{let n=t.fields,i=n.find(e=>!e.when);i&&Object.assign(u,i.fields);let a=n.find(t=>t.when&&e[t.when.field]!==void 0&&e[t.when.field]===t.when.value);if(a)Object.assign(u,a.fields);else if(!i)return l.push({message:`No matching field set found for discriminated schema`,path:r}),l}else u=t.fields;let d=new Set(Object.values(u).map(e=>e.name));Object.entries(u).forEach(([t,u])=>{let d=[...r,u.name],f=Object.hasOwnProperty.call(e,u.name)?e[u.name]:u.default===void 0?void 0:u.default;u.required&&f==null&&l.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if(u.type===`object`&&p&&!Array.isArray(p)){let e=s[p.id];if(e)if(c.has(p.id))l.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=f&&typeof f==`object`&&!Array.isArray(f)?f:{};l.push(...o(t,e,n,d,s,c)),p.constraints?.forEach((e,r)=>{if(`rules`in e)l.push(...a(e,t,n,[...d,`constraints[${r}]`],c));else{let i=n[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${L(e.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}),c.delete(p.id)}else l.push({message:`Nested schema '${p.id}' not found`,path:d})}if(u.type===`union`&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach((r,i)=>{let l=s[r.id];if(l)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,i.toString()]});else{c.add(r.id);let i=f&&typeof f==`object`&&!Array.isArray(f)?f:{},u=o(i,l,n,d,s,new Set(c));u.length===0&&f!==void 0?(e=!0,r.constraints?.forEach((r,o)=>{if(`rules`in r){let s=a(r,i,n,[...d,`constraints[${o}]`],c);s.length>0&&(e=!1,t.push(...s))}else{let a=n[r.predicate];a&&!a({data:i,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${o}]`]}))}})):f===void 0&&t.push(...u.filter(e=>e.message.includes(`is required`))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,i.toString()]})}),!e&&f!==void 0?(l.push({message:`Value does not match any union schema`,path:d}),l.push(...t)):f===void 0&&l.push(...t)}f!==void 0&&(l.push(...i(f,u.type,d,{values:u.values})),(u.type===`array`||u.type===`set`)&&Array.isArray(f)&&(u.constraints?.forEach((e,t)=>{let r=n[e.predicate];r&&!r({data:{[u.name]:f},field:u.name,arguments:e.parameters})&&l.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})}),u.itemsType&&f.forEach((e,t)=>l.push(...i(e,u.itemsType,[...d,t.toString()]))),p&&!Array.isArray(p)&&(s[p.id]?f.forEach((e,t)=>{typeof e==`object`&&e&&(c.has(p.id)?l.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),l.push(...o(e,s[p.id],n,[...d,t.toString()],s,c)),c.delete(p.id)))}):l.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach((t,r)=>{if(`rules`in t)l.push(...a(t,e,n,[...d,`constraints[${r}]`],c));else{let i=n[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${L(t.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}))});for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&l.push({message:`Unexpected field '${t}'`,path:[...r,t]});return t.constraints?.forEach((t,i)=>{if(`rules`in t)l.push(...a(t,e,n,[...r,`constraints[${i}]`],c));else{let a=n[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${L(t.parameters)}`,path:[...r,`constraints[${i}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...r,`constraints[${i}]`]})}}),l}return e.version!==`1.0.0`&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:i=>{if(typeof i!=`object`||!i)return r([{message:`Input must be an object`,path:[]}]);let a=i,s=o(a,e,t,[],e.nestedSchemas||{});return s.length>0?r(s):n(a)},types:{input:{},output:{}}}}}var R=class extends Error{constructor(e,t){super(e),this.errors=t,this.name=`SchemaValidationError`}},z=e=>({value:e}),B=e=>({issues:e}),V=(e,t,n=!0)=>e===void 0&&!n?[]:typeof e!=`string`||e.trim()===``?[{message:`Must be a non-empty string`,path:[t]}]:[],H=(e,t)=>{let n=[`string`,`number`,`boolean`,`array`,`set`,`enum`,`object`,`record`,`union`,`dynamic`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:e===`dynamic`?[{message:`Field type 'dynamic' is deprecated; use 'record' instead`,path:[t]}]:[]},_e=(e,t)=>{let n=[`normal`,`unique`,`btree`,`hash`,`spatial`,`fulltext`,`gi`,`expression`,`composite`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},ve=(e,t)=>{let n=[`and`,`or`,`not`,`nor`,`xor`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},U=(e,t,n=!1)=>e===void 0&&!n||typeof e==`boolean`?[]:[{message:`Must be a boolean`,path:[t]}],ye=(e,t,n)=>[],W=(e,t,n)=>{let r=[],i=[`predicate`,`name`],a=[`type`,`predicate`,`field`,`parameters`,`name`,`description`,`errorMessage`],o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...V(e.name,`${n}.name`)),r.push(...V(e.predicate,`${n}.predicate`)),e.field!==void 0&&typeof e.field!=`string`&&r.push({message:`Field must be a string`,path:[`${n}.field`]}),e.parameters!==void 0&&r.push(...ye(e.parameters,t,`${n}.parameters`)),r.push(...V(e.description,`${n}.description`,!1)),r.push(...V(e.errorMessage,`${n}.errorMessage`,!1)),r},G=(e,t,n)=>{let r=[],i=[`name`,`operator`,`rules`],a=i,o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...V(e.name,`${n}.name`)),r.push(...ve(e.operator,`${n}.operator`)),!Array.isArray(e.rules)||e.rules.length===0?r.push({message:`Rules must be a non-empty array`,path:[`${n}.rules`]}):e.rules.forEach((e,i)=>{`rules`in e?r.push(...G(e,t,`${n}.rules[${i}]`)):r.push(...W(e,t,`${n}.rules[${i}]`))}),r},K=(e,t,n)=>{if(!Array.isArray(e))return[{message:`Must be an array`,path:[n]}];let r=[];return e.forEach((e,i)=>{`rules`in e?r.push(...G(e,t,`${n}[${i}]`)):r.push(...W(e,t,`${n}[${i}]`))}),r},be=(e,t)=>{let n=[],r=[`operator`,`field`],i=[`operator`,`field`,`value`,`conditions`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...ve(e.operator,`${t}.operator`)),n.push(...V(e.field,`${t}.field`)),e.conditions!==void 0&&(Array.isArray(e.conditions)?e.conditions.forEach((e,r)=>n.push(...be(e,`${t}.conditions[${r}]`))):n.push({message:`Conditions must be an array`,path:[`${t}.conditions`]})),n},xe=(e,t)=>{let n=[],r=[`fields`,`type`,`name`],i=[`fields`,`type`,`unique`,`partial`,`description`,`order`,`name`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`)),n.push(..._e(e.type,`${t}.type`)),(!Array.isArray(e.fields)||e.fields.length===0||!e.fields.every(e=>typeof e==`string`))&&n.push({message:`Fields must be a non-empty array of strings`,path:[`${t}.fields`]}),n.push(...U(e.unique,`${t}.unique`,!1)),e.partial&&n.push(...be(e.partial,`${t}.partial`)),n.push(...V(e.description,`${t}.description`,!1)),e.order!==void 0&&![`asc`,`desc`].includes(e.order)&&n.push({message:`Order must be 'asc' or 'desc'`,path:[`${t}.order`]}),n},q=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e))return[{message:`Must be an array`,path:[t]}];let n=[];return e.forEach((e,r)=>n.push(...xe(e,`${t}[${r}]`))),n},Se=(e,t,n,r,i)=>{let a=[];return e===void 0?[]:(n===`union`&&Array.isArray(e)?(e.length===0&&a.push({message:`Schema array must not be empty for union type`,path:[t]}),e.forEach((e,n)=>{let i=`${t}[${n}]`;a.push(...V(e.id,`${i}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...K(e.constraints,`dynamic`,`${i}.constraints`)),e.indexes&&a.push(...q(e.indexes,`${i}.indexes`))})):(n===`object`||n===`array`&&i===`object`)&&!Array.isArray(e)?(a.push(...V(e.id,`${t}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...K(e.constraints,`dynamic`,`${t}.constraints`)),e.indexes&&a.push(...q(e.indexes,`${t}.indexes`))):a.push({message:`Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'`,path:[t]}),a)},Ce=(e,t,n)=>{if(e===void 0)return[];switch(t){case`string`:if(typeof e!=`string`)return[{message:`Default must be a string`,path:[n]}];break;case`number`:if(typeof e!=`number`)return[{message:`Default must be a number`,path:[n]}];break;case`boolean`:if(typeof e!=`boolean`)return[{message:`Default must be a boolean`,path:[n]}];break;case`array`:case`set`:if(!Array.isArray(e))return[{message:`Default must be an array`,path:[n]}];break;case`enum`:if(!Array.isArray(e)||!e.every(e=>typeof e==`string`||typeof e==`number`))return[{message:`Default must be an array of strings or numbers`,path:[n]}];break;case`object`:case`record`:if(typeof e!=`object`||!e)return[{message:`Default must be an object`,path:[n]}];break;case`union`:case`dynamic`:return[]}return[]},we=(e,t)=>e===void 0?[]:typeof e!=`object`||!e?[{message:`Hint must be an object`,path:[t]}]:`input`in e&&typeof e.input!=`object`?[{message:`Hint.input must be an object`,path:[`${t}.input`]}]:[],J=(e,t,n)=>{let r=[],i=[`name`,`type`],a=[`name`,`type`,`required`,`constraints`,`default`,`values`,`schema`,`itemsType`,`nestedSchema`,`deprecated`,`reference`,`description`,`unique`,`hint`],o=e;if(i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...V(e.name,`${t}.name`)),r.push(...H(e.type,`${t}.type`)),r.push(...U(e.required,`${t}.required`,!1)),e.constraints&&r.push(...K(e.constraints,e.type,`${t}.constraints`)),r.push(...Ce(e.default,e.type,`${t}.default`)),e.values!==void 0&&(e.type===`enum`?(!Array.isArray(e.values)||e.values.length===0||!e.values.every(e=>typeof e==`string`||typeof e==`number`))&&r.push({message:`Values must be a non-empty array of strings or numbers`,path:[`${t}.values`]}):r.push({message:`Values is only valid for 'enum' type`,path:[`${t}.values`]})),e.schema!==void 0&&r.push(...Se(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...H(e.itemsType,`${t}.itemsType`)),e.nestedSchema){r.push({message:`nestedSchema is deprecated; use schema instead`,path:[`${t}.nestedSchema`]});let i=[`id`],a=[`id`,`constraints`,`indexes`],o=e.nestedSchema;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})}),r.push(...V(e.nestedSchema.id,`${t}.nestedSchema.id`)),n.includes(e.nestedSchema.id)||r.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&r.push(...K(e.nestedSchema.constraints,`dynamic`,`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...q(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...U(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:`reference is deprecated`,path:[`${t}.reference`]});let n=[`schema`,`field`],i=[`schema`,`field`],a=e.reference;n.forEach(e=>{a[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})}),r.push(...V(e.reference.schema,`${t}.reference.schema`)),r.push(...V(e.reference.field,`${t}.reference.field`))}return r.push(...V(e.description,`${t}.description`,!1)),r.push(...U(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...we(e.hint,`${t}.hint`)),r},Te=(e,t,n)=>{let r=[];if(`type`in e&&[`string`,`number`,`boolean`,`array`,`set`,`enum`,`record`].includes(e.type)){let i=[`name`,`type`],a=[`name`,`type`,`default`,`schema`,`itemsType`,`constraints`,`description`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...V(e.name,`${t}.name`)),r.push(...H(e.type,`${t}.type`)),r.push(...Ce(e.default,e.type,`${t}.default`)),e.schema&&r.push(...Se(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...H(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...K(e.constraints,e.type,`${t}.constraints`)),r.push(...V(e.description,`${t}.description`,!1)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}else{let i=[`name`],a=[`name`,`description`,`concrete`,`fields`,`indexes`,`constraints`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...V(e.name,`${t}.name`)),r.push(...U(o.concrete,`${t}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&r.push({message:`Fields must be an object when concrete is true`,path:[`${t}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&r.push({message:`Fields array must not be empty`,path:[`${t}.fields`]}),o.fields.forEach((e,i)=>{let a=`${t}.fields[${i}]`;if(typeof e!=`object`||!e||!(`fields`in e))r.push({message:`Each variant must have a 'fields' property`,path:[a]});else{let t=e.fields;typeof t!=`object`||!t?r.push({message:`Fields must be a non-empty object`,path:[`${a}.fields`]}):Object.entries(t).forEach(([e,t])=>{r.push(...J(t,`${a}.fields.${e}`,n))}),e.when!==void 0&&(typeof e.when!=`object`||e.when===null?r.push({message:`When must be an object`,path:[`${a}.when`]}):r.push(...V(e.when.field,`${a}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!=`object`||o.fields===null?r.push({message:`Fields must be a non-empty object`,path:[`${t}.fields`]}):Object.entries(o.fields).forEach(([e,i])=>{r.push(...J(i,`${t}.fields.${e}`,n))})),r.push(...V(e.description,`${t}.description`,!1)),e.indexes&&r.push(...q(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...K(o.constraints,`dynamic`,`${t}.constraints`)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}return r},Ee=e=>{if(typeof e!=`object`||!e)return B([{message:`Schema must be an object`,path:[]}]);let t=e,n=[],r=[`name`,`version`,`fields`],i=[`name`,`version`,`description`,`fields`,`nestedSchemas`,`indexes`,`constraints`,`metadata`,`dependencies`,`migrations`,`mock`,`hint`],a=t;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[e]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[e]})}),n.push(...V(t.name,`name`)),n.push(...V(t.version,`version`)),typeof t.fields!=`object`||t.fields===null)n.push({message:`Fields must be a non-empty object`,path:[`fields`]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach(([t,r])=>{n.push(...J(r,`fields.${t}`,e))})}if(t.nestedSchemas!==void 0)if(typeof t.nestedSchemas!=`object`||t.nestedSchemas===null)n.push({message:`NestedSchemas must be an object`,path:[`nestedSchemas`]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach(([t,r])=>n.push(...Te(r,`nestedSchemas.${t}`,e)))}return n.push(...V(t.description,`description`,!1)),t.indexes&&n.push(...q(t.indexes,`indexes`)),t.constraints&&n.push(...K(t.constraints,`dynamic`,`constraints`)),t.metadata!==void 0&&(typeof t.metadata!=`object`||t.metadata===null)&&n.push({message:`Metadata must be an object`,path:[`metadata`]}),t.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`dependencies`]})),t.migrations!==void 0&&(Array.isArray(t.migrations)?t.migrations.forEach((e,t)=>n.push(...Oe(e,`migrations[${t}]`))):n.push({message:`Migrations must be an array`,path:[`migrations`]})),t.mock!==void 0&&typeof t.mock!=`function`&&n.push({message:`Mock must be a function`,path:[`mock`]}),t.hint&&n.push(...we(t.hint,`hint`)),n.length>0?B(n):z(t)},Y=(e,t)=>{let n=[];switch(e.type||n.push({message:`type is required`,path:[`${t}.type`]}),e.type){case`modifyProperty`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),(e.changes===void 0||typeof e.changes!=`object`)&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addField`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),n.push(...J(e.definition,`${t}.definition`,[]));break}case`removeField`:case`deprecateField`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`));break}case`modifyField`:{let r=[`type`,`id`,`changes`],i=[`type`,`id`,`changes`,`nestedSchemaChanges`],a=e;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]}),e.nestedSchemaChanges){let r=[`id`,`constraints`,`indexes`],i=e.nestedSchemaChanges;Object.keys(i).forEach(e=>{r.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})}),n.push(...V(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&n.push(...K(i.constraints,`dynamic`,`${t}.nestedSchemaChanges.constraints`)),i.indexes&&n.push(...q(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case`addIndex`:{let r=[`type`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...xe(e.definition,`${t}.definition`));break}case`removeIndex`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`));break}case`modifyIndex`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addConstraint`:{let r=[`type`,`constraint`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),`rules`in e.constraint?n.push(...G(e.constraint,`dynamic`,`${t}.constraint`)):n.push(...W(e.constraint,`dynamic`,`${t}.constraint`));break}case`removeConstraint`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`));break}case`modifyConstraint`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addNestedSchema`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),n.push(...Te(e.definition,`${t}.definition`,[]));break}case`removeNestedSchema`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`));break}case`modifyNestedSchema`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}default:n.push({message:`Unknown schema change type`,path:[`${t}.type`]})}return n},De=(e,t)=>{let n=[],r=[`forward`,`backward`],i=r,a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),typeof e.forward!=`function`&&n.push({message:`Forward must be a function`,path:[`${t}.forward`]}),typeof e.backward!=`function`&&n.push({message:`Backward must be a function`,path:[`${t}.backward`]}),n},Oe=(e,t)=>{let n=[],r=[`id`,`schemaVersion`,`changes`,`description`,`status`,`transform`,`createdAt`,`checksum`],i=[...r,`rollback`,`dependencies`],a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...V(e.id,`${t}.id`)),n.push(...V(e.schemaVersion,`${t}.schemaVersion`)),n.push(...V(e.description,`${t}.description`));let o=[`pending`,`applied`,`failed`];return o.includes(e.status)||n.push({message:`Status must be one of ${o.join(`, `)}`,path:[`${t}.status`]}),!Array.isArray(e.changes)||e.changes.length===0?n.push({message:`Changes must be a non-empty array`,path:[`${t}.changes`]}):e.changes.forEach((e,r)=>{n.push(...Y(e,`${t}.changes[${r}]`))}),e.rollback!==void 0&&(Array.isArray(e.rollback)?e.rollback.forEach((e,r)=>n.push(...Y(e,`${t}.rollback[${r}]`))):n.push({message:`Rollback must be an array`,path:[`${t}.rollback`]})),typeof e.transform==`string`?n.push(...V(e.transform,`${t}.transform`)):typeof e.transform==`object`&&e.transform!==null?n.push(...De(e.transform,`${t}.transform`)):n.push({message:`Transform must be a string or object`,path:[`${t}.transform`]}),n.push(...V(e.createdAt,`${t}.createdAt`)),n.push(...V(e.checksum,`${t}.checksum`)),e.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`${t}.dependencies`]})),n},ke={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:Ee,types:{input:{},output:{}}}},Ae={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(typeof e!=`object`||!e)return B([{message:`Migration must be an object`,path:[]}]);let t=e,n=Oe(t,``);return n.length>0?B(n):z(t)},types:{input:{},output:{}}}},je={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(!Array.isArray(e))return B([{message:`SchemaChanges must be an array`,path:[]}]);let t=e,n=[];return t.forEach((e,t)=>n.push(...Y(e,`[${t}]`))),n.length>0?B(n):z(t)},types:{input:[],output:[]}}};function Me(e){try{return!Ae[`~standard`].validate(e).issues}catch(e){throw new R(`Invalid migration definition`,e instanceof Error?e:Error(String(e)))}}function Ne(e){try{return!je[`~standard`].validate(e).issues}catch(e){throw new R(`Invalid schema change definition`,e instanceof Error?e:Error(String(e)))}}function Pe(e){try{return!ke[`~standard`].validate(e).issues}catch(e){throw new R(`Invalid schema definition`,e instanceof Error?e:Error(String(e)))}}var Fe=async e=>{if(typeof window<`u`&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}else{let{createHash:t}=await import(`crypto`);return t(`sha256`).update(e).digest(`hex`)}};function Ie(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}function Le(e,t){if(t&&`field`in e&&e.field){let n=t.fields[e.field];if(n)return n.type}if(`parameters`in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]==`string`)return`string`;if(typeof t==`number`||Array.isArray(t)&&typeof t[0]==`number`)return`number`;if(typeof t==`boolean`)return`boolean`;if(typeof t==`object`&&t){if(`minItems`in t||`maxItems`in t)return`array`;if(`schema`in t)return`object`}}}function Re(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function ze(e,t,n){switch(n){case`string`:if(e instanceof RegExp&&t instanceof RegExp)return e.source!==t.source;if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`number`:if(typeof e==`object`&&typeof t==`object`&&`precision`in e&&`precision`in t)return t.precision<e.precision||(t.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`array`:if(typeof e==`object`&&typeof t==`object`&&`minItems`in e&&`maxItems`in e&&`minItems`in t&&`maxItems`in t)return t.minItems>e.minItems||t.maxItems<e.maxItems;break;case`object`:if(typeof e==`object`&&typeof t==`object`&&`schema`in e&&`schema`in t)return Object.keys(t.schema).length>Object.keys(e.schema).length;break}return!1}function Be(e,t){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(t.operator&&n[t.operator]>n[e.operator]||t.rules&&t.rules.length>e.rules.length)}function Ve(e,t,n){if(!t)return!0;if(`rules`in t&&`rules`in e)return Be(t,e);if(`predicate`in e&&e.predicate!==void 0)return!0;if(`parameters`in e&&e.parameters!==void 0){let r=Le(t,n);return r?ze(t.parameters,e.parameters,r):!0}return!1}function He(e,t){switch(e.type){case`removeField`:case`removeIndex`:return`major`;case`modifyField`:return Re(e.changes)?`major`:e.changes.deprecated?`minor`:`patch`;case`modifyIndex`:return e.changes.unique!==void 0||e.changes.fields!==void 0?`major`:`minor`;case`addConstraint`:return`major`;case`removeConstraint`:return`minor`;case`modifyConstraint`:let n=t?.constraints?.find(t=>`name`in t&&t.name===e.name);return Ve(e.changes,n,t)?`major`:`minor`;case`addField`:case`addIndex`:case`deprecateField`:return`minor`;default:throw Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Ue(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case`addField`:if(n.has(a.id))throw Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case`removeField`:if(r.has(a.id))throw Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case`modifyField`:if(n.has(a.id))throw Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case`deprecateField`:if(n.has(a.id))throw Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id);break}}function We(e){let t=new Set,n=new Set,r=new Set;for(let i of e)switch(i.type){case`addConstraint`:let e=i.constraint,a=(`name`in e,e.name);if(n.has(a))throw Error(`Cannot add previously removed constraint: ${a}`);if(t.has(a))throw Error(`Cannot add already modified constraint: ${a}`);r.add(a);break;case`removeConstraint`:if(r.has(i.name))throw Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw Error(`Cannot remove modified constraint: ${i.name}`);n.add(i.name);break;case`modifyConstraint`:if(n.has(i.name))throw Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name);break}}function Ge(e,t,n){if(t.length===0)throw Error(`No changes provided`);Ue(t),We(t);let r=Ie(e),i=`patch`;for(let e of t){let t=He(e,n);if(t===`major`){i=`major`;break}else t===`minor`&&i===`patch`&&(i=`minor`)}switch(i){case`major`:return`${r.major+1}.0.0`;case`minor`:return`${r.major}.${r.minor+1}.0`;case`patch`:return`${r.major}.${r.minor}.${r.patch+1}`}}function X(e,t){let n=e=>e.split(`.`).map(e=>parseInt(e,10)||0),[r,i,a]=n(e),[o,s,c]=n(t);return r-o||i-s||a-c}var Z=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.migrationId=n,this.cause=r,this.name=`MigrationError`}},Ke=(e=>(e.INVALID_SCHEMA=`INVALID_SCHEMA`,e.INVALID_MIGRATION=`INVALID_MIGRATION`,e.CHECKSUM_MISMATCH=`CHECKSUM_MISMATCH`,e.TIMEOUT=`TIMEOUT`,e.MEMORY_LIMIT=`MEMORY_LIMIT`,e.CONCURRENT_OPERATION=`CONCURRENT_OPERATION`,e.TRANSFORM_ERROR=`TRANSFORM_ERROR`,e.VERSION_NOT_FOUND=`VERSION_NOT_FOUND`,e.CIRCULAR_DEPENDENCY=`CIRCULAR_DEPENDENCY`,e.STREAM_ERROR=`STREAM_ERROR`,e.ROLLBACK_ERROR=`ROLLBACK_ERROR`,e.MISSING_TRANSFORM=`MISSING_TRANSFORM`,e))(Ke||{}),qe=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,n){try{if(!Pe(e))throw new Z(`Invalid initial schema`,`INVALID_SCHEMA`);if(this.currentSchema=e,t){if(!t.every(e=>Me(e)))throw new Z(`Invalid migration configuration`,`INVALID_MIGRATION`);this.migrations=t.sort((e,t)=>X(e.schemaVersion,t.schemaVersion))}n&&(this.history=n.sort((e,t)=>X(e.version,t.version)))}catch(e){throw e instanceof Z?e:new Z(`Failed to initialize MigrationEngine`,`INVALID_SCHEMA`,void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{return await Fe(JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt}))}catch(t){throw new Z(`Checksum generation failed`,`CHECKSUM_MISMATCH`,e.id,t)}}async add(e){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);if(!e.changes?.length)throw new Z(`Migration must include changes`,`INVALID_MIGRATION`);try{e.changes.forEach(e=>Ne(e))}catch(e){throw new Z(`Invalid schema changes`,`INVALID_MIGRATION`,void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:`pending`,rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:``};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,n,r){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(n,r);return{newSchema:a.reduce((e,t)=>{let r=n===`forward`?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)},i),dataPreview:await e.processMigrationList(t,n,a)}}catch(e){throw e instanceof Z?e:new Z(`Dry run failed`,`INVALID_SCHEMA`,void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(n=>{let r=e===`forward`?`pending`:`applied`,i=t?X(n.schemaVersion,t)>=0:!0;return n.status===r&&i}).sort((t,n)=>e===`forward`?t.id.localeCompare(n.id):n.id.localeCompare(t.id))}applySchemaChanges(e,t,n){try{let r=Ge(e.version,t);return t.map(t=>{try{return fe(t,e)}catch(e){throw new Z(`Invalid schema change`,`INVALID_SCHEMA`,n,e)}}).reduce((e,t)=>{try{return de(e,t)}catch(e){throw new Z(`Failed to apply patch`,`INVALID_SCHEMA`,n,e)}},{...e,version:r})}catch(e){throw e instanceof Z?e:new Z(`Schema update failed`,`INVALID_SCHEMA`,n,e)}}async prepareMigration(){let e=this.migrations.filter(e=>e.status===`pending`);return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema(`forward`);let r=await e.processMigrationList(t,`forward`,n);return this.markMigrationsApplied(n),r}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new Z(`Checksum mismatch`,`CHECKSUM_MISMATCH`,e.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(e=>e.id===t.id)?{...t,status:`applied`}:t)}async rollback(e){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);return this.migrations.filter(e=>e.status===`applied`).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,n){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);try{let r=this.history.findIndex(e=>e.version===t);if(r===-1)throw Error(`Version ${t} not found in history`);let i=this.migrations.filter(e=>e.schemaVersion===t&&e.status===`applied`).sort((e,t)=>t.id.localeCompare(e.id)),a=this.history.length-r;if(a<0)return n;for(let e=0;e<a;e++)this.transformSchema(`backward`);let o=await e.processMigrationList(n,`backward`,i);return this.migrations=this.migrations.map(e=>e.schemaVersion===t&&e.status===`applied`?{...e,status:`pending`}:e),o}finally{this.isProcessing=!1}}static async processMigrationList(e,t,n){return(await Promise.all(n.map(async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Z(`Failed to resolve transform for migration ${e.id}`,`TRANSFORM_ERROR`,e.id,t)}}))).filter(e=>!!e.transform).reduce((e,{migration:t,transform:n})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await n(e);r.enqueue(t)}catch(e){r.error(new Z(`Data transformation failed for migration ${t.id}`,`TRANSFORM_ERROR`,t.id,e))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform==`string`?e.transform.startsWith(`http://`)||e.transform.startsWith(`https://`)?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let n=await fetch(e);if(!n.ok)throw new Z(`Failed to fetch transform module: ${e}`,`TRANSFORM_ERROR`,void 0);let r=await n.text();if(typeof window<`u`){let e=new Blob([r],{type:`application/javascript`});return(await import(URL.createObjectURL(e))).default[t]}else{let{runInNewContext:n}=await import(`vm`),i={module:{exports:{}},console};return n(r,i,e),i.module.exports[t]}}catch(t){throw new Z(`Failed to load remote transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new Z(`Failed to import local transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}transformSchema(e){try{if(e===`backward`){let e=this.history.pop();if(!e)throw Error(`No previous version`);this.currentSchema=e;return}let t=this.migrations.filter(e=>e.status===`pending`).flatMap(e=>e.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((e,t)=>this.applySchemaChanges(e,[t]),this.currentSchema)}catch(e){throw e instanceof Z?e:new Z(`Schema transformation failed`,`INVALID_SCHEMA`,void 0,e)}}};typeof window<`u`&&(window.Buffer=n.Buffer);var Je=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let n=-1,r=i=>{if(i<=n)throw Error(`next() called multiple times`);n=i;let a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,()=>r(i+1))}catch(e){return Promise.reject(e)}};return r(0)}wrap(e,t){let n=this;return new Proxy(e,{get(e,r,i){let a=Reflect.get(e,r,i);return typeof a==`function`?function(...i){let o={...t,operation:r.toString(),args:i};return n.execute(o,()=>a.apply(e,i))}:a}})}};const Ye=(e=3,t=100)=>async(n,r)=>{let i=0;for(;i<e;)try{return await r()}catch(n){if(n instanceof o&&n.type===`TRANSIENT_ERROR`){if(i++,i>=e)throw n;let r=t*2**i+Math.random()*50;await new Promise(e=>setTimeout(e,r))}else throw n}},Xe=async(e,t)=>{let n=Date.now();try{let r=await t();return Ze(e,n,r,null),r}catch(t){throw Ze(e,n,void 0,t),t}};function Ze(e,t,n,r){if(!e.eventBus)return;let i=Date.now()-t;e.eventBus.emit({name:`telemetry`,payload:{type:`telemetry`,method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?`document`:e.collection?`collection`:`database`,collection:e.collection,document:e.documentId},result:r?void 0:{type:Array.isArray(n)?`array`:typeof n,size:Array.isArray(n)?n.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}async function Qe(e,t){let{offset:n,limit:r}=t,i=[],a=0;return await e(async e=>a<n?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,i.length>=r?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1})),i}async function $e(e,t){let{limit:n,direction:r}=t,i=[];return await e(async e=>(i.push(e),i.length>=n?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1}),r),i}const{match:et}=(0,se.createMatcher)({});async function Q(e){let{collection:t,initial:n,validator:r,store:a,bus:c,lockManager:l}=e,[u,d]=s(n),{value:f,issues:p}=r?await r[`~standard`].validate(u):{value:n,issues:void 0};if(p)throw new o(`INVALID_DATA`,`Invalid data for ${t}`,e.schema,p,p);let m={current:Object.assign(f,d),deleted:!1};m.current.$id===void 0&&(m.current=Object.assign(m.current,{$id:(0,i.v7)(),$created:new Date().toJSON(),$version:1}));let h=e=>{let[t]=s(e);return t},g={save:async e=>{await l.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let i=await a.getById(n);if(i&&i.$version!==r)throw new o(`CONFLICT`,`Version mismatch on ${t}/${n}`);return m.current.$version=(r||0)+1,m.current.$updated=new Date().toJSON(),e?await e.addOp(a,`put`,m.current):await a.put(m.current),c.emit({name:`document:write`,payload:{type:`document:write`,data:m.current,timestamp:Date.now()}}),!0}finally{l.unlock()}},update:async(n,i)=>{let[a,l]=s(Object.assign({},m.current,n)),{value:u,issues:d}=r?await r[`~standard`].validate(a):{value:a,issues:void 0};if(d)throw new o(`INVALID_DATA`,`Invalid update for ${t}`,e.schema,d,d);m.current=Object.assign(u,l);let f=await g.save(i);return f&&c.emit({name:`document:update`,payload:{type:`document:update`,data:m.current,timestamp:Date.now()}}),f},delete:async e=>{await l.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let i=await a.getById(n);if(i&&i.$version!==r)throw new o(`CONFLICT`,`Version mismatch on delete ${t}/${n}`);return e?await e.addOp(a,`delete`,n):await a.delete(n),c.emit({name:`document:delete`,payload:{type:`document:delete`,data:m.current,timestamp:Date.now()}}),m.deleted=!0,!0}finally{l.unlock()}},read:async()=>{let e=m.current.$id,t=await a.getById(e);if(!t)throw Error(`Document not found.`);return m.current={...t},c.emit({name:`document:read`,payload:{type:`document:read`,data:m.current,timestamp:Date.now()}}),m.current},state:()=>h(m.current),$metadata:()=>s(m.current)[1],subscribe:c.subscribe};return new Proxy({},{get(e,t){if([`update`,`delete`,`subscribe`,`read`,`state`,`save`,`$metadata`].includes(t)){let e=g[t];return(...t)=>{if(m.deleted)throw new o(`INVALID_OPERATION`,`Document has been deleted`);return e(...t)}}if(m.deleted)throw new o(`INVALID_OPERATION`,`Document has been deleted`);return Reflect.get(m.current,t)}})}function tt(e,t){return`field`in e&&`operator`in e&&e.operator===`eq`&&`value`in e?e.field:null}async function nt({collection:e,validator:n,bus:r,store:a,pipeline:c,validate:l,schema:u}){let d=new t.Mutex,f={collection:e,validator:l?n:void 0,schema:u,store:a,bus:r,pipeline:c,lockManager:d,valid:!0},p={async validate(e){let t=n[`~standard`].validate(e);return t instanceof Promise?await t:t},create:async(t,c)=>{let[d,p]=s(t),{value:m,issues:h}=l?await n[`~standard`].validate(d):{value:d,issues:void 0};if(h)throw new o(`INVALID_DATA`,`Invalid data for collection '${e}'`,u,h,h);let g=Object.assign(m,p,{$id:(0,i.v7)(),$created:new Date().toJSON(),$version:1});c?await c.addOp(a,`add`,g):await a.add(g),r.emit({name:`document:create`,payload:{type:`document:create`,data:g,timestamp:Date.now()}});let _=await Q({...f,initial:g});return r.emit({name:`collection:read`,payload:{type:`collection:read`,model:e,timestamp:Date.now()}}),_},find:async t=>{let n,i=tt(t,a);if(i)try{let e=t.value;n=(await a.findByIndex(i,e))[0]}catch{n=void 0}if(n===void 0&&(n=await a.cursor(async e=>e&&et(e,t)?{value:e,done:!0}:{value:null,done:!1})??void 0),!n)return null;let o=await Q({...f,initial:n});return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`find`,model:e,timestamp:Date.now()}}),o},filter:async t=>{let n=[],i=tt(t,a);if(i)try{let e=t.value;n=await a.findByIndex(i,e)}catch{n=[]}n.length===0&&await a.cursor(async e=>(e&&et(e,t)&&n.push(e),{value:null,done:!1}));let o=await Promise.all(n.map(e=>Q({...f,initial:e})));return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`filter`,model:e,timestamp:Date.now()}}),o},update:async(t,i,s)=>{await d.lock();try{let c=await p.filter(t);if(c.length===0)return 0;let d=[];for(let t of c){let r=t.state(),a=Object.assign({},r,i);if(l){let t=await n[`~standard`].validate(a);if(t.issues)throw new o(`INVALID_DATA`,`Bulk update failed validation for ${e}`,u,t.issues,t.issues)}let s=t.$metadata(),c=Object.assign(a,t.$metadata(),{$updated:new Date().toJSON(),$version:(s.$version||0)+1});d.push(c)}return s?await s.addOp(a,`put`,d):await a.batch(d.map(e=>({type:`put`,data:e}))),d.forEach(e=>{r.emit({name:`document:update`,payload:{type:`document:update`,data:e,timestamp:Date.now()}})}),d.length}finally{d.unlock()}},delete:async(e,t)=>{await d.lock();try{let n=await p.filter(e),i=n.map(e=>e.$id);return i.length===0?0:(t?await t.addOp(a,`delete`,i):await a.delete(i),n.forEach(e=>{r.emit({name:`document:delete`,payload:{type:`document:delete`,data:e.state(),timestamp:Date.now()}})}),i.length)}finally{d.unlock()}},list:async t=>{let n={total:await a.count(),offset:t.type===`offset`?t.offset:0,limit:t.limit,cursor:t.type===`cursor`?t.cursor:void 0,count:0};return n.total===0?{async next(){return{value:[],done:!0}}}:{async next(){let i=t.type===`offset`?await Qe(a.cursor.bind(a),{...t,offset:n.offset}):await $e(a.cursor.bind(a),{...t,cursor:n.cursor});n.offset+=n.limit,n.count+=i.length;let o=await Promise.all(i.map(e=>Q({...f,initial:e})));return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`list`,model:e,timestamp:Date.now()}}),{value:o,done:n.count>=n.total}}}}},m={...c.wrap(p,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>f.valid=!1};return new Proxy(m,{get(t,n,r){let i=Reflect.get(t,n,r);return typeof i==`function`?(...r)=>{if(!f.valid&&n!==`invalidate`)throw new o(`INVALID_OPERATION`,`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}function rt(e){return typeof e._getIDBConnection==`function`}var it=class{id;staged=[];done=!1;constructor(){this.id=(0,i.v7)()}async addOp(e,t,n){if(this.done)throw new o(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);this.staged.push({store:e,op:{type:t,data:n}})}async commit(){if(this.done)throw new o(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);if(this.done=!0,this.staged.length===0)return;let e=new Map,t=new Map;for(let{store:n,op:r}of this.staged)rt(n)?(e.has(n)||e.set(n,[]),e.get(n).push(r)):(t.has(n)||t.set(n,[]),t.get(n).push(r));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){let t=Array.from(e.keys()).map(e=>e.name()),n=await e.keys().next().value._getIDBConnection();await new Promise((r,i)=>{let a=n.transaction(t,`readwrite`);a.oncomplete=()=>r(),a.onerror=()=>i(a.error??Error(`IDB transaction error`)),a.onabort=()=>i(a.error??Error(`IDB transaction aborted`)),(async()=>{try{for(let[t,n]of e)await t.executeInTransaction(n,a)}catch(e){try{a.abort()}catch{}i(e)}})()})}async commitMemory(e){let t=[];try{for(let[n,r]of e){let e=n._snapshotMemory();t.push({store:n,snapshot:e}),await n.executeInTransaction(r,null)}}catch(e){for(let{store:e,snapshot:n}of t)try{e._rollbackMemory(n)}catch{}throw e}}completed(){return this.done}};function at(e,t,n){let r,i=!1;return new ReadableStream({async pull(a){if(i){a.close();return}let o=0,s=r===void 0?void 0:{lower:r,lowerOpen:!0};try{await t.cursor(async(e,t)=>(a.enqueue(e),r=t,o++,o>=n?{done:!0,value:e}:{done:!1,value:e}),`forward`,s),o<n&&(i=!0)}catch(t){a.error($(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}async function ot(e,t,n,r){let i=t.getReader(),a=[];try{for(;;){let{value:e,done:t}=await i.read();if(t)break;if(!e)continue;let{$version:o}=e;e.$version=(o||0)+1,e.$updated=new Date().toJSON(),a.push(e),a.length>=r&&(await n.batch([{type:`put`,data:a}]),a=[])}a.length>0&&await n.batch([{type:`put`,data:a}])}catch(t){throw $(t,e)}finally{i.releaseLock()}}function $(e,t){return e instanceof o?e:e instanceof Error?new o(`INTERNAL_ERROR`,`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new o(`INTERNAL_ERROR`,`An unexpected error occurred during migration of collection '${t}'`)}async function st(e,t){let n=(0,r.createEventBus)(),i=new Map,a=new Je;a.use(Ye()),e.enableTelemetry&&a.use(Xe);let s=new Map,c=t({...e,collection:`schemas`,keyPath:`name`},[]);await c.open();async function l(n,r=[]){let i=s.get(n);return i||(i=t({...e,collection:n,keyPath:`$id`},r),s.set(n,i)),await i.open(),i}async function u(t){if(i.has(t))return i.get(t);let r=await c.getById(t);if(!r)throw new o(`SCHEMA_NOT_FOUND`,`Collection '${t}' does not exist`);let s=await l(t,r.indexes??[]),u=await nt({collection:t,bus:n,validator:ge(r,e.predicates||{}),validate:!!e.validate,store:s,pipeline:a,schema:r});return n.emit({name:`collection:read`,payload:{type:`collection:read`,schema:{name:t},timestamp:Date.now()}}),i.set(t,u),i.get(t)}async function d(e){return await c.put(e),n.emit({name:`collection:update`,payload:{type:`collection:update`,schema:e,timestamp:Date.now()}}),!0}let f={collection:u,createCollection:async e=>{if(await c.getById(e.name))throw new o(`SCHEMA_ALREADY_EXISTS`,`Collection '${e.name}' already exists`);if(!Pe(e))throw new o(`INVALID_SCHEMA_DEFINITION`,`Invalid schema definition`);await c.put(e);let t=u(e.name);return n.emit({name:`collection:create`,payload:{type:`collection:create`,schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{let t=await c.getById(e);if(!t)throw new o(`SCHEMA_NOT_FOUND`,`Collection '${e}' does not exist`);return await(await l(e,t.indexes??[])).clear(),s.delete(e),await c.delete(e),i.delete(e),n.emit({name:`collection:delete`,payload:{type:`collection:delete`,schema:t,timestamp:Date.now()}}),!0},updateCollection:d,migrateCollection:async(e,t,n=100)=>{let r=i.get(e);r&&(r.invalidate(),i.delete(e));let a=await c.getById(e);if(!a)throw new o(`SCHEMA_NOT_FOUND`,`Schema for '${e}' not found`);let s=await l(e,a.indexes??[]),f=new qe(a);await f.add(t);let p=(await f.dryRun(new ReadableStream({start(e){e.close()}}),`forward`)).newSchema,m=new Set((a.indexes??[]).map(e=>e.name)),h=p.indexes??[],g=new Set(h.map(e=>e.name)),_=h.filter(e=>!m.has(e.name)),v=(a.indexes??[]).filter(e=>!g.has(e.name));await d(p);try{let t=at(e,s,n);await ot(e,await f.migrate(t),s,n)}catch(t){throw $(t,e)}for(let e of _)await s.createIndex(e);for(let e of v)await s.dropIndex(e.name);return await u(e)}},p=a.wrap(f,{eventBus:n}),m={...p,transaction:async e=>{let t=new it;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:n.subscribe,close:()=>{s.clear(),n.clear()},clear:async()=>{await c.clear(),await Promise.all(s.values().map(e=>e.clear())),s.clear()},ensureCollection:async e=>{try{await p.createCollection(e)}catch(e){if(e instanceof o&&e.type===`SCHEMA_ALREADY_EXISTS`)return;throw e}},setupCollections:async e=>{for(let t of e)await m.ensureCollection(t)}};return m}exports.ConnectionManager=p,exports.DEFAULT_KEYPATH=`$id`,exports.DatabaseConnection=st,exports.DatabaseError=o,exports.DatabaseErrorType=a,exports.IndexedDBStore=h,exports.createDocument=Q,exports.createEphemeralStore=f,exports.createIndexedDbStore=_,exports.openCollection=nt;
package/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import{t as e}from"./rolldown-runtime-QTnfLwEv.mjs";import{SystemError as t}from"@asaidimu/utils-error";import{Buffer as n}from"buffer";import{createEventBus as r}from"@asaidimu/utils-events";import{v7 as i}from"uuid";const a=`$id`;let o=function(e){return e.SCHEMA_NOT_FOUND=`SCHEMA_NOT_FOUND`,e.SCHEMA_ALREADY_EXISTS=`SCHEMA_ALREADY_EXISTS`,e.INVALID_SCHEMA_NAME=`INVALID_SCHEMA_NAME`,e.INVALID_SCHEMA_DEFINITION=`INVALID_SCHEMA_DEFINITION`,e.SUBSCRIPTION_FAILED=`SUBSCRIPTION_FAILED`,e.INTERNAL_ERROR=`INTERNAL_ERROR`,e.INVALID_DATA=`INVALID_DATA`,e.CONFLICT=`CONFLICT`,e.TRANSIENT_ERROR=`TRANSIENT_ERROR`,e.TRANSACTION_FAILED=`TRANSACTION_FAILED`,e.CONNECTION_FAILED=`CONNECTION_FAILED`,e.INVALID_OPERATION=`INVALID_OPERATION`,e}({});var s=class extends Error{type;schema;issues;constructor(e,t,n,r,i){super(t,{cause:r}),this.name=`DatabaseError`,this.type=e,this.schema=n,this.issues=i}};function c(e){if(typeof e!=`object`||!e||Array.isArray(e))return[e,{}];let t={};return[Object.entries(e).reduce((e,[n,r])=>(n.startsWith(`$`)?t[n]=r:e[n]=r,e),{}),t]}function l(e,t){if(!(!e||e.$version===void 0||t.$version===void 0)&&t.$version<=e.$version)throw new s(`CONFLICT`,`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function u(e,t){let n=[];for(let r of t.fields){let t=e[r];if(t==null)return null;n.push(String(t))}return n.join(`\0`)}function d(e,t){if(!t.partial)return!0;let{field:n,value:r}=t.partial;return e[n]===r}var f=class{storeName;keyPath;data=new Map;indexes=new Map;nextId=1;constructor(e,t=`$id`,n=[]){this.storeName=e,this.keyPath=t;for(let e of n)this.indexes.set(e.name,{definition:e,map:new Map})}name(){return this.storeName}async open(){}_snapshotMemory(){let e=new Map;for(let[t,n]of this.data)e.set(t,{...n});let t=new Map;for(let[e,n]of this.indexes){let r=new Map;for(let[e,t]of n.map)r.set(e,new Set(t));t.set(e,{definition:n.definition,map:r})}return{data:e,indexes:t,nextId:this.nextId}}_rollbackMemory(e){this.data=e.data,this.indexes=e.indexes,this.nextId=e.nextId}async createIndex(e){if(this.indexes.has(e.name))return;let t={definition:e,map:new Map};this.indexes.set(e.name,t);for(let e of this.data.values())this.indexOne(t,e)}async dropIndex(e){this.indexes.delete(e)}async getByIndex(e,t){return(await this.findByIndex(e,t))[0]}async findByIndex(e,t){let n=this.indexes.get(e);if(!n)throw new s(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=String(t),i=n.map.get(r);if(!i||i.size===0)return[];let a=[];for(let e of i){let t=this.data.get(e);t&&a.push(this.clone(t))}return a}async getByKeyRange(e,t){let n=this.indexes.get(e);if(!n)throw new s(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=[];for(let[e,i]of n.map.entries())if(this.isInKeyRange(e,t))for(let e of i){let t=this.data.get(e);t&&r.push(this.clone(t))}return r}async add(e){let t=Array.isArray(e)?e:[e],n=[];for(let e of t){let t=e[this.keyPath];if((t===void 0||t===``)&&(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new s(`CONFLICT`,`Duplicate key ${t}`);this.enforceUniqueIndexes(e,void 0);let r=Object.freeze(this.clone(e));this.data.set(t,r),this.indexDocument(r),n.push(t)}return Array.isArray(e)?n:n[0]}async put(e){let t=this.getKey(e),n=this.data.get(t);l(n,e),this.enforceUniqueIndexes(e,n),n&&this.unindexDocument(n);let r=Object.freeze(this.clone(e));return this.data.set(t,r),this.indexDocument(r),t}async batch(e){let t=new Map,n=e=>t.has(e)?t.get(e):this.data.get(e);for(let r of e)if(r.type===`add`||r.type===`put`){let e=Array.isArray(r.data)?r.data:[r.data];for(let i of e){let e;if(r.type===`add`){if(e=i[this.keyPath],(e===void 0||e===``)&&(e=String(this.nextId++),i[this.keyPath]=e),n(e)!=null)throw new s(`CONFLICT`,`Duplicate key ${e}`)}else e=this.getKey(i);l(n(e)??void 0,i),t.set(e,Object.freeze(this.clone(i)))}}else{let e=Array.isArray(r.data)?r.data:[r.data];for(let n of e)t.set(n,null)}for(let[e,n]of t.entries()){let t=this.data.get(e);t&&this.unindexDocument(t),n===null?this.data.delete(e):(this.enforceUniqueIndexes(n,t),this.data.set(e,n),this.indexDocument(n))}}async delete(e){let t=Array.isArray(e)?e:[e];for(let e of t){let t=this.data.get(e);t&&this.unindexDocument(t),this.data.delete(e)}}async clear(){this.data.clear();for(let e of this.indexes.values())e.map.clear()}async executeInTransaction(e,t){if(t!==null)throw new s(`INTERNAL_ERROR`,`executeInTransaction called on MemoryStore '${this.storeName}' with a non-null sharedTx`);for(let t of e)if(t.type===`add`)await this.add(t.data);else if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.put(t)}else await this.delete(t.data)}async getById(e){let t=this.data.get(e);return t?this.clone(t):void 0}async getAll(){return Array.from(this.data.values()).map(e=>this.clone(e))}async count(){return this.data.size}async cursor(e,t=`forward`,n){let r=Array.from(this.data.entries());n&&(r=r.filter(([e])=>this.isInKeyRange(e,n)));let i=r.sort(([e],[t])=>e>t?1:e<t?-1:0);t===`backward`&&i.reverse();let a=null,o=0;for(;o<i.length;){let[t,n]=i[o],{value:r,done:s,offset:c}=await e(this.clone(n),t,null);if(a=r,s)break;o+=c&&c>0?c:1}return a}getKey(e){let t=e[this.keyPath];if(t==null)throw new s(`INVALID_DATA`,`Record must have a '${this.keyPath}' property`);return t}clone(e){return{...e}}indexDocument(e){for(let t of this.indexes.values())this.indexOne(t,e)}indexOne(e,t){if(!d(t,e.definition))return;let n=u(t,e.definition);if(n===null)return;let r=t[this.keyPath];if(r===void 0)return;let i=e.map.get(n);i||(i=new Set,e.map.set(n,i)),i.add(r)}unindexDocument(e){let t=e[this.keyPath];if(t!==void 0)for(let n of this.indexes.values()){let r=u(e,n.definition);if(r===null)continue;let i=n.map.get(r);i&&(i.delete(t),i.size===0&&n.map.delete(r))}}enforceUniqueIndexes(e,t){let n=e[this.keyPath],r=t?t[this.keyPath]:void 0;for(let t of this.indexes.values()){if(!t.definition.unique||!d(e,t.definition))continue;let i=u(e,t.definition);if(i===null)continue;let a=t.map.get(i);if(!(!a||a.size===0)){for(let e of a)if(!(e===n||e===r))throw new s(`CONFLICT`,`Unique index '${t.definition.name}' violation: value already exists for field(s) [${t.definition.fields.join(`, `)}]`)}}}isInKeyRange(e,t){if(!t)return!0;let{lower:n,upper:r,lowerOpen:i=!1,upperOpen:a=!1}=t;return(n===void 0||(i?e>n:e>=n))&&(r===void 0||(a?e<r:e<=r))}};function p(e){return new f(e.database,e.keyPath)}var m=class e extends t{constructor(t,n){super({code:`SYNC_ERROR`,message:t,cause:n}),this.name=`SyncError`,Object.setPrototypeOf(this,e.prototype)}},h=class e extends m{constructor(t){super(`[ArtifactContainer] Operation timed out: ${t}`),this.name=`TimeoutError`,Object.setPrototypeOf(this,e.prototype)}},g=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??`macrotask`}async lock(e){if(!this._locked){this._locked=!0;return}if(this.waiters.length>=this._capacity)throw Error(`Mutex queue is full (capacity: ${this._capacity})`);let t,n=new Promise(e=>t=e);if(this.waiters.push(t),e==null){await n;return}let r;await Promise.race([n.then(()=>clearTimeout(r)),new Promise((n,i)=>{r=setTimeout(()=>{let e=this.waiters.indexOf(t);e!==-1&&this.waiters.splice(e,1),i(new h(`Mutex lock timed out`))},e)})])}tryLock(){return this._locked?!1:(this._locked=!0,!0)}unlock(){if(!this._locked)throw Error(`Mutex is not locked`);let e=this.waiters.shift();e?this._yieldMode===`microtask`?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},_=class{mutex=new g({yieldMode:`microtask`});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=!!e,this.throws=!!t}resolve(e){if(this._done)throw Error(`Cannot resolve: operation is already completed.`);if(this.running())throw Error(`Cannot resolve: operation is currently running.`);this._value=e,this._done=!0}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,`Once do() timed out`):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,`Once do() timed out`)):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,`Once do() timed out`)))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){let e=Error(`Cannot execute doSync while an async operation is pending.`);if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){let e=Error(`Cannot execute doSync: lock is currently held.`);if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}let e=Error(`Cannot execute doSync while an async operation is pending.`);if(this.throws)throw e;return{value:null,error:e}}try{let t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return this.promise!==null&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw Error(`Once operation is not yet complete`);if(this._error)throw this._error;return this._value}reset(){if(this.running())throw Error(`Cannot reset Once while an operation is in progress.`);this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,n=`Operation timed out`){if(t==null)return e;let r;return Promise.race([e.then(e=>(clearTimeout(r),e)),new Promise((e,i)=>{r=setTimeout(()=>i(new h(n)),t)})])}},v=class{config;connectionInitializer=new _({retry:!0,throws:!0});schemasStoreName;constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||`schemas`}async openDatabase(){return new Promise((e,t)=>{let n=indexedDB.open(this.config.database);n.onerror=()=>t(Error(`Failed to open database: ${n.error?.message}`)),n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:`name`})},n.onsuccess=()=>e(n.result)})}async upgradeDatabase(e,t){let n=e.version+1;return e.close(),new Promise((e,r)=>{let i=indexedDB.open(this.config.database,n);i.onerror=()=>r(Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{let n=e.target.result,r=e.target.transaction;t(n,r)},i.onsuccess=()=>e(i.result)})}async ensureStore(e,t=`$id`,n=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade(r=>{if(r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:`name`}),!r.objectStoreNames.contains(e)){let i=r.createObjectStore(e,{keyPath:t});for(let e of n){let t=e.fields.length===1?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}})}async createStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);if(i.indexNames.contains(t.name))return;let a=t.fields.length===1?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})})}async dropStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)})}getConnection=async()=>{let e=await this.connectionInitializer.do(async()=>{let e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e});if(e.error)throw new s(`CONNECTION_FAILED`,`Failed to open database: ${this.config.database}`,void 0,e.error);return e.value};async openTransaction(e,t=`readwrite`){return(await this.getConnection()).transaction(e,t)}async upgrade(e){let t=await this.getConnection();this.connectionInitializer.reset();let n=await this.connectionInitializer.do(async()=>await this.upgradeDatabase(t,e));if(n.error)throw new s(`INTERNAL_ERROR`,`Database upgrade failed for ${this.config.database}`,void 0,n.error);return n.value}close(){let e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function y(e){if(e){if(e.lower!==void 0&&e.upper!==void 0)return IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen);if(e.lower!==void 0)return IDBKeyRange.lowerBound(e.lower,e.lowerOpen);if(e.upper!==void 0)return IDBKeyRange.upperBound(e.upper,e.upperOpen)}}var b=class{connectionManager;collection;keyPath;indexes;constructor(e,t,n=`$id`,r=[]){this.connectionManager=e,this.collection=t,this.keyPath=n,this.indexes=r}name(){return this.collection}async _getIDBConnection(){return this.connectionManager.getConnection()}async open(){await this.connectionManager.ensureStore(this.collection,this.keyPath,this.indexes)}async createIndex(e){await this.connectionManager.createStoreIndex(this.collection,e)}async dropIndex(e){await this.connectionManager.dropStoreIndex(this.collection,e)}async getByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.get(t))})}async getByKeyRange(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.getAll(y(t)))})}async findByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))})}async put(e){return this.withTx(`readwrite`,async t=>{let n=e[this.keyPath];return n!==void 0&&l(await this.requestToPromise(t.get(n)),e),this.requestToPromise(t.put(e))})}async add(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e],r=[];for(let e of n){let n=await this.requestToPromise(t.add(e));r.push(n)}return Array.isArray(e)?r:r[0]})}async batch(e){return this.withTx(`readwrite`,async t=>{for(let n of e)if(n.type===`put`||n.type===`add`){let e=Array.isArray(n.data)?n.data:[n.data];for(let r of e)if(n.type===`put`){let e=r[this.keyPath];e!==void 0&&l(await this.requestToPromise(t.get(e)),r),await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{let e=Array.isArray(n.data)?n.data:[n.data];for(let n of e)await this.requestToPromise(t.delete(n))}})}async delete(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e];for(let e of n)await this.requestToPromise(t.delete(e))})}async clear(){return this.withTx(`readwrite`,async e=>{await this.requestToPromise(e.clear())})}async executeInTransaction(e,t){if(!t)throw new s(`INTERNAL_ERROR`,`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);let n=t.objectStore(this.collection);for(let t of e)if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e){let e=t[this.keyPath];e!==void 0&&l(await this.requestToPromise(n.get(e)),t),await this.requestToPromise(n.put(t))}}else if(t.type===`add`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.add(t))}else{let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.delete(t))}}async getById(e){return this.withTx(`readonly`,async t=>this.requestToPromise(t.get(e)))}async getAll(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.getAll()))}async count(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.count()))}async cursor(e,t=`forward`,n){return this.withTx(`readonly`,async r=>{let i=t===`forward`?`next`:`prev`,a=r.openCursor(y(n),i);return new Promise((t,n)=>{let r=null;a.onsuccess=async i=>{let a=i.target.result;if(!a)return t(r);try{let{value:n,done:i,offset:o}=await e(a.value,a.key,a);r=n,i?t(r):o&&o>0?a.advance(o):a.continue()}catch(e){n(e)}},a.onerror=()=>n(this.mapError(a.error))})})}mapError(e){if(e instanceof s)return e;let t=e?.message||`Unknown IndexedDB Error`,n=e?.name||``;return n===`QuotaExceededError`?new s(`INTERNAL_ERROR`,`Storage quota exceeded`):n===`VersionError`?new s(`CONFLICT`,t):n===`InvalidStateError`||n===`TransactionInactiveError`?new s(`TRANSIENT_ERROR`,t):new s(`INTERNAL_ERROR`,t)}async withTx(e,t){let n=await this.connectionManager.getConnection();return new Promise(async(r,i)=>{let a=n.transaction(this.collection,e),o=a.objectStore(this.collection),s,c;a.oncomplete=()=>{c?i(c):r(s)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{let e=t(o,a);s=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch{}}})}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}};const x=new Map,ee=e=>{let t=x.get(e.database);t||(t=new _({retry:!0,throws:!0}),x.set(e.database,t));try{let{value:n,error:r}=t.doSync(()=>new v(e));if(r)throw new s(`CONNECTION_FAILED`,`Failed to initialize connection for database: ${e.database}`,void 0,r);return new b(n,e.collection,e.keyPath)}catch(e){throw e instanceof s?e:new s(`CONNECTION_FAILED`,e instanceof Error?e.message:`An unexpected connection error occurred`,void 0,e)}};var te=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{createEventBus:()=>u}),t.exports=c(l);var u=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error(`EventBus Error:`,e),crossTab:!1,channelName:`event-bus-channel`})=>{let t=new Map,n=[],r=0,i=0,a=new Map,o=new Map,s=null;e.crossTab&&typeof BroadcastChannel<`u`?s=new BroadcastChannel(e.channelName):e.crossTab&&console.warn(`BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.`);let c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{let t=n;n=[],t.forEach(({name:t,payload:n})=>{let r=performance.now();try{(o.get(t)||[]).forEach(e=>e(n))}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-r)})},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{let n=t.get(e);n?o.set(e,Array.from(n)):o.delete(e)};return s&&(s.onmessage=e=>{let{name:t,payload:n}=e.data;(o.get(t)||[]).forEach(e=>e(n))}),{subscribe:(e,n)=>{t.has(e)||t.set(e,new Set);let r=t.get(e);return r.add(n),d(e),()=>{r.delete(n),r.size===0?(t.delete(e),o.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async){n.push({name:t,payload:r}),n.length>=e.batchSize?l():u(),s&&s.postMessage({name:t,payload:r});return}let i=performance.now();try{(o.get(t)||[]).forEach(e=>e(r)),s&&s.postMessage({name:t,payload:r})}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:r,activeSubscriptions:Array.from(t.values()).reduce((e,t)=>e+t.size,0),eventCounts:a,averageEmitDuration:r>0?i/r:0}),clear:()=>{t.clear(),o.clear(),n=[],r=0,i=0,a.clear(),s&&=(s.close(),null)}}};0&&(t.exports={createEventBus:u})})),ne=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{QueryBuilder:()=>u,createJoiner:()=>T,createMatcher:()=>v,createPaginator:()=>de,createProjector:()=>le,createSorter:()=>ce}),t.exports=c(l);var u=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:`offset`,offset:e,limit:t},this}cursor(e,t,n){return this.query.pagination={type:`cursor`,cursor:e,limit:t,direction:n},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`computed`,expression:e,alias:t}),this}case(e,t,n){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`case`,conditions:e,else:t,alias:n}),this}join(e,t,n){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:n,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function d(e){function t(e,t){return f(t)?e[t.field]:p(t)?t.value:g(t)?i(t,e):m(t)?i(t.expression,e):h(t)?a(e,t):t}let n=new Map([[`and`,(e,t)=>t.every(t=>o(e,t))],[`or`,(e,t)=>t.some(t=>o(e,t))],[`not`,(e,t)=>!t.every(t=>o(e,t))],[`nor`,(e,t)=>!t.some(t=>o(e,t))],[`xor`,(e,t)=>t.filter(t=>o(e,t)).length===1]]);function r(e,t){let{operator:r,conditions:i}=t,a=n.get(r);if(a)return a(e,i);throw Error(`Unsupported logical operator: ${r}`)}function i(n,r){let i=n.arguments.map(e=>t(r,e));if(e[n.function])return e[n.function](...i);throw Error(`Function ${n.function} not found!`)}function a(e,t){for(let n of t.conditions)if(o(e,n.when))return n.then;return t.else}function o(n,i){if(_(i))return r(n,i);if(!i||!i.field)return!1;let{field:a,operator:o,value:s}=i,c=n[a],l=t(n,s),u=new Map([[`eq`,(e,t)=>e===t],[`neq`,(e,t)=>e!==t],[`lt`,(e,t)=>e<t],[`lte`,(e,t)=>e<=t],[`gt`,(e,t)=>e>t],[`gte`,(e,t)=>e>=t],[`in`,(e,t)=>Array.isArray(t)&&t.includes(e)],[`nin`,(e,t)=>Array.isArray(t)&&!t.includes(e)],[`contains`,(e,t)=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.includes(s):!1],[`ncontains`,(e,t)=>typeof e==`string`&&!e.includes(t)],[`startswith`,(e,t)=>typeof e==`string`&&e.startsWith(t)],[`endswith`,(e,t)=>typeof e==`string`&&e.endsWith(t)],[`exists`,e=>e!=null],[`nexists`,e=>e==null]]),d=e[o]||u.get(o);if(d)return d(c,l);throw Error(`Unsupported comparison operator: ${o}`)}return{resolve:t,evaluate:o}}function f(e){return e?.type===`field`}function p(e){return e?.type===`value`}function m(e){return e?.type===`computed`}function h(e){return e?.type===`case`}function g(e){return e?.type===`function`}function _(e){return e?e.conditions!==void 0:!1}function v(e){let{evaluate:t}=d(e),n=new WeakMap;function r(e,r){let i=n.get(e);i||(i=new Map,n.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let o=t(e,r);return i.set(a,o),o}return{matcher:r,match:r}}var y=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`JoinError`}},b=e=>e&&`field`in e&&`operator`in e&&`value`in e,x=e=>`operator`in e&&`conditions`in e,ee=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`field`,te=(e,t)=>{if(!e.relation)throw new y(`Join configuration must specify a relation`,`INVALID_CONFIG`);if(!t[e.relation])throw new y(`Collection "${e.relation}" not found in database`,`COLLECTION_NOT_FOUND`);if(e.alias&&typeof e.alias!=`string`)throw new y(`Join alias must be a string`,`INVALID_ALIAS`)},ne=(e,t)=>t.split(`.`).reduce((e,t)=>e?.[t],e),S=(e,t)=>{if(e){if(b(e)&&e){let n=ee(e.value)?ne(t,e.value.field):e.value;return{...e,value:n}}if(x(e)){let n={...e};return e.conditions&&(n.conditions=e.conditions.map(e=>S(e,t))),n}return e}},re=(e,t)=>{if(!e)return{};let n=S(e.filters,t);return{...e,filters:n}},ie=(e,t,n)=>{let r=n.alias||n.relation;return[{...e,[r]:t}]},C=(e,t)=>{let n=new Map;return e.forEach(e=>{let r=e[t];n.has(r)||n.set(r,[]),n.get(r).push(e)}),n},w=async(e,t,n,r)=>{try{if(te(n,e),!Array.isArray(t))throw new y(`Source data must be an array`,`INVALID_SOURCE_DATA`);let i=e[n.relation],a;return n.query?.filters&&b(n.query.filters)&&(a=C(i,n.query.filters.field)),(await Promise.all(t.map(async e=>{let t=re(n.query,e),o;return o=t.filters&&b(t.filters)&&a?.has(t.filters.value)?a.get(t.filters.value)||[]:i.filter(e=>r.matcher(e,t.filters)),ie(e,await[e=>t.sort?r.sorter(e,t.sort):e,e=>t.projection?r.projector(e,t.projection):e,async e=>t.pagination?await r.paginator(e,t.pagination):e].reduce(async(e,t)=>t(await e),Promise.resolve(o)),n)}))).flat()}catch(e){throw e instanceof y?e:new y(`Join operation failed: ${e.message}`,`JOIN_EXECUTION_ERROR`)}},ae=async(e,t,n,r)=>n.reduce(async(t,n)=>w(e,await t,n,r),Promise.resolve(t));function T(){return{join:ae}}var E=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name=`UnsupportedComparisonError`}},D=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name=`InvalidSortDirectionError`}};function oe(e,t,n){if(e===t)return 0;if(e==null||t==null)return e==null?n===`asc`?-1:1:n===`asc`?1:-1;if(typeof e==`string`&&typeof t==`string`)return n===`asc`?e.localeCompare(t):t.localeCompare(e);if(typeof e==`number`&&typeof t==`number`)return n===`asc`?e-t:t-e;throw new E(e,t)}function se(e,t){let n=Array.from(e);return t.length===0?n:n.sort((e,n)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],o=n[t];try{if(i!==`asc`&&i!==`desc`)throw new D(i);let e=oe(a,o,i);if(e!==0)return e}catch(e){throw e instanceof E||e instanceof D?e:Error(`Error comparing field '${t}': ${e.message}`)}}return 0})}function ce(){return{sort:se}}function le(e){let{resolve:t}=d(e);function n(e,t,n){for(let r of t){if(typeof r==`string`){let t=r;n[t]=e[t];continue}for(let[t,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=a(e[t],i))}}function r(e,t,n){Object.keys(n).length===0&&Object.assign(n,e);for(let e of t){if(typeof e==`string`){let t=e;delete n[t];continue}for(let[t,r]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&typeof e==`object`?n[t]=a(e,r):delete n[t]}}}function i(e,n,r){for(let i of n)r[i.alias]=t(e,i)}function a(e,t){let a={};return t.include?.length&&n(e,t.include,a),t.exclude?.length&&r(e,t.exclude,a),t.computed?.length&&i(e,t.computed,a),a}return{project:a}}async function*ue(e,t,n=e=>String(e)){t.type===`offset`?yield*fe(e,t):yield*O(e,t,n)}function de(){return{paginate:ue}}async function*fe(e,t){let{offset:n,limit:r}=t,i=0,a=r,o=[];for await(let t of e){if(a<=0&&(yield o,o=[],a=r),i<n){i++;continue}o.push(t),a--}o.length>0&&(yield o)}async function*O(e,t,n){let{cursor:r,limit:i,direction:a}=t,o=i,s=r===void 0,c=[];if(a===`forward`)for await(let t of e){if(o<=0&&(yield c,c=[],o=i),!s){s=n(t)===r;continue}c.push(t),o--}else{let t=[];for await(let n of e)t.push(n);for(let e=t.length-1;e>=0;e--){let a=t[e];if(!s){s=n(a)===r;continue}c.push(a),o--,o<=0&&(yield c,c=[],o=i)}}c.length>0&&(yield c)}0&&(t.exports={QueryBuilder,createJoiner,createMatcher,createPaginator,createProjector,createSorter})})),S=e(((e,t)=>{t.exports=n;function n(e){var t,n;if(typeof e!=`function`)throw Error(`expected a function but got `+e);return function(){return t?n:(t=!0,n=e.apply(this,arguments),n)}}})),re=e(((e,t)=>{t.exports={encode:e=>new Uint8Array(Buffer.from(e,`utf8`)),decode:e=>Buffer.from(e).toString(`utf8`)}})),ie=e(((e,t)=>{t.exports=n;function n(e,t,n){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,o=n&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!o)return e.apply(i,a)},t),o)return e.apply(this,arguments)}}})),C=e(((e,t)=>{function n(e){if(e.length===0)return`.`;let t=a(e);return t=t.reduce(c,[]),i(...t)}function r(...e){let t=``;for(let r of e)t=r.startsWith(`/`)?r:n(i(t,r));return t}function i(...e){if(e.length===0)return``;let t=e.join(`/`);return t=t.replace(/\/{2,}/g,`/`),t}function a(e){if(e.length===0)return[];if(e===`/`)return[`/`];let t=e.split(`/`);return t[t.length-1]===``&&t.pop(),e[0]===`/`?t[0]=`/`:t[0]!==`.`&&t.unshift(`.`),t}function o(e){let t=e.lastIndexOf(`/`);if(t===-1)throw Error(`Cannot get dirname of "${e}"`);return t===0?`/`:e.slice(0,t)}function s(e){if(e===`/`)throw Error(`Cannot get basename of "${e}"`);let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function c(e,t){if(e.length===0)return e.push(t),e;if(t===`.`)return e;if(t===`..`){if(e.length===1){if(e[0]===`/`)throw Error(`Unable to normalize path - traverses above root directory`);if(e[0]===`.`)return e.push(t),e}return e[e.length-1]===`..`?(e.push(`..`),e):(e.pop(),e)}return e.push(t),e}t.exports={join:i,normalize:n,split:a,basename:s,dirname:o,resolve:r}})),w=e(((e,t)=>{function n(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+`: `+this.message:this.message=e}}}t.exports={EEXIST:n(`EEXIST`),ENOENT:n(`ENOENT`),ENOTDIR:n(`ENOTDIR`),ENOTEMPTY:n(`ENOTEMPTY`),ETIMEDOUT:n(`ETIMEDOUT`),EISDIR:n(`EISDIR`)}})),ae=e(((e,t)=>{let n=C(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:o,EISDIR:s}=w();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:`dir`,size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){e===null?this._root=new Map([[`/`,this._makeRoot()]]):typeof e==`string`?this._root=new Map([[`/`,this._makeRoot(this.parse(e))]]):this._root=e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get(`/`))-1}_countInodes(e){let t=1;for(let[n,r]of e)n!==0&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get(`/`))+1}_maxInode(e){let t=e.get(0).ino;for(let[n,r]of e)n!==0&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get(`/`)){let t=``,n=(e,r)=>{for(let[i,a]of e){if(i===0)continue;let e=a.get(0),o=e.mode.toString(8);t+=`${` `.repeat(r)}${i}\t${o}`,e.type===`file`?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+=`
1
+ import{t as e}from"./rolldown-runtime-QTnfLwEv.mjs";import{Mutex as t,Once as n}from"@asaidimu/utils-sync";import{Buffer as r}from"buffer";import{createEventBus as i}from"@asaidimu/utils-events";import{v7 as a}from"uuid";const o=`$id`;let s=function(e){return e.SCHEMA_NOT_FOUND=`SCHEMA_NOT_FOUND`,e.SCHEMA_ALREADY_EXISTS=`SCHEMA_ALREADY_EXISTS`,e.INVALID_SCHEMA_NAME=`INVALID_SCHEMA_NAME`,e.INVALID_SCHEMA_DEFINITION=`INVALID_SCHEMA_DEFINITION`,e.SUBSCRIPTION_FAILED=`SUBSCRIPTION_FAILED`,e.INTERNAL_ERROR=`INTERNAL_ERROR`,e.INVALID_DATA=`INVALID_DATA`,e.CONFLICT=`CONFLICT`,e.TRANSIENT_ERROR=`TRANSIENT_ERROR`,e.TRANSACTION_FAILED=`TRANSACTION_FAILED`,e.CONNECTION_FAILED=`CONNECTION_FAILED`,e.INVALID_OPERATION=`INVALID_OPERATION`,e}({});var c=class extends Error{type;schema;issues;constructor(e,t,n,r,i){super(t,{cause:r}),this.name=`DatabaseError`,this.type=e,this.schema=n,this.issues=i}};function l(e){if(typeof e!=`object`||!e||Array.isArray(e))return[e,{}];let t={};return[Object.entries(e).reduce((e,[n,r])=>(n.startsWith(`$`)?t[n]=r:e[n]=r,e),{}),t]}function u(e,t){if(!(!e||e.$version===void 0||t.$version===void 0)&&t.$version<=e.$version)throw new c(`CONFLICT`,`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}function d(e,t){let n=[];for(let r of t.fields){let t=e[r];if(t==null)return null;n.push(String(t))}return n.join(`\0`)}function f(e,t){if(!t.partial)return!0;let{field:n,value:r}=t.partial;return e[n]===r}var p=class{storeName;keyPath;data=new Map;indexes=new Map;nextId=1;constructor(e,t=`$id`,n=[]){this.storeName=e,this.keyPath=t;for(let e of n)this.indexes.set(e.name,{definition:e,map:new Map})}name(){return this.storeName}async open(){}_snapshotMemory(){let e=new Map;for(let[t,n]of this.data)e.set(t,{...n});let t=new Map;for(let[e,n]of this.indexes){let r=new Map;for(let[e,t]of n.map)r.set(e,new Set(t));t.set(e,{definition:n.definition,map:r})}return{data:e,indexes:t,nextId:this.nextId}}_rollbackMemory(e){this.data=e.data,this.indexes=e.indexes,this.nextId=e.nextId}async createIndex(e){if(this.indexes.has(e.name))return;let t={definition:e,map:new Map};this.indexes.set(e.name,t);for(let e of this.data.values())this.indexOne(t,e)}async dropIndex(e){this.indexes.delete(e)}async getByIndex(e,t){return(await this.findByIndex(e,t))[0]}async findByIndex(e,t){let n=this.indexes.get(e);if(!n)throw new c(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=String(t),i=n.map.get(r);if(!i||i.size===0)return[];let a=[];for(let e of i){let t=this.data.get(e);t&&a.push(this.clone(t))}return a}async getByKeyRange(e,t){let n=this.indexes.get(e);if(!n)throw new c(`INTERNAL_ERROR`,`Index '${e}' does not exist on this store`);let r=[];for(let[e,i]of n.map.entries())if(this.isInKeyRange(e,t))for(let e of i){let t=this.data.get(e);t&&r.push(this.clone(t))}return r}async add(e){let t=Array.isArray(e)?e:[e],n=[];for(let e of t){let t=e[this.keyPath];if((t===void 0||t===``)&&(t=String(this.nextId++),e[this.keyPath]=t),this.data.has(t))throw new c(`CONFLICT`,`Duplicate key ${t}`);this.enforceUniqueIndexes(e,void 0);let r=Object.freeze(this.clone(e));this.data.set(t,r),this.indexDocument(r),n.push(t)}return Array.isArray(e)?n:n[0]}async put(e){let t=this.getKey(e),n=this.data.get(t);u(n,e),this.enforceUniqueIndexes(e,n),n&&this.unindexDocument(n);let r=Object.freeze(this.clone(e));return this.data.set(t,r),this.indexDocument(r),t}async batch(e){let t=new Map,n=e=>t.has(e)?t.get(e):this.data.get(e);for(let r of e)if(r.type===`add`||r.type===`put`){let e=Array.isArray(r.data)?r.data:[r.data];for(let i of e){let e;if(r.type===`add`){if(e=i[this.keyPath],(e===void 0||e===``)&&(e=String(this.nextId++),i[this.keyPath]=e),n(e)!=null)throw new c(`CONFLICT`,`Duplicate key ${e}`)}else e=this.getKey(i);u(n(e)??void 0,i),t.set(e,Object.freeze(this.clone(i)))}}else{let e=Array.isArray(r.data)?r.data:[r.data];for(let n of e)t.set(n,null)}for(let[e,n]of t.entries()){let t=this.data.get(e);t&&this.unindexDocument(t),n===null?this.data.delete(e):(this.enforceUniqueIndexes(n,t),this.data.set(e,n),this.indexDocument(n))}}async delete(e){let t=Array.isArray(e)?e:[e];for(let e of t){let t=this.data.get(e);t&&this.unindexDocument(t),this.data.delete(e)}}async clear(){this.data.clear();for(let e of this.indexes.values())e.map.clear()}async executeInTransaction(e,t){if(t!==null)throw new c(`INTERNAL_ERROR`,`executeInTransaction called on MemoryStore '${this.storeName}' with a non-null sharedTx`);for(let t of e)if(t.type===`add`)await this.add(t.data);else if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.put(t)}else await this.delete(t.data)}async getById(e){let t=this.data.get(e);return t?this.clone(t):void 0}async getAll(){return Array.from(this.data.values()).map(e=>this.clone(e))}async count(){return this.data.size}async cursor(e,t=`forward`,n){let r=Array.from(this.data.entries());n&&(r=r.filter(([e])=>this.isInKeyRange(e,n)));let i=r.sort(([e],[t])=>e>t?1:e<t?-1:0);t===`backward`&&i.reverse();let a=null,o=0;for(;o<i.length;){let[t,n]=i[o],{value:r,done:s,offset:c}=await e(this.clone(n),t,null);if(a=r,s)break;o+=c&&c>0?c:1}return a}getKey(e){let t=e[this.keyPath];if(t==null)throw new c(`INVALID_DATA`,`Record must have a '${this.keyPath}' property`);return t}clone(e){return{...e}}indexDocument(e){for(let t of this.indexes.values())this.indexOne(t,e)}indexOne(e,t){if(!f(t,e.definition))return;let n=d(t,e.definition);if(n===null)return;let r=t[this.keyPath];if(r===void 0)return;let i=e.map.get(n);i||(i=new Set,e.map.set(n,i)),i.add(r)}unindexDocument(e){let t=e[this.keyPath];if(t!==void 0)for(let n of this.indexes.values()){let r=d(e,n.definition);if(r===null)continue;let i=n.map.get(r);i&&(i.delete(t),i.size===0&&n.map.delete(r))}}enforceUniqueIndexes(e,t){let n=e[this.keyPath],r=t?t[this.keyPath]:void 0;for(let t of this.indexes.values()){if(!t.definition.unique||!f(e,t.definition))continue;let i=d(e,t.definition);if(i===null)continue;let a=t.map.get(i);if(!(!a||a.size===0)){for(let e of a)if(!(e===n||e===r))throw new c(`CONFLICT`,`Unique index '${t.definition.name}' violation: value already exists for field(s) [${t.definition.fields.join(`, `)}]`)}}}isInKeyRange(e,t){if(!t)return!0;let{lower:n,upper:r,lowerOpen:i=!1,upperOpen:a=!1}=t;return(n===void 0||(i?e>n:e>=n))&&(r===void 0||(a?e<r:e<=r))}};function m(e){return new p(e.database,e.keyPath)}var h=class{config;connectionInitializer=new n({retry:!0,throws:!0});schemasStoreName;constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||`schemas`}async openDatabase(){return new Promise((e,t)=>{let n=indexedDB.open(this.config.database);n.onerror=()=>t(Error(`Failed to open database: ${n.error?.message}`)),n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:`name`})},n.onsuccess=()=>e(n.result)})}async upgradeDatabase(e,t){let n=e.version+1;return e.close(),new Promise((e,r)=>{let i=indexedDB.open(this.config.database,n);i.onerror=()=>r(Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{let n=e.target.result,r=e.target.transaction;t(n,r)},i.onsuccess=()=>e(i.result)})}async ensureStore(e,t=`$id`,n=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade(r=>{if(r.objectStoreNames.contains(this.schemasStoreName)||r.createObjectStore(this.schemasStoreName,{keyPath:`name`}),!r.objectStoreNames.contains(e)){let i=r.createObjectStore(e,{keyPath:t});for(let e of n){let t=e.fields.length===1?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}})}async createStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);if(i.indexNames.contains(t.name))return;let a=t.fields.length===1?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})})}async dropStoreIndex(e,t){await this.upgrade((n,r)=>{let i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)})}getConnection=async()=>{let e=await this.connectionInitializer.do(async()=>{let e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e});if(e.error)throw new c(`CONNECTION_FAILED`,`Failed to open database: ${this.config.database}`,void 0,e.error);return e.value};async openTransaction(e,t=`readwrite`){return(await this.getConnection()).transaction(e,t)}async upgrade(e){let t=await this.getConnection();this.connectionInitializer.reset();let n=await this.connectionInitializer.do(async()=>await this.upgradeDatabase(t,e));if(n.error)throw new c(`INTERNAL_ERROR`,`Database upgrade failed for ${this.config.database}`,void 0,n.error);return n.value}close(){let e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function g(e){if(e){if(e.lower!==void 0&&e.upper!==void 0)return IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen);if(e.lower!==void 0)return IDBKeyRange.lowerBound(e.lower,e.lowerOpen);if(e.upper!==void 0)return IDBKeyRange.upperBound(e.upper,e.upperOpen)}}var _=class{connectionManager;collection;keyPath;indexes;constructor(e,t,n=`$id`,r=[]){this.connectionManager=e,this.collection=t,this.keyPath=n,this.indexes=r}name(){return this.collection}async _getIDBConnection(){return this.connectionManager.getConnection()}async open(){await this.connectionManager.ensureStore(this.collection,this.keyPath,this.indexes)}async createIndex(e){await this.connectionManager.createStoreIndex(this.collection,e)}async dropIndex(e){await this.connectionManager.dropStoreIndex(this.collection,e)}async getByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.get(t))})}async getByKeyRange(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e);return this.requestToPromise(r.getAll(g(t)))})}async findByIndex(e,t){return this.withTx(`readonly`,async n=>{let r=n.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))})}async put(e){return this.withTx(`readwrite`,async t=>{let n=e[this.keyPath];return n!==void 0&&u(await this.requestToPromise(t.get(n)),e),this.requestToPromise(t.put(e))})}async add(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e],r=[];for(let e of n){let n=await this.requestToPromise(t.add(e));r.push(n)}return Array.isArray(e)?r:r[0]})}async batch(e){return this.withTx(`readwrite`,async t=>{for(let n of e)if(n.type===`put`||n.type===`add`){let e=Array.isArray(n.data)?n.data:[n.data];for(let r of e)if(n.type===`put`){let e=r[this.keyPath];e!==void 0&&u(await this.requestToPromise(t.get(e)),r),await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{let e=Array.isArray(n.data)?n.data:[n.data];for(let n of e)await this.requestToPromise(t.delete(n))}})}async delete(e){return this.withTx(`readwrite`,async t=>{let n=Array.isArray(e)?e:[e];for(let e of n)await this.requestToPromise(t.delete(e))})}async clear(){return this.withTx(`readwrite`,async e=>{await this.requestToPromise(e.clear())})}async executeInTransaction(e,t){if(!t)throw new c(`INTERNAL_ERROR`,`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);let n=t.objectStore(this.collection);for(let t of e)if(t.type===`put`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e){let e=t[this.keyPath];e!==void 0&&u(await this.requestToPromise(n.get(e)),t),await this.requestToPromise(n.put(t))}}else if(t.type===`add`){let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.add(t))}else{let e=Array.isArray(t.data)?t.data:[t.data];for(let t of e)await this.requestToPromise(n.delete(t))}}async getById(e){return this.withTx(`readonly`,async t=>this.requestToPromise(t.get(e)))}async getAll(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.getAll()))}async count(){return this.withTx(`readonly`,async e=>this.requestToPromise(e.count()))}async cursor(e,t=`forward`,n){return this.withTx(`readonly`,async r=>{let i=t===`forward`?`next`:`prev`,a=r.openCursor(g(n),i);return new Promise((t,n)=>{let r=null;a.onsuccess=async i=>{let a=i.target.result;if(!a)return t(r);try{let{value:n,done:i,offset:o}=await e(a.value,a.key,a);r=n,i?t(r):o&&o>0?a.advance(o):a.continue()}catch(e){n(e)}},a.onerror=()=>n(this.mapError(a.error))})})}mapError(e){if(e instanceof c)return e;let t=e?.message||`Unknown IndexedDB Error`,n=e?.name||``;return n===`QuotaExceededError`?new c(`INTERNAL_ERROR`,`Storage quota exceeded`):n===`VersionError`?new c(`CONFLICT`,t):n===`InvalidStateError`||n===`TransactionInactiveError`?new c(`TRANSIENT_ERROR`,t):new c(`INTERNAL_ERROR`,t)}async withTx(e,t){let n=await this.connectionManager.getConnection();return new Promise(async(r,i)=>{let a=n.transaction(this.collection,e),o=a.objectStore(this.collection),s,c;a.oncomplete=()=>{c?i(c):r(s)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{let e=t(o,a);s=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch{}}})}requestToPromise(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}};const v=new Map,y=e=>{let t=v.get(e.database);t||(t=new n({retry:!0,throws:!0}),v.set(e.database,t));try{let{value:n,error:r}=t.doSync(()=>new h(e));if(r)throw new c(`CONNECTION_FAILED`,`Failed to initialize connection for database: ${e.database}`,void 0,r);return new _(n,e.collection,e.keyPath)}catch(e){throw e instanceof c?e:new c(`CONNECTION_FAILED`,e instanceof Error?e.message:`An unexpected connection error occurred`,void 0,e)}};var b=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{createEventBus:()=>u}),t.exports=c(l);var u=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error(`EventBus Error:`,e),crossTab:!1,channelName:`event-bus-channel`})=>{let t=new Map,n=[],r=0,i=0,a=new Map,o=new Map,s=null;e.crossTab&&typeof BroadcastChannel<`u`?s=new BroadcastChannel(e.channelName):e.crossTab&&console.warn(`BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.`);let c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{let t=n;n=[],t.forEach(({name:t,payload:n})=>{let r=performance.now();try{(o.get(t)||[]).forEach(e=>e(n))}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-r)})},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{let n=t.get(e);n?o.set(e,Array.from(n)):o.delete(e)};return s&&(s.onmessage=e=>{let{name:t,payload:n}=e.data;(o.get(t)||[]).forEach(e=>e(n))}),{subscribe:(e,n)=>{t.has(e)||t.set(e,new Set);let r=t.get(e);return r.add(n),d(e),()=>{r.delete(n),r.size===0?(t.delete(e),o.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async){n.push({name:t,payload:r}),n.length>=e.batchSize?l():u(),s&&s.postMessage({name:t,payload:r});return}let i=performance.now();try{(o.get(t)||[]).forEach(e=>e(r)),s&&s.postMessage({name:t,payload:r})}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-i)},getMetrics:()=>({totalEvents:r,activeSubscriptions:Array.from(t.values()).reduce((e,t)=>e+t.size,0),eventCounts:a,averageEmitDuration:r>0?i/r:0}),clear:()=>{t.clear(),o.clear(),n=[],r=0,i=0,a.clear(),s&&=(s.close(),null)}}};0&&(t.exports={createEventBus:u})})),ee=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{QueryBuilder:()=>u,createJoiner:()=>se,createMatcher:()=>v,createPaginator:()=>O,createProjector:()=>ue,createSorter:()=>le}),t.exports=c(l);var u=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:`offset`,offset:e,limit:t},this}cursor(e,t,n){return this.query.pagination={type:`cursor`,cursor:e,limit:t,direction:n},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`computed`,expression:e,alias:t}),this}case(e,t,n){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:`case`,conditions:e,else:t,alias:n}),this}join(e,t,n){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:n,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function d(e){function t(e,t){return f(t)?e[t.field]:p(t)?t.value:g(t)?i(t,e):m(t)?i(t.expression,e):h(t)?a(e,t):t}let n=new Map([[`and`,(e,t)=>t.every(t=>o(e,t))],[`or`,(e,t)=>t.some(t=>o(e,t))],[`not`,(e,t)=>!t.every(t=>o(e,t))],[`nor`,(e,t)=>!t.some(t=>o(e,t))],[`xor`,(e,t)=>t.filter(t=>o(e,t)).length===1]]);function r(e,t){let{operator:r,conditions:i}=t,a=n.get(r);if(a)return a(e,i);throw Error(`Unsupported logical operator: ${r}`)}function i(n,r){let i=n.arguments.map(e=>t(r,e));if(e[n.function])return e[n.function](...i);throw Error(`Function ${n.function} not found!`)}function a(e,t){for(let n of t.conditions)if(o(e,n.when))return n.then;return t.else}function o(n,i){if(_(i))return r(n,i);if(!i||!i.field)return!1;let{field:a,operator:o,value:s}=i,c=n[a],l=t(n,s),u=new Map([[`eq`,(e,t)=>e===t],[`neq`,(e,t)=>e!==t],[`lt`,(e,t)=>e<t],[`lte`,(e,t)=>e<=t],[`gt`,(e,t)=>e>t],[`gte`,(e,t)=>e>=t],[`in`,(e,t)=>Array.isArray(t)&&t.includes(e)],[`nin`,(e,t)=>Array.isArray(t)&&!t.includes(e)],[`contains`,(e,t)=>typeof e==`string`?e.includes(t):Array.isArray(e)?e.includes(s):!1],[`ncontains`,(e,t)=>typeof e==`string`&&!e.includes(t)],[`startswith`,(e,t)=>typeof e==`string`&&e.startsWith(t)],[`endswith`,(e,t)=>typeof e==`string`&&e.endsWith(t)],[`exists`,e=>e!=null],[`nexists`,e=>e==null]]),d=e[o]||u.get(o);if(d)return d(c,l);throw Error(`Unsupported comparison operator: ${o}`)}return{resolve:t,evaluate:o}}function f(e){return e?.type===`field`}function p(e){return e?.type===`value`}function m(e){return e?.type===`computed`}function h(e){return e?.type===`case`}function g(e){return e?.type===`function`}function _(e){return e?e.conditions!==void 0:!1}function v(e){let{evaluate:t}=d(e),n=new WeakMap;function r(e,r){let i=n.get(e);i||(i=new Map,n.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let o=t(e,r);return i.set(a,o),o}return{matcher:r,match:r}}var y=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`JoinError`}},b=e=>e&&`field`in e&&`operator`in e&&`value`in e,ee=e=>`operator`in e&&`conditions`in e,te=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`field`,ne=(e,t)=>{if(!e.relation)throw new y(`Join configuration must specify a relation`,`INVALID_CONFIG`);if(!t[e.relation])throw new y(`Collection "${e.relation}" not found in database`,`COLLECTION_NOT_FOUND`);if(e.alias&&typeof e.alias!=`string`)throw new y(`Join alias must be a string`,`INVALID_ALIAS`)},re=(e,t)=>t.split(`.`).reduce((e,t)=>e?.[t],e),x=(e,t)=>{if(e){if(b(e)&&e){let n=te(e.value)?re(t,e.value.field):e.value;return{...e,value:n}}if(ee(e)){let n={...e};return e.conditions&&(n.conditions=e.conditions.map(e=>x(e,t))),n}return e}},S=(e,t)=>{if(!e)return{};let n=x(e.filters,t);return{...e,filters:n}},ie=(e,t,n)=>{let r=n.alias||n.relation;return[{...e,[r]:t}]},C=(e,t)=>{let n=new Map;return e.forEach(e=>{let r=e[t];n.has(r)||n.set(r,[]),n.get(r).push(e)}),n},ae=async(e,t,n,r)=>{try{if(ne(n,e),!Array.isArray(t))throw new y(`Source data must be an array`,`INVALID_SOURCE_DATA`);let i=e[n.relation],a;return n.query?.filters&&b(n.query.filters)&&(a=C(i,n.query.filters.field)),(await Promise.all(t.map(async e=>{let t=S(n.query,e),o;return o=t.filters&&b(t.filters)&&a?.has(t.filters.value)?a.get(t.filters.value)||[]:i.filter(e=>r.matcher(e,t.filters)),ie(e,await[e=>t.sort?r.sorter(e,t.sort):e,e=>t.projection?r.projector(e,t.projection):e,async e=>t.pagination?await r.paginator(e,t.pagination):e].reduce(async(e,t)=>t(await e),Promise.resolve(o)),n)}))).flat()}catch(e){throw e instanceof y?e:new y(`Join operation failed: ${e.message}`,`JOIN_EXECUTION_ERROR`)}},oe=async(e,t,n,r)=>n.reduce(async(t,n)=>ae(e,await t,n,r),Promise.resolve(t));function se(){return{join:oe}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name=`UnsupportedComparisonError`}},T=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name=`InvalidSortDirectionError`}};function E(e,t,n){if(e===t)return 0;if(e==null||t==null)return e==null?n===`asc`?-1:1:n===`asc`?1:-1;if(typeof e==`string`&&typeof t==`string`)return n===`asc`?e.localeCompare(t):t.localeCompare(e);if(typeof e==`number`&&typeof t==`number`)return n===`asc`?e-t:t-e;throw new w(e,t)}function ce(e,t){let n=Array.from(e);return t.length===0?n:n.sort((e,n)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],o=n[t];try{if(i!==`asc`&&i!==`desc`)throw new T(i);let e=E(a,o,i);if(e!==0)return e}catch(e){throw e instanceof w||e instanceof T?e:Error(`Error comparing field '${t}': ${e.message}`)}}return 0})}function le(){return{sort:ce}}function ue(e){let{resolve:t}=d(e);function n(e,t,n){for(let r of t){if(typeof r==`string`){let t=r;n[t]=e[t];continue}for(let[t,i]of Object.entries(r))Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=a(e[t],i))}}function r(e,t,n){Object.keys(n).length===0&&Object.assign(n,e);for(let e of t){if(typeof e==`string`){let t=e;delete n[t];continue}for(let[t,r]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&typeof e==`object`?n[t]=a(e,r):delete n[t]}}}function i(e,n,r){for(let i of n)r[i.alias]=t(e,i)}function a(e,t){let a={};return t.include?.length&&n(e,t.include,a),t.exclude?.length&&r(e,t.exclude,a),t.computed?.length&&i(e,t.computed,a),a}return{project:a}}async function*D(e,t,n=e=>String(e)){t.type===`offset`?yield*de(e,t):yield*k(e,t,n)}function O(){return{paginate:D}}async function*de(e,t){let{offset:n,limit:r}=t,i=0,a=r,o=[];for await(let t of e){if(a<=0&&(yield o,o=[],a=r),i<n){i++;continue}o.push(t),a--}o.length>0&&(yield o)}async function*k(e,t,n){let{cursor:r,limit:i,direction:a}=t,o=i,s=r===void 0,c=[];if(a===`forward`)for await(let t of e){if(o<=0&&(yield c,c=[],o=i),!s){s=n(t)===r;continue}c.push(t),o--}else{let t=[];for await(let n of e)t.push(n);for(let e=t.length-1;e>=0;e--){let a=t[e];if(!s){s=n(a)===r;continue}c.push(a),o--,o<=0&&(yield c,c=[],o=i)}}c.length>0&&(yield c)}0&&(t.exports={QueryBuilder,createJoiner,createMatcher,createPaginator,createProjector,createSorter})})),te=e(((e,t)=>{t.exports=n;function n(e){var t,n;if(typeof e!=`function`)throw Error(`expected a function but got `+e);return function(){return t?n:(t=!0,n=e.apply(this,arguments),n)}}})),ne=e(((e,t)=>{t.exports={encode:e=>new Uint8Array(Buffer.from(e,`utf8`)),decode:e=>Buffer.from(e).toString(`utf8`)}})),re=e(((e,t)=>{t.exports=n;function n(e,t,n){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,o=n&&!r;if(clearTimeout(r),r=setTimeout(function(){if(r=null,!o)return e.apply(i,a)},t),o)return e.apply(this,arguments)}}})),x=e(((e,t)=>{function n(e){if(e.length===0)return`.`;let t=a(e);return t=t.reduce(c,[]),i(...t)}function r(...e){let t=``;for(let r of e)t=r.startsWith(`/`)?r:n(i(t,r));return t}function i(...e){if(e.length===0)return``;let t=e.join(`/`);return t=t.replace(/\/{2,}/g,`/`),t}function a(e){if(e.length===0)return[];if(e===`/`)return[`/`];let t=e.split(`/`);return t[t.length-1]===``&&t.pop(),e[0]===`/`?t[0]=`/`:t[0]!==`.`&&t.unshift(`.`),t}function o(e){let t=e.lastIndexOf(`/`);if(t===-1)throw Error(`Cannot get dirname of "${e}"`);return t===0?`/`:e.slice(0,t)}function s(e){if(e===`/`)throw Error(`Cannot get basename of "${e}"`);let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function c(e,t){if(e.length===0)return e.push(t),e;if(t===`.`)return e;if(t===`..`){if(e.length===1){if(e[0]===`/`)throw Error(`Unable to normalize path - traverses above root directory`);if(e[0]===`.`)return e.push(t),e}return e[e.length-1]===`..`?(e.push(`..`),e):(e.pop(),e)}return e.push(t),e}t.exports={join:i,normalize:n,split:a,basename:s,dirname:o,resolve:r}})),S=e(((e,t)=>{function n(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+`: `+this.message:this.message=e}}}t.exports={EEXIST:n(`EEXIST`),ENOENT:n(`ENOENT`),ENOTDIR:n(`ENOTDIR`),ENOTEMPTY:n(`ENOTEMPTY`),ETIMEDOUT:n(`ETIMEDOUT`),EISDIR:n(`EISDIR`)}})),ie=e(((e,t)=>{let n=x(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:o,EISDIR:s}=S();t.exports=class{constructor(){}_makeRoot(e=new Map){return e.set(0,{mode:511,type:`dir`,size:0,ino:0,mtimeMs:Date.now()}),e}activate(e=null){e===null?this._root=new Map([[`/`,this._makeRoot()]]):typeof e==`string`?this._root=new Map([[`/`,this._makeRoot(this.parse(e))]]):this._root=e}get activated(){return!!this._root}deactivate(){this._root=void 0}size(){return this._countInodes(this._root.get(`/`))-1}_countInodes(e){let t=1;for(let[n,r]of e)n!==0&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get(`/`))+1}_maxInode(e){let t=e.get(0).ino;for(let[n,r]of e)n!==0&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get(`/`)){let t=``,n=(e,r)=>{for(let[i,a]of e){if(i===0)continue;let e=a.get(0),o=e.mode.toString(8);t+=`${` `.repeat(r)}${i}\t${o}`,e.type===`file`?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+=`
2
2
  `,n(a,r+1))}};return n(e,0),t}parse(e){let t=0;function n(e){let n=++t,r=e.length===1?`dir`:`file`,[i,a,o]=e;return i=parseInt(i,8),a=a?parseInt(a):0,o=o?parseInt(o):Date.now(),new Map([[0,{mode:i,type:r,size:a,mtimeMs:o,ino:n}]])}let r=e.trim().split(`
3
- `),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of r){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[r,...i]=e.split(` `),o=n(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:o}),a[a.length-2].node.set(r,o)}return i}_lookup(e,t=!0){let r=this._root,a=`/`,o=n.split(e);for(let s=0;s<o.length;++s){let c=o[s];if(r=r.get(c),!r)throw new i(e);if(t||s<o.length-1){let e=r.get(0);if(e.type===`symlink`){let t=n.resolve(a,e.target);r=this._lookup(t)}a=a?n.join(a,c):c}}return r}mkdir(e,{mode:t}){if(e===`/`)throw new r;let i=this._lookup(n.dirname(e)),a=n.basename(e);if(i.has(a))throw new r;let o=new Map,s={mode:t,type:`dir`,size:0,mtimeMs:Date.now(),ino:this.autoinc()};o.set(0,s),i.set(a,o)}rmdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;if(t.size>1)throw new o;let r=this._lookup(n.dirname(e)),i=n.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;return[...t.keys()].filter(e=>typeof e==`string`)}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch{}if(a!==void 0){if(a.type===`dir`)throw new s;r??=a.mode,i=a.ino}r??=438,i??=this.autoinc();let o=this._lookup(n.dirname(e)),c=n.basename(e),l={mode:r,type:`file`,size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,l),o.set(c,u),l}unlink(e){let t=this._lookup(n.dirname(e)),r=n.basename(e);t.delete(r)}rename(e,t){let r=n.basename(t),i=this._lookup(e);this._lookup(n.dirname(t)).set(r,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let r,i;try{let e=this.stat(t);i===null&&(i=e.mode),r=e.ino}catch{}i??=40960,r??=this.autoinc();let a=this._lookup(n.dirname(t)),o=n.basename(t),s={mode:i,type:`symlink`,target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,s),a.set(o,c),s}_du(e){let t=0;for(let[n,r]of e.entries())n===0?t+=r.size:t+=this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}})),T=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class{constructor(e=`keyval-store`,t=`keyval`){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||=new Promise((e,t)=>{let n=indexedDB.open(this._dbName);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=()=>{n.result.createObjectStore(this._storeName)}})}_withIDBStore(e,t){return this._init(),this._dbp.then(n=>new Promise((r,i)=>{let a=n.transaction(this.storeName,e);a.oncomplete=()=>r(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(e=>{e.close(),this._dbp=void 0})}};let n;function r(){return n||=new t,n}function i(e,t=r()){let n;return t._withIDBStore(`readwrite`,t=>{n=t.get(e)}).then(()=>n.result)}function a(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{n.put(t,e)})}function o(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{let r=n.get(e);r.onsuccess=()=>{n.put(t(r.result),e)}})}function s(e,t=r()){return t._withIDBStore(`readwrite`,t=>{t.delete(e)})}function c(e=r()){return e._withIDBStore(`readwrite`,e=>{e.clear()})}function l(e=r()){let t=[];return e._withIDBStore(`readwrite`,e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function u(e=r()){return e._close()}e.Store=t,e.get=i,e.set=a,e.update=o,e.del=s,e.clear=c,e.keys=l,e.close=u})),E=e(((e,t)=>{let n=T();t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename)}saveSuperblock(e){return n.set(`!root`,e,this._store)}loadSuperblock(){return n.get(`!root`,this._store)}readFile(e){return n.get(e,this._store)}writeFile(e,t){return n.set(e,t,this._store)}unlink(e){return n.del(e,this._store)}wipe(){return n.clear(this._store)}close(){return n.close(this._store)}}})),D=e(((e,t)=>{t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+`/.superblock.txt`).then(e=>e.ok?e.text():null)}async readFile(e){let t=await fetch(this._url+e);if(t.status===200)return t.arrayBuffer();throw Error(`ENOENT`)}async sizeFile(e){let t=await fetch(this._url+e,{method:`HEAD`});if(t.status===200)return t.headers.get(`content-length`);throw Error(`ENOENT`)}}})),oe=e(((e,t)=>{let n=T(),r=e=>new Promise(t=>setTimeout(t,e));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){let t=Date.now();return this._lock.expires>t+e?!0:await this.renew()}else return!1}async renew({ttl:e=5e3}={}){let t;return await n.update(`lock`,n=>{let r=Date.now()+e;return t=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:r}:n,this._lock},this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await n.update(`lock`,n=>{let a=Date.now(),o=a+e;return r=n&&n.expires<a,t=n===void 0||r,i=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:o}:n,this._lock},this._store),i)throw Error(`Mutex double-locked`);return t}async wait({interval:e=100,limit:t=6e3,ttl:n}={}){for(;t--;){if(await this.acquire({ttl:n}))return!0;await r(e)}throw Error(`Mutex timeout`)}async release({force:e=!1}={}){let t,r,i;if(await n.update(`lock`,n=>(t=e||n&&n.holder===this._id,r=n===void 0,i=n&&n.holder!==this._id,this._lock=t?void 0:n,this._lock),this._store),await n.close(this._store),!t&&!e){if(r)throw Error(`Mutex double-freed`);if(i)throw Error(`Mutex lost ownership`)}return t}}})),se=e(((e,t)=>{t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(e=>{navigator.locks.request(this._database+`_lock`,{ifAvailable:!0},t=>(this._has=!!t,e(!!t),new Promise(e=>{this._release=e})))})}async wait({timeout:e=6e5}={}){return new Promise((t,n)=>{let r=new AbortController;setTimeout(()=>{r.abort(),n(Error(`Mutex timeout`))},e),navigator.locks.request(this._database+`_lock`,{signal:r.signal},e=>(this._has=!!e,t(!!e),new Promise(e=>{this._release=e})))})}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+`_lock`,{steal:!0},e=>!0)}}})),ce=e(((e,t)=>{let{encode:n,decode:r}=re(),i=ie(),a=ae(),{ENOENT:o,ENOTEMPTY:s,ETIMEDOUT:c}=w(),l=E(),u=D(),d=oe(),f=se(),p=C();t.exports=class{constructor(){this.saveSuperblock=i(()=>{this.flush()},500)}async init(e,{wipe:t,url:n,urlauto:r,fileDbName:i=e,db:o=null,fileStoreName:s=e+`_files`,lockDbName:c=e+`_lock`,lockStoreName:p=e+`_lock`}={}){this._name=e,this._idb=o||new l(i,s),this._mutex=navigator.locks?new f(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:n},this._needsWipe=!!t,n&&(this._http=new u(n),this._urlauto=!!r)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();let e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){let e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,n){let r=p.split(p.dirname(e)),i=r.shift();for(let e of r){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch{}}return this._cache.writeStat(e,t,n)}async readFile(e,t){let n=typeof t==`string`?t:t&&t.encoding;if(n&&n!==`utf8`)throw Error(`Only "utf8" encoding is supported in readFile`);let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;t.type===`symlink`;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&((!a||a.size!=i.byteLength)&&(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),n===`utf8`?i=r(i):i.toString=()=>r(i)),!a)throw new o(e);return i}async writeFile(e,t,r){let{mode:i,encoding:a=`utf8`}=r;if(typeof t==`string`){if(a!==`utf8`)throw Error(`Only "utf8" encoding is supported in writeFile`);t=n(t)}let o=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(o.ino,t)}async unlink(e,t){let n=this._cache.lstat(e);this._cache.unlink(e),n.type!==`symlink`&&await this._idb.unlink(n.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){let{mode:n=511}=t;this._cache.mkdir(e,{mode:n})}rmdir(e,t){if(e===`/`)throw new s;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let n=await this._http.sizeFile(e);await this._writeStat(e,n,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}})),le=e(((e,t)=>{t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return this.type===`file`}isDirectory(){return this.type===`dir`}isSymbolicLink(){return this.type===`symlink`}}})),ue=e(((e,t)=>{let n=ce(),r=le(),i=C();function a(e,t,...n){return e=i.normalize(e),(t===void 0||typeof t==`function`)&&(t={}),typeof t==`string`&&(t={encoding:t}),[e,t,...n]}function o(e,t,n,...r){return e=i.normalize(e),(n===void 0||typeof n==`function`)&&(n={}),typeof n==`string`&&(n={encoding:n}),[e,t,n,...r]}function s(e,t,...n){return[i.normalize(e),i.normalize(t),...n]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,o,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,s,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,s,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new n,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&=(this._initPromiseResolve(),null),t.defer||this.stat(`/`)}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(e=>this._gracefulShutdownResolve=e),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,n){return async(...r)=>{r=t(...r);let i={name:e.name,args:r};this._operations.add(i);try{return await this._activate(),await e.apply(this,r)}finally{this._operations.delete(i),n&&this._backend.saveSuperblock(),this._operations.size===0&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&=(clearTimeout(this._deactivationTimeout),null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||=this._backend.activate?this._backend.activate():Promise.resolve(),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||=this._backend.deactivate?this._backend.deactivate():Promise.resolve(),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,n){return await this._backend.writeFile(e,t,n),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){return new r(await this._backend.stat(e,t))}async lstat(e,t){return new r(await this._backend.lstat(e,t))}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}})),de=e(((e,t)=>{let n=S(),r=ue();function i(e,t){return typeof e==`function`&&(t=e),t=n(t),[(...e)=>t(null,...e),t]}t.exports=class{constructor(...e){this.promises=new r(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,n){let[r,a]=i(t,n);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,n,r){let[a,o]=i(n,r);this.promises.writeFile(e,t,n).then(a).catch(o)}unlink(e,t,n){let[r,a]=i(t,n);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,n){let[r,a]=i(t,n);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,n){let[r,a]=i(t,n);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,n){let[r,a]=i(t,n);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,n){let[r,a]=i(n);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,n){let[r,a]=i(t,n);this.promises.stat(e).then(r).catch(a)}lstat(e,t,n){let[r,a]=i(t,n);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,n){let[r,a]=i(t,n);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,n){let[r,a]=i(n);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,n){let[r,a]=i(t,n);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){let[n,r]=i(t);this.promises.du(e).then(n).catch(r)}flush(e){let[t,n]=i(e);this.promises.flush().then(t).catch(n)}}}));te();var fe=ne();de();var O=class extends Error{constructor(e,t){super(e),this.operation=t,this.name=`JsonPatchError`}};function k(e){let t=pe(e);return t===``?[]:t.substring(1).split(`/`).map(he)}function pe(e){return e===``||e===`/`?``:e.startsWith(`/`)?`/`+e.substring(1).split(`/`).map(me).join(`/`):`/`+e.split(`.`).map(me).join(`/`)}function me(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function he(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}var A=new Map;function j(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)throw new O(`Invalid path - parent not found at ${e}`);if(Array.isArray(n)){let t=e===`-`?n.length:parseInt(e);if(isNaN(t)||t<0||t>n.length)throw new O(`Invalid array index: ${e}`);n=n[t]}else{if(!n.hasOwnProperty(e))throw new O(`Property ${e} not found`);n=n[e]}}return n}function M(e,t){let n=A.get(t)||k(t);if(A.set(t,n),n.length===0)return e;let r=j(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new O(`Invalid array index: ${i}`);return r[e]}return r[i]}function ge(e,t,n){let r=A.get(t)||k(t);A.set(t,r);let i=j(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter(e=>e!==n)):i[a]===n&&delete i[a],e}function N(e,t,n){let r=A.get(t)||k(t);if(A.set(t,r),r.length===0)return n;let i=r.slice(0,-1),a=r[r.length-1],o=j(e,i);if(Array.isArray(o))if(a===`-`)o.push(n);else{let e=parseInt(a);if(e<0||e>o.length)throw new O(`Invalid array index: ${a}`);o.splice(e,0,n)}else o[a]=n;return e}function P(e,t){let n=A.get(t)||k(t);if(A.set(t,n),n.length===0)return;let r=j(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);r.splice(e,1)}else delete r[i];return e}function _e(e,t){let n=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case`add`:n=N(n,e.path,e.value);break;case`remove`:n=P(n,e.path);break;case`removeValue`:n=ge(n,e.path,e.value);break;case`replace`:n=N(P(n,e.path),e.path,e.value);break;case`copy`:{let t=M(n,e.from);n=N(n,e.path,JSON.parse(JSON.stringify(t)));break}case`move`:{let t=M(n,e.from);n=N(n,e.path,t),n=P(n,e.from);break}case`test`:{let t=M(n,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new O(`Test operation failed`);break}default:throw new O(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof O&&(t.operation=e),t}return n}function ve(e,t){let n=[];switch(e.type){case`addField`:n.push({op:`add`,path:`/fields/${e.id}`,value:e.definition});break;case`removeField`:n.push({op:`remove`,path:`/fields/${e.id}`});break;case`modifyField`:{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach(([e,r])=>{n.push({op:`replace`,path:`${t}/${e}`,value:r})});break}case`deprecateField`:n.push({op:`add`,path:`/fields/${e.id}/deprecated`,value:!0});break;case`addIndex`:t.indexes||n.push({op:`add`,path:`/indexes`,value:[]}),n.push({op:`add`,path:`/indexes/-`,value:e.definition});break;case`removeIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/indexes/${r}`});break}case`modifyIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`/indexes/${r}/${e}`,value:t})});break}case`addConstraint`:t.constraints||n.push({op:`add`,path:`/constraints`,value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(e=>{n.push({op:`add`,path:`/constraints/-`,value:e})}):n.push({op:`add`,path:`/constraints/-`,value:e.constraint});break;case`removeConstraint`:{let r=t.constraints?.findIndex(t=>Array.isArray(t)?t.some(t=>t.name===e.name):t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/constraints/${r}`});break}case`modifyConstraint`:{let r=ye(t,e.name);r&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`${r}/${e}`,value:t})});break}}return n}function ye(e,t){if(!e.constraints)return null;for(let n=0;n<e.constraints.length;n++){let r=e.constraints[n];if(r.name===t)return`/constraints/${n}`;if(be(r)){let e=xe(r.rules,t);if(e)return`/constraints/${n}${e}`}}return null}function be(e){return e&&`operator`in e&&`rules`in e}function xe(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(`name`in r&&r.name===t)return`/rules/${n}`;if(be(r)){let e=xe(r.rules,t);if(e)return`/rules/${n}${e}`}}return null}var F=new Map;function I(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function Se(e,t){let n=e=>({value:e}),r=e=>({issues:e}),i=(e,t,n,r)=>{switch(t){case`string`:return typeof e==`string`?[]:[{message:`Expected string, got ${typeof e}`,path:n}];case`number`:return typeof e!=`number`||isNaN(e)?[{message:`Expected number, got ${typeof e}`,path:n}]:[];case`boolean`:return typeof e==`boolean`?[]:[{message:`Expected boolean, got ${typeof e}`,path:n}];case`array`:return Array.isArray(e)?[]:[{message:`Expected array, got ${typeof e}`,path:n}];case`set`:return!Array.isArray(e)||new Set(e).size!==e.length?[{message:`Expected unique array, got ${typeof e}`,path:n}]:[];case`enum`:return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:n}]:[{message:`Enum type requires 'values' definition`,path:n}];case`object`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected object, got ${typeof e}`,path:n}]:[];case`record`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];case`union`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected union (object), got ${typeof e}`,path:n}]:[];case`dynamic`:return console.warn(`Deprecated: 'dynamic' type used. Use 'record' instead.`),typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];default:return[{message:`Unknown type '${t}'`,path:n}]}};function a(e,t,n,r,i){let o=[],s=e.rules.map((e,s)=>{let c=[...r,`rules[${s}]`],l=`${e.name}@${c.join(`.`)}`;if(`rules`in e){if(i.has(l))return!0;i.add(l);let r=a(e,t,n,c,i);return o.push(...r),i.delete(l),r.length===0}else{let r=n[e.predicate];if(!r)return o.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(F.has(i)){let t=F.get(i);return t||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return F.set(i,a),a||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:c}),a}});return(()=>{switch(e.operator){case`and`:return s.every(e=>e);case`or`:return s.some(e=>e);case`not`:return!s.every(e=>e);case`nor`:return!s.some(e=>e);case`xor`:return s.filter(e=>e).length===1}})()||o.push({message:`Constraint group '${e.name}' failed`,path:r}),o}function o(e,t,n,r,s,c=new Set){let l=[];if(`type`in t&&!(`fields`in t)){let o=r.length>0?e[r[r.length-1]]:e;return l.push(...i(o,t.type,r,{values:t.values})),t.constraints&&t.constraints.forEach((e,t)=>{if(`rules`in e)l.push(...a(e,{value:o},n,[...r,`constraints[${t}]`],c));else{let i=n[e.predicate];i?i({data:{value:o},field:`value`,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:[...r,`constraints[${t}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...r,`constraints[${t}]`]})}}),l}let u={};if(`concrete`in t)if(t.concrete===!0||!Array.isArray(t.fields))u=t.fields;else{let n=t.fields,i=n.find(e=>!e.when);i&&Object.assign(u,i.fields);let a=n.find(t=>t.when&&e[t.when.field]!==void 0&&e[t.when.field]===t.when.value);if(a)Object.assign(u,a.fields);else if(!i)return l.push({message:`No matching field set found for discriminated schema`,path:r}),l}else u=t.fields;let d=new Set(Object.values(u).map(e=>e.name));Object.entries(u).forEach(([t,u])=>{let d=[...r,u.name],f=Object.hasOwnProperty.call(e,u.name)?e[u.name]:u.default===void 0?void 0:u.default;u.required&&f==null&&l.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if(u.type===`object`&&p&&!Array.isArray(p)){let e=s[p.id];if(e)if(c.has(p.id))l.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=f&&typeof f==`object`&&!Array.isArray(f)?f:{};l.push(...o(t,e,n,d,s,c)),p.constraints?.forEach((e,r)=>{if(`rules`in e)l.push(...a(e,t,n,[...d,`constraints[${r}]`],c));else{let i=n[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}),c.delete(p.id)}else l.push({message:`Nested schema '${p.id}' not found`,path:d})}if(u.type===`union`&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach((r,i)=>{let l=s[r.id];if(l)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,i.toString()]});else{c.add(r.id);let i=f&&typeof f==`object`&&!Array.isArray(f)?f:{},u=o(i,l,n,d,s,new Set(c));u.length===0&&f!==void 0?(e=!0,r.constraints?.forEach((r,o)=>{if(`rules`in r){let s=a(r,i,n,[...d,`constraints[${o}]`],c);s.length>0&&(e=!1,t.push(...s))}else{let a=n[r.predicate];a&&!a({data:i,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${o}]`]}))}})):f===void 0&&t.push(...u.filter(e=>e.message.includes(`is required`))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,i.toString()]})}),!e&&f!==void 0?(l.push({message:`Value does not match any union schema`,path:d}),l.push(...t)):f===void 0&&l.push(...t)}f!==void 0&&(l.push(...i(f,u.type,d,{values:u.values})),(u.type===`array`||u.type===`set`)&&Array.isArray(f)&&(u.constraints?.forEach((e,t)=>{let r=n[e.predicate];r&&!r({data:{[u.name]:f},field:u.name,arguments:e.parameters})&&l.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})}),u.itemsType&&f.forEach((e,t)=>l.push(...i(e,u.itemsType,[...d,t.toString()]))),p&&!Array.isArray(p)&&(s[p.id]?f.forEach((e,t)=>{typeof e==`object`&&e&&(c.has(p.id)?l.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),l.push(...o(e,s[p.id],n,[...d,t.toString()],s,c)),c.delete(p.id)))}):l.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach((t,r)=>{if(`rules`in t)l.push(...a(t,e,n,[...d,`constraints[${r}]`],c));else{let i=n[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${I(t.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}))});for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&l.push({message:`Unexpected field '${t}'`,path:[...r,t]});return t.constraints?.forEach((t,i)=>{if(`rules`in t)l.push(...a(t,e,n,[...r,`constraints[${i}]`],c));else{let a=n[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${I(t.parameters)}`,path:[...r,`constraints[${i}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...r,`constraints[${i}]`]})}}),l}return e.version!==`1.0.0`&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:i=>{if(typeof i!=`object`||!i)return r([{message:`Input must be an object`,path:[]}]);let a=i,s=o(a,e,t,[],e.nestedSchemas||{});return s.length>0?r(s):n(a)},types:{input:{},output:{}}}}}var L=class extends Error{constructor(e,t){super(e),this.errors=t,this.name=`SchemaValidationError`}},R=e=>({value:e}),z=e=>({issues:e}),B=(e,t,n=!0)=>e===void 0&&!n?[]:typeof e!=`string`||e.trim()===``?[{message:`Must be a non-empty string`,path:[t]}]:[],V=(e,t)=>{let n=[`string`,`number`,`boolean`,`array`,`set`,`enum`,`object`,`record`,`union`,`dynamic`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:e===`dynamic`?[{message:`Field type 'dynamic' is deprecated; use 'record' instead`,path:[t]}]:[]},Ce=(e,t)=>{let n=[`normal`,`unique`,`btree`,`hash`,`spatial`,`fulltext`,`gi`,`expression`,`composite`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},we=(e,t)=>{let n=[`and`,`or`,`not`,`nor`,`xor`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},H=(e,t,n=!1)=>e===void 0&&!n||typeof e==`boolean`?[]:[{message:`Must be a boolean`,path:[t]}],Te=(e,t,n)=>[],U=(e,t,n)=>{let r=[],i=[`predicate`,`name`],a=[`type`,`predicate`,`field`,`parameters`,`name`,`description`,`errorMessage`],o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...B(e.name,`${n}.name`)),r.push(...B(e.predicate,`${n}.predicate`)),e.field!==void 0&&typeof e.field!=`string`&&r.push({message:`Field must be a string`,path:[`${n}.field`]}),e.parameters!==void 0&&r.push(...Te(e.parameters,t,`${n}.parameters`)),r.push(...B(e.description,`${n}.description`,!1)),r.push(...B(e.errorMessage,`${n}.errorMessage`,!1)),r},W=(e,t,n)=>{let r=[],i=[`name`,`operator`,`rules`],a=i,o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...B(e.name,`${n}.name`)),r.push(...we(e.operator,`${n}.operator`)),!Array.isArray(e.rules)||e.rules.length===0?r.push({message:`Rules must be a non-empty array`,path:[`${n}.rules`]}):e.rules.forEach((e,i)=>{`rules`in e?r.push(...W(e,t,`${n}.rules[${i}]`)):r.push(...U(e,t,`${n}.rules[${i}]`))}),r},G=(e,t,n)=>{if(!Array.isArray(e))return[{message:`Must be an array`,path:[n]}];let r=[];return e.forEach((e,i)=>{`rules`in e?r.push(...W(e,t,`${n}[${i}]`)):r.push(...U(e,t,`${n}[${i}]`))}),r},Ee=(e,t)=>{let n=[],r=[`operator`,`field`],i=[`operator`,`field`,`value`,`conditions`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...we(e.operator,`${t}.operator`)),n.push(...B(e.field,`${t}.field`)),e.conditions!==void 0&&(Array.isArray(e.conditions)?e.conditions.forEach((e,r)=>n.push(...Ee(e,`${t}.conditions[${r}]`))):n.push({message:`Conditions must be an array`,path:[`${t}.conditions`]})),n},De=(e,t)=>{let n=[],r=[`fields`,`type`,`name`],i=[`fields`,`type`,`unique`,`partial`,`description`,`order`,`name`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),n.push(...Ce(e.type,`${t}.type`)),(!Array.isArray(e.fields)||e.fields.length===0||!e.fields.every(e=>typeof e==`string`))&&n.push({message:`Fields must be a non-empty array of strings`,path:[`${t}.fields`]}),n.push(...H(e.unique,`${t}.unique`,!1)),e.partial&&n.push(...Ee(e.partial,`${t}.partial`)),n.push(...B(e.description,`${t}.description`,!1)),e.order!==void 0&&![`asc`,`desc`].includes(e.order)&&n.push({message:`Order must be 'asc' or 'desc'`,path:[`${t}.order`]}),n},K=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e))return[{message:`Must be an array`,path:[t]}];let n=[];return e.forEach((e,r)=>n.push(...De(e,`${t}[${r}]`))),n},q=(e,t,n,r,i)=>{let a=[];return e===void 0?[]:(n===`union`&&Array.isArray(e)?(e.length===0&&a.push({message:`Schema array must not be empty for union type`,path:[t]}),e.forEach((e,n)=>{let i=`${t}[${n}]`;a.push(...B(e.id,`${i}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...G(e.constraints,`dynamic`,`${i}.constraints`)),e.indexes&&a.push(...K(e.indexes,`${i}.indexes`))})):(n===`object`||n===`array`&&i===`object`)&&!Array.isArray(e)?(a.push(...B(e.id,`${t}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...G(e.constraints,`dynamic`,`${t}.constraints`)),e.indexes&&a.push(...K(e.indexes,`${t}.indexes`))):a.push({message:`Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'`,path:[t]}),a)},Oe=(e,t,n)=>{if(e===void 0)return[];switch(t){case`string`:if(typeof e!=`string`)return[{message:`Default must be a string`,path:[n]}];break;case`number`:if(typeof e!=`number`)return[{message:`Default must be a number`,path:[n]}];break;case`boolean`:if(typeof e!=`boolean`)return[{message:`Default must be a boolean`,path:[n]}];break;case`array`:case`set`:if(!Array.isArray(e))return[{message:`Default must be an array`,path:[n]}];break;case`enum`:if(!Array.isArray(e)||!e.every(e=>typeof e==`string`||typeof e==`number`))return[{message:`Default must be an array of strings or numbers`,path:[n]}];break;case`object`:case`record`:if(typeof e!=`object`||!e)return[{message:`Default must be an object`,path:[n]}];break;case`union`:case`dynamic`:return[]}return[]},ke=(e,t)=>e===void 0?[]:typeof e!=`object`||!e?[{message:`Hint must be an object`,path:[t]}]:`input`in e&&typeof e.input!=`object`?[{message:`Hint.input must be an object`,path:[`${t}.input`]}]:[],J=(e,t,n)=>{let r=[],i=[`name`,`type`],a=[`name`,`type`,`required`,`constraints`,`default`,`values`,`schema`,`itemsType`,`nestedSchema`,`deprecated`,`reference`,`description`,`unique`,`hint`],o=e;if(i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...V(e.type,`${t}.type`)),r.push(...H(e.required,`${t}.required`,!1)),e.constraints&&r.push(...G(e.constraints,e.type,`${t}.constraints`)),r.push(...Oe(e.default,e.type,`${t}.default`)),e.values!==void 0&&(e.type===`enum`?(!Array.isArray(e.values)||e.values.length===0||!e.values.every(e=>typeof e==`string`||typeof e==`number`))&&r.push({message:`Values must be a non-empty array of strings or numbers`,path:[`${t}.values`]}):r.push({message:`Values is only valid for 'enum' type`,path:[`${t}.values`]})),e.schema!==void 0&&r.push(...q(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...V(e.itemsType,`${t}.itemsType`)),e.nestedSchema){r.push({message:`nestedSchema is deprecated; use schema instead`,path:[`${t}.nestedSchema`]});let i=[`id`],a=[`id`,`constraints`,`indexes`],o=e.nestedSchema;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})}),r.push(...B(e.nestedSchema.id,`${t}.nestedSchema.id`)),n.includes(e.nestedSchema.id)||r.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&r.push(...G(e.nestedSchema.constraints,`dynamic`,`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...K(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...H(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:`reference is deprecated`,path:[`${t}.reference`]});let n=[`schema`,`field`],i=[`schema`,`field`],a=e.reference;n.forEach(e=>{a[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})}),r.push(...B(e.reference.schema,`${t}.reference.schema`)),r.push(...B(e.reference.field,`${t}.reference.field`))}return r.push(...B(e.description,`${t}.description`,!1)),r.push(...H(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...ke(e.hint,`${t}.hint`)),r},Ae=(e,t,n)=>{let r=[];if(`type`in e&&[`string`,`number`,`boolean`,`array`,`set`,`enum`,`record`].includes(e.type)){let i=[`name`,`type`],a=[`name`,`type`,`default`,`schema`,`itemsType`,`constraints`,`description`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...V(e.type,`${t}.type`)),r.push(...Oe(e.default,e.type,`${t}.default`)),e.schema&&r.push(...q(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...V(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...G(e.constraints,e.type,`${t}.constraints`)),r.push(...B(e.description,`${t}.description`,!1)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}else{let i=[`name`],a=[`name`,`description`,`concrete`,`fields`,`indexes`,`constraints`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...H(o.concrete,`${t}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&r.push({message:`Fields must be an object when concrete is true`,path:[`${t}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&r.push({message:`Fields array must not be empty`,path:[`${t}.fields`]}),o.fields.forEach((e,i)=>{let a=`${t}.fields[${i}]`;if(typeof e!=`object`||!e||!(`fields`in e))r.push({message:`Each variant must have a 'fields' property`,path:[a]});else{let t=e.fields;typeof t!=`object`||!t?r.push({message:`Fields must be a non-empty object`,path:[`${a}.fields`]}):Object.entries(t).forEach(([e,t])=>{r.push(...J(t,`${a}.fields.${e}`,n))}),e.when!==void 0&&(typeof e.when!=`object`||e.when===null?r.push({message:`When must be an object`,path:[`${a}.when`]}):r.push(...B(e.when.field,`${a}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!=`object`||o.fields===null?r.push({message:`Fields must be a non-empty object`,path:[`${t}.fields`]}):Object.entries(o.fields).forEach(([e,i])=>{r.push(...J(i,`${t}.fields.${e}`,n))})),r.push(...B(e.description,`${t}.description`,!1)),e.indexes&&r.push(...K(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...G(o.constraints,`dynamic`,`${t}.constraints`)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}return r},je=e=>{if(typeof e!=`object`||!e)return z([{message:`Schema must be an object`,path:[]}]);let t=e,n=[],r=[`name`,`version`,`fields`],i=[`name`,`version`,`description`,`fields`,`nestedSchemas`,`indexes`,`constraints`,`metadata`,`dependencies`,`migrations`,`mock`,`hint`],a=t;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[e]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[e]})}),n.push(...B(t.name,`name`)),n.push(...B(t.version,`version`)),typeof t.fields!=`object`||t.fields===null)n.push({message:`Fields must be a non-empty object`,path:[`fields`]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach(([t,r])=>{n.push(...J(r,`fields.${t}`,e))})}if(t.nestedSchemas!==void 0)if(typeof t.nestedSchemas!=`object`||t.nestedSchemas===null)n.push({message:`NestedSchemas must be an object`,path:[`nestedSchemas`]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach(([t,r])=>n.push(...Ae(r,`nestedSchemas.${t}`,e)))}return n.push(...B(t.description,`description`,!1)),t.indexes&&n.push(...K(t.indexes,`indexes`)),t.constraints&&n.push(...G(t.constraints,`dynamic`,`constraints`)),t.metadata!==void 0&&(typeof t.metadata!=`object`||t.metadata===null)&&n.push({message:`Metadata must be an object`,path:[`metadata`]}),t.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`dependencies`]})),t.migrations!==void 0&&(Array.isArray(t.migrations)?t.migrations.forEach((e,t)=>n.push(...Ne(e,`migrations[${t}]`))):n.push({message:`Migrations must be an array`,path:[`migrations`]})),t.mock!==void 0&&typeof t.mock!=`function`&&n.push({message:`Mock must be a function`,path:[`mock`]}),t.hint&&n.push(...ke(t.hint,`hint`)),n.length>0?z(n):R(t)},Y=(e,t)=>{let n=[];switch(e.type||n.push({message:`type is required`,path:[`${t}.type`]}),e.type){case`modifyProperty`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),(e.changes===void 0||typeof e.changes!=`object`)&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addField`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...J(e.definition,`${t}.definition`,[]));break}case`removeField`:case`deprecateField`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`));break}case`modifyField`:{let r=[`type`,`id`,`changes`],i=[`type`,`id`,`changes`,`nestedSchemaChanges`],a=e;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]}),e.nestedSchemaChanges){let r=[`id`,`constraints`,`indexes`],i=e.nestedSchemaChanges;Object.keys(i).forEach(e=>{r.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})}),n.push(...B(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&n.push(...G(i.constraints,`dynamic`,`${t}.nestedSchemaChanges.constraints`)),i.indexes&&n.push(...K(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case`addIndex`:{let r=[`type`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...De(e.definition,`${t}.definition`));break}case`removeIndex`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`));break}case`modifyIndex`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addConstraint`:{let r=[`type`,`constraint`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),`rules`in e.constraint?n.push(...W(e.constraint,`dynamic`,`${t}.constraint`)):n.push(...U(e.constraint,`dynamic`,`${t}.constraint`));break}case`removeConstraint`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`));break}case`modifyConstraint`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addNestedSchema`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...Ae(e.definition,`${t}.definition`,[]));break}case`removeNestedSchema`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`));break}case`modifyNestedSchema`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}default:n.push({message:`Unknown schema change type`,path:[`${t}.type`]})}return n},Me=(e,t)=>{let n=[],r=[`forward`,`backward`],i=r,a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),typeof e.forward!=`function`&&n.push({message:`Forward must be a function`,path:[`${t}.forward`]}),typeof e.backward!=`function`&&n.push({message:`Backward must be a function`,path:[`${t}.backward`]}),n},Ne=(e,t)=>{let n=[],r=[`id`,`schemaVersion`,`changes`,`description`,`status`,`transform`,`createdAt`,`checksum`],i=[...r,`rollback`,`dependencies`],a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...B(e.schemaVersion,`${t}.schemaVersion`)),n.push(...B(e.description,`${t}.description`));let o=[`pending`,`applied`,`failed`];return o.includes(e.status)||n.push({message:`Status must be one of ${o.join(`, `)}`,path:[`${t}.status`]}),!Array.isArray(e.changes)||e.changes.length===0?n.push({message:`Changes must be a non-empty array`,path:[`${t}.changes`]}):e.changes.forEach((e,r)=>{n.push(...Y(e,`${t}.changes[${r}]`))}),e.rollback!==void 0&&(Array.isArray(e.rollback)?e.rollback.forEach((e,r)=>n.push(...Y(e,`${t}.rollback[${r}]`))):n.push({message:`Rollback must be an array`,path:[`${t}.rollback`]})),typeof e.transform==`string`?n.push(...B(e.transform,`${t}.transform`)):typeof e.transform==`object`&&e.transform!==null?n.push(...Me(e.transform,`${t}.transform`)):n.push({message:`Transform must be a string or object`,path:[`${t}.transform`]}),n.push(...B(e.createdAt,`${t}.createdAt`)),n.push(...B(e.checksum,`${t}.checksum`)),e.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`${t}.dependencies`]})),n},Pe={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:je,types:{input:{},output:{}}}},Fe={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(typeof e!=`object`||!e)return z([{message:`Migration must be an object`,path:[]}]);let t=e,n=Ne(t,``);return n.length>0?z(n):R(t)},types:{input:{},output:{}}}},Ie={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(!Array.isArray(e))return z([{message:`SchemaChanges must be an array`,path:[]}]);let t=e,n=[];return t.forEach((e,t)=>n.push(...Y(e,`[${t}]`))),n.length>0?z(n):R(t)},types:{input:[],output:[]}}};function Le(e){try{return!Fe[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid migration definition`,e instanceof Error?e:Error(String(e)))}}function Re(e){try{return!Ie[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid schema change definition`,e instanceof Error?e:Error(String(e)))}}function ze(e){try{return!Pe[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid schema definition`,e instanceof Error?e:Error(String(e)))}}var Be=async e=>{if(typeof window<`u`&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}else{let{createHash:t}=await import(`crypto`);return t(`sha256`).update(e).digest(`hex`)}};function Ve(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}function He(e,t){if(t&&`field`in e&&e.field){let n=t.fields[e.field];if(n)return n.type}if(`parameters`in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]==`string`)return`string`;if(typeof t==`number`||Array.isArray(t)&&typeof t[0]==`number`)return`number`;if(typeof t==`boolean`)return`boolean`;if(typeof t==`object`&&t){if(`minItems`in t||`maxItems`in t)return`array`;if(`schema`in t)return`object`}}}function Ue(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function We(e,t,n){switch(n){case`string`:if(e instanceof RegExp&&t instanceof RegExp)return e.source!==t.source;if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`number`:if(typeof e==`object`&&typeof t==`object`&&`precision`in e&&`precision`in t)return t.precision<e.precision||(t.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`array`:if(typeof e==`object`&&typeof t==`object`&&`minItems`in e&&`maxItems`in e&&`minItems`in t&&`maxItems`in t)return t.minItems>e.minItems||t.maxItems<e.maxItems;break;case`object`:if(typeof e==`object`&&typeof t==`object`&&`schema`in e&&`schema`in t)return Object.keys(t.schema).length>Object.keys(e.schema).length;break}return!1}function Ge(e,t){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(t.operator&&n[t.operator]>n[e.operator]||t.rules&&t.rules.length>e.rules.length)}function Ke(e,t,n){if(!t)return!0;if(`rules`in t&&`rules`in e)return Ge(t,e);if(`predicate`in e&&e.predicate!==void 0)return!0;if(`parameters`in e&&e.parameters!==void 0){let r=He(t,n);return r?We(t.parameters,e.parameters,r):!0}return!1}function qe(e,t){switch(e.type){case`removeField`:case`removeIndex`:return`major`;case`modifyField`:return Ue(e.changes)?`major`:e.changes.deprecated?`minor`:`patch`;case`modifyIndex`:return e.changes.unique!==void 0||e.changes.fields!==void 0?`major`:`minor`;case`addConstraint`:return`major`;case`removeConstraint`:return`minor`;case`modifyConstraint`:let n=t?.constraints?.find(t=>`name`in t&&t.name===e.name);return Ke(e.changes,n,t)?`major`:`minor`;case`addField`:case`addIndex`:case`deprecateField`:return`minor`;default:throw Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Je(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case`addField`:if(n.has(a.id))throw Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case`removeField`:if(r.has(a.id))throw Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case`modifyField`:if(n.has(a.id))throw Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case`deprecateField`:if(n.has(a.id))throw Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id);break}}function Ye(e){let t=new Set,n=new Set,r=new Set;for(let i of e)switch(i.type){case`addConstraint`:let e=i.constraint,a=(`name`in e,e.name);if(n.has(a))throw Error(`Cannot add previously removed constraint: ${a}`);if(t.has(a))throw Error(`Cannot add already modified constraint: ${a}`);r.add(a);break;case`removeConstraint`:if(r.has(i.name))throw Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw Error(`Cannot remove modified constraint: ${i.name}`);n.add(i.name);break;case`modifyConstraint`:if(n.has(i.name))throw Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name);break}}function Xe(e,t,n){if(t.length===0)throw Error(`No changes provided`);Je(t),Ye(t);let r=Ve(e),i=`patch`;for(let e of t){let t=qe(e,n);if(t===`major`){i=`major`;break}else t===`minor`&&i===`patch`&&(i=`minor`)}switch(i){case`major`:return`${r.major+1}.0.0`;case`minor`:return`${r.major}.${r.minor+1}.0`;case`patch`:return`${r.major}.${r.minor}.${r.patch+1}`}}function X(e,t){let n=e=>e.split(`.`).map(e=>parseInt(e,10)||0),[r,i,a]=n(e),[o,s,c]=n(t);return r-o||i-s||a-c}var Z=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.migrationId=n,this.cause=r,this.name=`MigrationError`}},Ze=(e=>(e.INVALID_SCHEMA=`INVALID_SCHEMA`,e.INVALID_MIGRATION=`INVALID_MIGRATION`,e.CHECKSUM_MISMATCH=`CHECKSUM_MISMATCH`,e.TIMEOUT=`TIMEOUT`,e.MEMORY_LIMIT=`MEMORY_LIMIT`,e.CONCURRENT_OPERATION=`CONCURRENT_OPERATION`,e.TRANSFORM_ERROR=`TRANSFORM_ERROR`,e.VERSION_NOT_FOUND=`VERSION_NOT_FOUND`,e.CIRCULAR_DEPENDENCY=`CIRCULAR_DEPENDENCY`,e.STREAM_ERROR=`STREAM_ERROR`,e.ROLLBACK_ERROR=`ROLLBACK_ERROR`,e.MISSING_TRANSFORM=`MISSING_TRANSFORM`,e))(Ze||{}),Qe=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,n){try{if(!ze(e))throw new Z(`Invalid initial schema`,`INVALID_SCHEMA`);if(this.currentSchema=e,t){if(!t.every(e=>Le(e)))throw new Z(`Invalid migration configuration`,`INVALID_MIGRATION`);this.migrations=t.sort((e,t)=>X(e.schemaVersion,t.schemaVersion))}n&&(this.history=n.sort((e,t)=>X(e.version,t.version)))}catch(e){throw e instanceof Z?e:new Z(`Failed to initialize MigrationEngine`,`INVALID_SCHEMA`,void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{return await Be(JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt}))}catch(t){throw new Z(`Checksum generation failed`,`CHECKSUM_MISMATCH`,e.id,t)}}async add(e){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);if(!e.changes?.length)throw new Z(`Migration must include changes`,`INVALID_MIGRATION`);try{e.changes.forEach(e=>Re(e))}catch(e){throw new Z(`Invalid schema changes`,`INVALID_MIGRATION`,void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:`pending`,rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:``};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,n,r){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(n,r);return{newSchema:a.reduce((e,t)=>{let r=n===`forward`?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)},i),dataPreview:await e.processMigrationList(t,n,a)}}catch(e){throw e instanceof Z?e:new Z(`Dry run failed`,`INVALID_SCHEMA`,void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(n=>{let r=e===`forward`?`pending`:`applied`,i=t?X(n.schemaVersion,t)>=0:!0;return n.status===r&&i}).sort((t,n)=>e===`forward`?t.id.localeCompare(n.id):n.id.localeCompare(t.id))}applySchemaChanges(e,t,n){try{let r=Xe(e.version,t);return t.map(t=>{try{return ve(t,e)}catch(e){throw new Z(`Invalid schema change`,`INVALID_SCHEMA`,n,e)}}).reduce((e,t)=>{try{return _e(e,t)}catch(e){throw new Z(`Failed to apply patch`,`INVALID_SCHEMA`,n,e)}},{...e,version:r})}catch(e){throw e instanceof Z?e:new Z(`Schema update failed`,`INVALID_SCHEMA`,n,e)}}async prepareMigration(){let e=this.migrations.filter(e=>e.status===`pending`);return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema(`forward`);let r=await e.processMigrationList(t,`forward`,n);return this.markMigrationsApplied(n),r}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new Z(`Checksum mismatch`,`CHECKSUM_MISMATCH`,e.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(e=>e.id===t.id)?{...t,status:`applied`}:t)}async rollback(e){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);return this.migrations.filter(e=>e.status===`applied`).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,n){if(this.isProcessing)throw new Z(`Concurrent operation`,`CONCURRENT_OPERATION`);try{let r=this.history.findIndex(e=>e.version===t);if(r===-1)throw Error(`Version ${t} not found in history`);let i=this.migrations.filter(e=>e.schemaVersion===t&&e.status===`applied`).sort((e,t)=>t.id.localeCompare(e.id)),a=this.history.length-r;if(a<0)return n;for(let e=0;e<a;e++)this.transformSchema(`backward`);let o=await e.processMigrationList(n,`backward`,i);return this.migrations=this.migrations.map(e=>e.schemaVersion===t&&e.status===`applied`?{...e,status:`pending`}:e),o}finally{this.isProcessing=!1}}static async processMigrationList(e,t,n){return(await Promise.all(n.map(async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Z(`Failed to resolve transform for migration ${e.id}`,`TRANSFORM_ERROR`,e.id,t)}}))).filter(e=>!!e.transform).reduce((e,{migration:t,transform:n})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await n(e);r.enqueue(t)}catch(e){r.error(new Z(`Data transformation failed for migration ${t.id}`,`TRANSFORM_ERROR`,t.id,e))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform==`string`?e.transform.startsWith(`http://`)||e.transform.startsWith(`https://`)?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let n=await fetch(e);if(!n.ok)throw new Z(`Failed to fetch transform module: ${e}`,`TRANSFORM_ERROR`,void 0);let r=await n.text();if(typeof window<`u`){let e=new Blob([r],{type:`application/javascript`});return(await import(URL.createObjectURL(e))).default[t]}else{let{runInNewContext:n}=await import(`vm`),i={module:{exports:{}},console};return n(r,i,e),i.module.exports[t]}}catch(t){throw new Z(`Failed to load remote transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new Z(`Failed to import local transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}transformSchema(e){try{if(e===`backward`){let e=this.history.pop();if(!e)throw Error(`No previous version`);this.currentSchema=e;return}let t=this.migrations.filter(e=>e.status===`pending`).flatMap(e=>e.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((e,t)=>this.applySchemaChanges(e,[t]),this.currentSchema)}catch(e){throw e instanceof Z?e:new Z(`Schema transformation failed`,`INVALID_SCHEMA`,void 0,e)}}};typeof window<`u`&&(window.Buffer=n);var $e=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let n=-1,r=i=>{if(i<=n)throw Error(`next() called multiple times`);n=i;let a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,()=>r(i+1))}catch(e){return Promise.reject(e)}};return r(0)}wrap(e,t){let n=this;return new Proxy(e,{get(e,r,i){let a=Reflect.get(e,r,i);return typeof a==`function`?function(...i){let o={...t,operation:r.toString(),args:i};return n.execute(o,()=>a.apply(e,i))}:a}})}};const et=(e=3,t=100)=>async(n,r)=>{let i=0;for(;i<e;)try{return await r()}catch(n){if(n instanceof s&&n.type===`TRANSIENT_ERROR`){if(i++,i>=e)throw n;let r=t*2**i+Math.random()*50;await new Promise(e=>setTimeout(e,r))}else throw n}},tt=async(e,t)=>{let n=Date.now();try{let r=await t();return nt(e,n,r,null),r}catch(t){throw nt(e,n,void 0,t),t}};function nt(e,t,n,r){if(!e.eventBus)return;let i=Date.now()-t;e.eventBus.emit({name:`telemetry`,payload:{type:`telemetry`,method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?`document`:e.collection?`collection`:`database`,collection:e.collection,document:e.documentId},result:r?void 0:{type:Array.isArray(n)?`array`:typeof n,size:Array.isArray(n)?n.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}async function rt(e,t){let{offset:n,limit:r}=t,i=[],a=0;return await e(async e=>a<n?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,i.length>=r?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1})),i}async function it(e,t){let{limit:n,direction:r}=t,i=[];return await e(async e=>(i.push(e),i.length>=n?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1}),r),i}const{match:at}=(0,fe.createMatcher)({});async function Q(e){let{collection:t,initial:n,validator:r,store:a,bus:o,lockManager:l}=e,[u,d]=c(n),{value:f,issues:p}=r?await r[`~standard`].validate(u):{value:n,issues:void 0};if(p)throw new s(`INVALID_DATA`,`Invalid data for ${t}`,e.schema,p,p);let m={current:Object.assign(f,d),deleted:!1};m.current.$id===void 0&&(m.current=Object.assign(m.current,{$id:i(),$created:new Date().toJSON(),$version:1}));let h=e=>{let[t]=c(e);return t},g={save:async e=>{await l.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let i=await a.getById(n);if(i&&i.$version!==r)throw new s(`CONFLICT`,`Version mismatch on ${t}/${n}`);return m.current.$version=(r||0)+1,m.current.$updated=new Date().toJSON(),e?await e.addOp(a,`put`,m.current):await a.put(m.current),o.emit({name:`document:write`,payload:{type:`document:write`,data:m.current,timestamp:Date.now()}}),!0}finally{l.unlock()}},update:async(n,i)=>{let[a,l]=c(Object.assign({},m.current,n)),{value:u,issues:d}=r?await r[`~standard`].validate(a):{value:a,issues:void 0};if(d)throw new s(`INVALID_DATA`,`Invalid update for ${t}`,e.schema,d,d);m.current=Object.assign(u,l);let f=await g.save(i);return f&&o.emit({name:`document:update`,payload:{type:`document:update`,data:m.current,timestamp:Date.now()}}),f},delete:async e=>{await l.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let i=await a.getById(n);if(i&&i.$version!==r)throw new s(`CONFLICT`,`Version mismatch on delete ${t}/${n}`);return e?await e.addOp(a,`delete`,n):await a.delete(n),o.emit({name:`document:delete`,payload:{type:`document:delete`,data:m.current,timestamp:Date.now()}}),m.deleted=!0,!0}finally{l.unlock()}},read:async()=>{let e=m.current.$id,t=await a.getById(e);if(!t)throw Error(`Document not found.`);return m.current={...t},o.emit({name:`document:read`,payload:{type:`document:read`,data:m.current,timestamp:Date.now()}}),m.current},state:()=>h(m.current),$metadata:()=>c(m.current)[1],subscribe:o.subscribe};return new Proxy({},{get(e,t){if([`update`,`delete`,`subscribe`,`read`,`state`,`save`,`$metadata`].includes(t)){let e=g[t];return(...t)=>{if(m.deleted)throw new s(`INVALID_OPERATION`,`Document has been deleted`);return e(...t)}}if(m.deleted)throw new s(`INVALID_OPERATION`,`Document has been deleted`);return Reflect.get(m.current,t)}})}function ot(e,t){return`field`in e&&`operator`in e&&e.operator===`eq`&&`value`in e?e.field:null}async function st({collection:e,validator:t,bus:n,store:r,pipeline:a,validate:o,schema:l}){let u=new g,d={collection:e,validator:o?t:void 0,schema:l,store:r,bus:n,pipeline:a,lockManager:u,valid:!0},f={async validate(e){let n=t[`~standard`].validate(e);return n instanceof Promise?await n:n},create:async(a,u)=>{let[f,p]=c(a),{value:m,issues:h}=o?await t[`~standard`].validate(f):{value:f,issues:void 0};if(h)throw new s(`INVALID_DATA`,`Invalid data for collection '${e}'`,l,h,h);let g=Object.assign(m,p,{$id:i(),$created:new Date().toJSON(),$version:1});u?await u.addOp(r,`add`,g):await r.add(g),n.emit({name:`document:create`,payload:{type:`document:create`,data:g,timestamp:Date.now()}});let _=await Q({...d,initial:g});return n.emit({name:`collection:read`,payload:{type:`collection:read`,model:e,timestamp:Date.now()}}),_},find:async t=>{let i,a=ot(t,r);if(a)try{let e=t.value;i=(await r.findByIndex(a,e))[0]}catch{i=void 0}if(i===void 0&&(i=await r.cursor(async e=>e&&at(e,t)?{value:e,done:!0}:{value:null,done:!1})??void 0),!i)return null;let o=await Q({...d,initial:i});return n.emit({name:`collection:read`,payload:{type:`collection:read`,method:`find`,model:e,timestamp:Date.now()}}),o},filter:async t=>{let i=[],a=ot(t,r);if(a)try{let e=t.value;i=await r.findByIndex(a,e)}catch{i=[]}i.length===0&&await r.cursor(async e=>(e&&at(e,t)&&i.push(e),{value:null,done:!1}));let o=await Promise.all(i.map(e=>Q({...d,initial:e})));return n.emit({name:`collection:read`,payload:{type:`collection:read`,method:`filter`,model:e,timestamp:Date.now()}}),o},update:async(i,a,c)=>{await u.lock();try{let u=await f.filter(i);if(u.length===0)return 0;let d=[];for(let n of u){let r=n.state(),i=Object.assign({},r,a);if(o){let n=await t[`~standard`].validate(i);if(n.issues)throw new s(`INVALID_DATA`,`Bulk update failed validation for ${e}`,l,n.issues,n.issues)}let c=n.$metadata(),u=Object.assign(i,n.$metadata(),{$updated:new Date().toJSON(),$version:(c.$version||0)+1});d.push(u)}return c?await c.addOp(r,`put`,d):await r.batch(d.map(e=>({type:`put`,data:e}))),d.forEach(e=>{n.emit({name:`document:update`,payload:{type:`document:update`,data:e,timestamp:Date.now()}})}),d.length}finally{u.unlock()}},delete:async(e,t)=>{await u.lock();try{let i=await f.filter(e),a=i.map(e=>e.$id);return a.length===0?0:(t?await t.addOp(r,`delete`,a):await r.delete(a),i.forEach(e=>{n.emit({name:`document:delete`,payload:{type:`document:delete`,data:e.state(),timestamp:Date.now()}})}),a.length)}finally{u.unlock()}},list:async t=>{let i={total:await r.count(),offset:t.type===`offset`?t.offset:0,limit:t.limit,cursor:t.type===`cursor`?t.cursor:void 0,count:0};return i.total===0?{async next(){return{value:[],done:!0}}}:{async next(){let a=t.type===`offset`?await rt(r.cursor.bind(r),{...t,offset:i.offset}):await it(r.cursor.bind(r),{...t,cursor:i.cursor});i.offset+=i.limit,i.count+=a.length;let o=await Promise.all(a.map(e=>Q({...d,initial:e})));return n.emit({name:`collection:read`,payload:{type:`collection:read`,method:`list`,model:e,timestamp:Date.now()}}),{value:o,done:i.count>=i.total}}}}},p={...a.wrap(f,{collection:e,eventBus:n}),subscribe:n.subscribe,invalidate:()=>d.valid=!1};return new Proxy(p,{get(t,n,r){let i=Reflect.get(t,n,r);return typeof i==`function`?(...r)=>{if(!d.valid&&n!==`invalidate`)throw new s(`INVALID_OPERATION`,`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}function ct(e){return typeof e._getIDBConnection==`function`}var lt=class{id;staged=[];done=!1;constructor(){this.id=i()}async addOp(e,t,n){if(this.done)throw new s(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);this.staged.push({store:e,op:{type:t,data:n}})}async commit(){if(this.done)throw new s(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);if(this.done=!0,this.staged.length===0)return;let e=new Map,t=new Map;for(let{store:n,op:r}of this.staged)ct(n)?(e.has(n)||e.set(n,[]),e.get(n).push(r)):(t.has(n)||t.set(n,[]),t.get(n).push(r));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){let t=Array.from(e.keys()).map(e=>e.name()),n=await e.keys().next().value._getIDBConnection();await new Promise((r,i)=>{let a=n.transaction(t,`readwrite`);a.oncomplete=()=>r(),a.onerror=()=>i(a.error??Error(`IDB transaction error`)),a.onabort=()=>i(a.error??Error(`IDB transaction aborted`)),(async()=>{try{for(let[t,n]of e)await t.executeInTransaction(n,a)}catch(e){try{a.abort()}catch{}i(e)}})()})}async commitMemory(e){let t=[];try{for(let[n,r]of e){let e=n._snapshotMemory();t.push({store:n,snapshot:e}),await n.executeInTransaction(r,null)}}catch(e){for(let{store:e,snapshot:n}of t)try{e._rollbackMemory(n)}catch{}throw e}}completed(){return this.done}};function ut(e,t,n){let r,i=!1;return new ReadableStream({async pull(a){if(i){a.close();return}let o=0,s=r===void 0?void 0:{lower:r,lowerOpen:!0};try{await t.cursor(async(e,t)=>(a.enqueue(e),r=t,o++,o>=n?{done:!0,value:e}:{done:!1,value:e}),`forward`,s),o<n&&(i=!0)}catch(t){a.error($(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}async function dt(e,t,n,r){let i=t.getReader(),a=[];try{for(;;){let{value:e,done:t}=await i.read();if(t)break;if(!e)continue;let{$version:o}=e;e.$version=(o||0)+1,e.$updated=new Date().toJSON(),a.push(e),a.length>=r&&(await n.batch([{type:`put`,data:a}]),a=[])}a.length>0&&await n.batch([{type:`put`,data:a}])}catch(t){throw $(t,e)}finally{i.releaseLock()}}function $(e,t){return e instanceof s?e:e instanceof Error?new s(`INTERNAL_ERROR`,`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new s(`INTERNAL_ERROR`,`An unexpected error occurred during migration of collection '${t}'`)}async function ft(e,t){let n=r(),i=new Map,a=new $e;a.use(et()),e.enableTelemetry&&a.use(tt);let o=new Map,c=t({...e,collection:`schemas`,keyPath:`name`},[]);await c.open();async function l(n,r=[]){let i=o.get(n);return i||(i=t({...e,collection:n,keyPath:`$id`},r),o.set(n,i)),await i.open(),i}async function u(t){if(i.has(t))return i.get(t);let r=await c.getById(t);if(!r)throw new s(`SCHEMA_NOT_FOUND`,`Collection '${t}' does not exist`);let o=await l(t,r.indexes??[]),u=await st({collection:t,bus:n,validator:Se(r,e.predicates||{}),validate:!!e.validate,store:o,pipeline:a,schema:r});return n.emit({name:`collection:read`,payload:{type:`collection:read`,schema:{name:t},timestamp:Date.now()}}),i.set(t,u),i.get(t)}async function d(e){return await c.put(e),n.emit({name:`collection:update`,payload:{type:`collection:update`,schema:e,timestamp:Date.now()}}),!0}let f={collection:u,createCollection:async e=>{if(await c.getById(e.name))throw new s(`SCHEMA_ALREADY_EXISTS`,`Collection '${e.name}' already exists`);if(!ze(e))throw new s(`INVALID_SCHEMA_DEFINITION`,`Invalid schema definition`);await c.put(e);let t=u(e.name);return n.emit({name:`collection:create`,payload:{type:`collection:create`,schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{let t=await c.getById(e);if(!t)throw new s(`SCHEMA_NOT_FOUND`,`Collection '${e}' does not exist`);return await(await l(e,t.indexes??[])).clear(),o.delete(e),await c.delete(e),i.delete(e),n.emit({name:`collection:delete`,payload:{type:`collection:delete`,schema:t,timestamp:Date.now()}}),!0},updateCollection:d,migrateCollection:async(e,t,n=100)=>{let r=i.get(e);r&&(r.invalidate(),i.delete(e));let a=await c.getById(e);if(!a)throw new s(`SCHEMA_NOT_FOUND`,`Schema for '${e}' not found`);let o=await l(e,a.indexes??[]),f=new Qe(a);await f.add(t);let p=(await f.dryRun(new ReadableStream({start(e){e.close()}}),`forward`)).newSchema,m=new Set((a.indexes??[]).map(e=>e.name)),h=p.indexes??[],g=new Set(h.map(e=>e.name)),_=h.filter(e=>!m.has(e.name)),v=(a.indexes??[]).filter(e=>!g.has(e.name));await d(p);try{let t=ut(e,o,n);await dt(e,await f.migrate(t),o,n)}catch(t){throw $(t,e)}for(let e of _)await o.createIndex(e);for(let e of v)await o.dropIndex(e.name);return await u(e)}},p=a.wrap(f,{eventBus:n}),m={...p,transaction:async e=>{let t=new lt;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:n.subscribe,close:()=>{o.clear(),n.clear()},clear:async()=>{await c.clear(),await Promise.all(o.values().map(e=>e.clear())),o.clear()},ensureCollection:async e=>{try{await p.createCollection(e)}catch(e){if(e instanceof s&&e.type===`SCHEMA_ALREADY_EXISTS`)return;throw e}},setupCollections:async e=>{for(let t of e)await m.ensureCollection(t)}};return m}export{v as ConnectionManager,a as DEFAULT_KEYPATH,ft as DatabaseConnection,s as DatabaseError,o as DatabaseErrorType,b as IndexedDBStore,Q as createDocument,p as createEphemeralStore,ee as createIndexedDbStore,st as openCollection};
3
+ `),i=this._makeRoot(),a=[{indent:-1,node:i},{indent:0,node:null}];for(let e of r){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[r,...i]=e.split(` `),o=n(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:o}),a[a.length-2].node.set(r,o)}return i}_lookup(e,t=!0){let r=this._root,a=`/`,o=n.split(e);for(let s=0;s<o.length;++s){let c=o[s];if(r=r.get(c),!r)throw new i(e);if(t||s<o.length-1){let e=r.get(0);if(e.type===`symlink`){let t=n.resolve(a,e.target);r=this._lookup(t)}a=a?n.join(a,c):c}}return r}mkdir(e,{mode:t}){if(e===`/`)throw new r;let i=this._lookup(n.dirname(e)),a=n.basename(e);if(i.has(a))throw new r;let o=new Map,s={mode:t,type:`dir`,size:0,mtimeMs:Date.now(),ino:this.autoinc()};o.set(0,s),i.set(a,o)}rmdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;if(t.size>1)throw new o;let r=this._lookup(n.dirname(e)),i=n.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if(t.get(0).type!==`dir`)throw new a;return[...t.keys()].filter(e=>typeof e==`string`)}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch{}if(a!==void 0){if(a.type===`dir`)throw new s;r??=a.mode,i=a.ino}r??=438,i??=this.autoinc();let o=this._lookup(n.dirname(e)),c=n.basename(e),l={mode:r,type:`file`,size:t,mtimeMs:Date.now(),ino:i},u=new Map;return u.set(0,l),o.set(c,u),l}unlink(e){let t=this._lookup(n.dirname(e)),r=n.basename(e);t.delete(r)}rename(e,t){let r=n.basename(t),i=this._lookup(e);this._lookup(n.dirname(t)).set(r,i),this.unlink(e)}stat(e){return this._lookup(e).get(0)}lstat(e){return this._lookup(e,!1).get(0)}readlink(e){return this._lookup(e,!1).get(0).target}symlink(e,t){let r,i;try{let e=this.stat(t);i===null&&(i=e.mode),r=e.ino}catch{}i??=40960,r??=this.autoinc();let a=this._lookup(n.dirname(t)),o=n.basename(t),s={mode:i,type:`symlink`,target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,s),a.set(o,c),s}_du(e){let t=0;for(let[n,r]of e.entries())n===0?t+=r.size:t+=this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}})),C=e((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class{constructor(e=`keyval-store`,t=`keyval`){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||=new Promise((e,t)=>{let n=indexedDB.open(this._dbName);n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result),n.onupgradeneeded=()=>{n.result.createObjectStore(this._storeName)}})}_withIDBStore(e,t){return this._init(),this._dbp.then(n=>new Promise((r,i)=>{let a=n.transaction(this.storeName,e);a.oncomplete=()=>r(),a.onabort=a.onerror=()=>i(a.error),t(a.objectStore(this.storeName))}))}_close(){return this._init(),this._dbp.then(e=>{e.close(),this._dbp=void 0})}};let n;function r(){return n||=new t,n}function i(e,t=r()){let n;return t._withIDBStore(`readwrite`,t=>{n=t.get(e)}).then(()=>n.result)}function a(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{n.put(t,e)})}function o(e,t,n=r()){return n._withIDBStore(`readwrite`,n=>{let r=n.get(e);r.onsuccess=()=>{n.put(t(r.result),e)}})}function s(e,t=r()){return t._withIDBStore(`readwrite`,t=>{t.delete(e)})}function c(e=r()){return e._withIDBStore(`readwrite`,e=>{e.clear()})}function l(e=r()){let t=[];return e._withIDBStore(`readwrite`,e=>{(e.openKeyCursor||e.openCursor).call(e).onsuccess=function(){this.result&&(t.push(this.result.key),this.result.continue())}}).then(()=>t)}function u(e=r()){return e._close()}e.Store=t,e.get=i,e.set=a,e.update=o,e.del=s,e.clear=c,e.keys=l,e.close=u})),ae=e(((e,t)=>{let n=C();t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename)}saveSuperblock(e){return n.set(`!root`,e,this._store)}loadSuperblock(){return n.get(`!root`,this._store)}readFile(e){return n.get(e,this._store)}writeFile(e,t){return n.set(e,t,this._store)}unlink(e){return n.del(e,this._store)}wipe(){return n.clear(this._store)}close(){return n.close(this._store)}}})),oe=e(((e,t)=>{t.exports=class{constructor(e){this._url=e}loadSuperblock(){return fetch(this._url+`/.superblock.txt`).then(e=>e.ok?e.text():null)}async readFile(e){let t=await fetch(this._url+e);if(t.status===200)return t.arrayBuffer();throw Error(`ENOENT`)}async sizeFile(e){let t=await fetch(this._url+e,{method:`HEAD`});if(t.status===200)return t.headers.get(`content-length`);throw Error(`ENOENT`)}}})),se=e(((e,t)=>{let n=C(),r=e=>new Promise(t=>setTimeout(t,e));t.exports=class{constructor(e,t){this._id=Math.random(),this._database=e,this._storename=t,this._store=new n.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){let t=Date.now();return this._lock.expires>t+e?!0:await this.renew()}else return!1}async renew({ttl:e=5e3}={}){let t;return await n.update(`lock`,n=>{let r=Date.now()+e;return t=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:r}:n,this._lock},this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await n.update(`lock`,n=>{let a=Date.now(),o=a+e;return r=n&&n.expires<a,t=n===void 0||r,i=n&&n.holder===this._id,this._lock=t?{holder:this._id,expires:o}:n,this._lock},this._store),i)throw Error(`Mutex double-locked`);return t}async wait({interval:e=100,limit:t=6e3,ttl:n}={}){for(;t--;){if(await this.acquire({ttl:n}))return!0;await r(e)}throw Error(`Mutex timeout`)}async release({force:e=!1}={}){let t,r,i;if(await n.update(`lock`,n=>(t=e||n&&n.holder===this._id,r=n===void 0,i=n&&n.holder!==this._id,this._lock=t?void 0:n,this._lock),this._store),await n.close(this._store),!t&&!e){if(r)throw Error(`Mutex double-freed`);if(i)throw Error(`Mutex lost ownership`)}return t}}})),w=e(((e,t)=>{t.exports=class{constructor(e){this._id=Math.random(),this._database=e,this._has=!1,this._release=null}async has(){return this._has}async acquire(){return new Promise(e=>{navigator.locks.request(this._database+`_lock`,{ifAvailable:!0},t=>(this._has=!!t,e(!!t),new Promise(e=>{this._release=e})))})}async wait({timeout:e=6e5}={}){return new Promise((t,n)=>{let r=new AbortController;setTimeout(()=>{r.abort(),n(Error(`Mutex timeout`))},e),navigator.locks.request(this._database+`_lock`,{signal:r.signal},e=>(this._has=!!e,t(!!e),new Promise(e=>{this._release=e})))})}async release({force:e=!1}={}){this._has=!1,this._release?this._release():e&&navigator.locks.request(this._database+`_lock`,{steal:!0},e=>!0)}}})),T=e(((e,t)=>{let{encode:n,decode:r}=ne(),i=re(),a=ie(),{ENOENT:o,ENOTEMPTY:s,ETIMEDOUT:c}=S(),l=ae(),u=oe(),d=se(),f=w(),p=x();t.exports=class{constructor(){this.saveSuperblock=i(()=>{this.flush()},500)}async init(e,{wipe:t,url:n,urlauto:r,fileDbName:i=e,db:o=null,fileStoreName:s=e+`_files`,lockDbName:c=e+`_lock`,lockStoreName:p=e+`_lock`}={}){this._name=e,this._idb=o||new l(i,s),this._mutex=navigator.locks?new f(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:n},this._needsWipe=!!t,n&&(this._http=new u(n),this._urlauto=!!r)}async activate(){if(this._cache.activated)return;this._needsWipe&&(this._needsWipe=!1,await this._idb.wipe(),await this._mutex.release({force:!0})),await this._mutex.has()||await this._mutex.wait();let e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){let e=await this._http.loadSuperblock();this._cache.activate(e),await this._saveSuperblock()}else this._cache.activate();if(!await this._mutex.has())throw new c}async deactivate(){await this._mutex.has()&&await this._saveSuperblock(),this._cache.deactivate();try{await this._mutex.release()}catch(e){console.log(e)}await this._idb.close()}async _saveSuperblock(){this._cache.activated&&(this._lastSavedAt=Date.now(),await this._idb.saveSuperblock(this._cache._root))}_writeStat(e,t,n){let r=p.split(p.dirname(e)),i=r.shift();for(let e of r){i=p.join(i,e);try{this._cache.mkdir(i,{mode:511})}catch{}}return this._cache.writeStat(e,t,n)}async readFile(e,t){let n=typeof t==`string`?t:t&&t.encoding;if(n&&n!==`utf8`)throw Error(`Only "utf8" encoding is supported in readFile`);let i=null,a=null;try{a=this._cache.stat(e),i=await this._idb.readFile(a.ino)}catch(e){if(!this._urlauto)throw e}if(!i&&this._http){let t=this._cache.lstat(e);for(;t.type===`symlink`;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);i=await this._http.readFile(e)}if(i&&((!a||a.size!=i.byteLength)&&(a=await this._writeStat(e,i.byteLength,{mode:a?a.mode:438}),this.saveSuperblock()),n===`utf8`?i=r(i):i.toString=()=>r(i)),!a)throw new o(e);return i}async writeFile(e,t,r){let{mode:i,encoding:a=`utf8`}=r;if(typeof t==`string`){if(a!==`utf8`)throw Error(`Only "utf8" encoding is supported in writeFile`);t=n(t)}let o=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(o.ino,t)}async unlink(e,t){let n=this._cache.lstat(e);this._cache.unlink(e),n.type!==`symlink`&&await this._idb.unlink(n.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){let{mode:n=511}=t;this._cache.mkdir(e,{mode:n})}rmdir(e,t){if(e===`/`)throw new s;this._cache.rmdir(e)}rename(e,t){this._cache.rename(e,t)}stat(e,t){return this._cache.stat(e)}lstat(e,t){return this._cache.lstat(e)}readlink(e,t){return this._cache.readlink(e)}symlink(e,t){this._cache.symlink(e,t)}async backFile(e,t){let n=await this._http.sizeFile(e);await this._writeStat(e,n,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}})),E=e(((e,t)=>{t.exports=class{constructor(e){this.type=e.type,this.mode=e.mode,this.size=e.size,this.ino=e.ino,this.mtimeMs=e.mtimeMs,this.ctimeMs=e.ctimeMs||e.mtimeMs,this.uid=1,this.gid=1,this.dev=1}isFile(){return this.type===`file`}isDirectory(){return this.type===`dir`}isSymbolicLink(){return this.type===`symlink`}}})),ce=e(((e,t)=>{let n=T(),r=E(),i=x();function a(e,t,...n){return e=i.normalize(e),(t===void 0||typeof t==`function`)&&(t={}),typeof t==`string`&&(t={encoding:t}),[e,t,...n]}function o(e,t,n,...r){return e=i.normalize(e),(n===void 0||typeof n==`function`)&&(n={}),typeof n==`string`&&(n={encoding:n}),[e,t,n,...r]}function s(e,t,...n){return[i.normalize(e),i.normalize(t),...n]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,a,!1),this.writeFile=this._wrap(this.writeFile,o,!0),this.unlink=this._wrap(this.unlink,a,!0),this.readdir=this._wrap(this.readdir,a,!1),this.mkdir=this._wrap(this.mkdir,a,!0),this.rmdir=this._wrap(this.rmdir,a,!0),this.rename=this._wrap(this.rename,s,!0),this.stat=this._wrap(this.stat,a,!1),this.lstat=this._wrap(this.lstat,a,!1),this.readlink=this._wrap(this.readlink,a,!1),this.symlink=this._wrap(this.symlink,s,!0),this.backFile=this._wrap(this.backFile,a,!0),this.du=this._wrap(this.du,a,!1),this._deactivationPromise=null,this._deactivationTimeout=null,this._activationPromise=null,this._operations=new Set,e&&this.init(e,t)}async init(...e){return this._initPromiseResolve&&await this._initPromise,this._initPromise=this._init(...e),this._initPromise}async _init(e,t={}){await this._gracefulShutdown(),this._activationPromise&&await this._deactivate(),this._backend&&this._backend.destroy&&await this._backend.destroy(),this._backend=t.backend||new n,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&=(this._initPromiseResolve(),null),t.defer||this.stat(`/`)}async _gracefulShutdown(){this._operations.size>0&&(this._isShuttingDown=!0,await new Promise(e=>this._gracefulShutdownResolve=e),this._isShuttingDown=!1,this._gracefulShutdownResolve=null)}_wrap(e,t,n){return async(...r)=>{r=t(...r);let i={name:e.name,args:r};this._operations.add(i);try{return await this._activate(),await e.apply(this,r)}finally{this._operations.delete(i),n&&this._backend.saveSuperblock(),this._operations.size===0&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&=(clearTimeout(this._deactivationTimeout),null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||=this._backend.activate?this._backend.activate():Promise.resolve(),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||=this._backend.deactivate?this._backend.deactivate():Promise.resolve(),this._activationPromise=null,this._gracefulShutdownResolve&&this._gracefulShutdownResolve(),this._deactivationPromise}async readFile(e,t){return this._backend.readFile(e,t)}async writeFile(e,t,n){return await this._backend.writeFile(e,t,n),null}async unlink(e,t){return await this._backend.unlink(e,t),null}async readdir(e,t){return this._backend.readdir(e,t)}async mkdir(e,t){return await this._backend.mkdir(e,t),null}async rmdir(e,t){return await this._backend.rmdir(e,t),null}async rename(e,t){return await this._backend.rename(e,t),null}async stat(e,t){return new r(await this._backend.stat(e,t))}async lstat(e,t){return new r(await this._backend.lstat(e,t))}async readlink(e,t){return this._backend.readlink(e,t)}async symlink(e,t){return await this._backend.symlink(e,t),null}async backFile(e,t){return await this._backend.backFile(e,t),null}async du(e){return this._backend.du(e)}async flush(){return this._backend.flush()}}})),le=e(((e,t)=>{let n=te(),r=ce();function i(e,t){return typeof e==`function`&&(t=e),t=n(t),[(...e)=>t(null,...e),t]}t.exports=class{constructor(...e){this.promises=new r(...e),this.init=this.init.bind(this),this.readFile=this.readFile.bind(this),this.writeFile=this.writeFile.bind(this),this.unlink=this.unlink.bind(this),this.readdir=this.readdir.bind(this),this.mkdir=this.mkdir.bind(this),this.rmdir=this.rmdir.bind(this),this.rename=this.rename.bind(this),this.stat=this.stat.bind(this),this.lstat=this.lstat.bind(this),this.readlink=this.readlink.bind(this),this.symlink=this.symlink.bind(this),this.backFile=this.backFile.bind(this),this.du=this.du.bind(this),this.flush=this.flush.bind(this)}init(e,t){return this.promises.init(e,t)}readFile(e,t,n){let[r,a]=i(t,n);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,n,r){let[a,o]=i(n,r);this.promises.writeFile(e,t,n).then(a).catch(o)}unlink(e,t,n){let[r,a]=i(t,n);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,n){let[r,a]=i(t,n);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,n){let[r,a]=i(t,n);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,n){let[r,a]=i(t,n);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,n){let[r,a]=i(n);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,n){let[r,a]=i(t,n);this.promises.stat(e).then(r).catch(a)}lstat(e,t,n){let[r,a]=i(t,n);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,n){let[r,a]=i(t,n);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,n){let[r,a]=i(n);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,n){let[r,a]=i(t,n);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){let[n,r]=i(t);this.promises.du(e).then(n).catch(r)}flush(e){let[t,n]=i(e);this.promises.flush().then(t).catch(n)}}}));b();var ue=ee();le();var D=class extends Error{constructor(e,t){super(e),this.operation=t,this.name=`JsonPatchError`}};function O(e){let t=de(e);return t===``?[]:t.substring(1).split(`/`).map(fe)}function de(e){return e===``||e===`/`?``:e.startsWith(`/`)?`/`+e.substring(1).split(`/`).map(k).join(`/`):`/`+e.split(`.`).map(k).join(`/`)}function k(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function fe(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}var A=new Map;function j(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)throw new D(`Invalid path - parent not found at ${e}`);if(Array.isArray(n)){let t=e===`-`?n.length:parseInt(e);if(isNaN(t)||t<0||t>n.length)throw new D(`Invalid array index: ${e}`);n=n[t]}else{if(!n.hasOwnProperty(e))throw new D(`Property ${e} not found`);n=n[e]}}return n}function M(e,t){let n=A.get(t)||O(t);if(A.set(t,n),n.length===0)return e;let r=j(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new D(`Invalid array index: ${i}`);return r[e]}return r[i]}function pe(e,t,n){let r=A.get(t)||O(t);A.set(t,r);let i=j(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter(e=>e!==n)):i[a]===n&&delete i[a],e}function N(e,t,n){let r=A.get(t)||O(t);if(A.set(t,r),r.length===0)return n;let i=r.slice(0,-1),a=r[r.length-1],o=j(e,i);if(Array.isArray(o))if(a===`-`)o.push(n);else{let e=parseInt(a);if(e<0||e>o.length)throw new D(`Invalid array index: ${a}`);o.splice(e,0,n)}else o[a]=n;return e}function P(e,t){let n=A.get(t)||O(t);if(A.set(t,n),n.length===0)return;let r=j(e,n.slice(0,-1)),i=n[n.length-1];if(Array.isArray(r)){let e=parseInt(i);r.splice(e,1)}else delete r[i];return e}function me(e,t){let n=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case`add`:n=N(n,e.path,e.value);break;case`remove`:n=P(n,e.path);break;case`removeValue`:n=pe(n,e.path,e.value);break;case`replace`:n=N(P(n,e.path),e.path,e.value);break;case`copy`:{let t=M(n,e.from);n=N(n,e.path,JSON.parse(JSON.stringify(t)));break}case`move`:{let t=M(n,e.from);n=N(n,e.path,t),n=P(n,e.from);break}case`test`:{let t=M(n,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new D(`Test operation failed`);break}default:throw new D(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof D&&(t.operation=e),t}return n}function he(e,t){let n=[];switch(e.type){case`addField`:n.push({op:`add`,path:`/fields/${e.id}`,value:e.definition});break;case`removeField`:n.push({op:`remove`,path:`/fields/${e.id}`});break;case`modifyField`:{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach(([e,r])=>{n.push({op:`replace`,path:`${t}/${e}`,value:r})});break}case`deprecateField`:n.push({op:`add`,path:`/fields/${e.id}/deprecated`,value:!0});break;case`addIndex`:t.indexes||n.push({op:`add`,path:`/indexes`,value:[]}),n.push({op:`add`,path:`/indexes/-`,value:e.definition});break;case`removeIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/indexes/${r}`});break}case`modifyIndex`:{let r=t.indexes?.findIndex(t=>t.name===e.name);r!==void 0&&r>=0&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`/indexes/${r}/${e}`,value:t})});break}case`addConstraint`:t.constraints||n.push({op:`add`,path:`/constraints`,value:[]}),Array.isArray(e.constraint)?e.constraint.forEach(e=>{n.push({op:`add`,path:`/constraints/-`,value:e})}):n.push({op:`add`,path:`/constraints/-`,value:e.constraint});break;case`removeConstraint`:{let r=t.constraints?.findIndex(t=>Array.isArray(t)?t.some(t=>t.name===e.name):t.name===e.name);r!==void 0&&r>=0&&n.push({op:`remove`,path:`/constraints/${r}`});break}case`modifyConstraint`:{let r=ge(t,e.name);r&&Object.entries(e.changes).forEach(([e,t])=>{n.push({op:`replace`,path:`${r}/${e}`,value:t})});break}}return n}function ge(e,t){if(!e.constraints)return null;for(let n=0;n<e.constraints.length;n++){let r=e.constraints[n];if(r.name===t)return`/constraints/${n}`;if(_e(r)){let e=ve(r.rules,t);if(e)return`/constraints/${n}${e}`}}return null}function _e(e){return e&&`operator`in e&&`rules`in e}function ve(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(`name`in r&&r.name===t)return`/rules/${n}`;if(_e(r)){let e=ve(r.rules,t);if(e)return`/rules/${n}${e}`}}return null}var F=new Map;function I(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ye(e,t){let n=e=>({value:e}),r=e=>({issues:e}),i=(e,t,n,r)=>{switch(t){case`string`:return typeof e==`string`?[]:[{message:`Expected string, got ${typeof e}`,path:n}];case`number`:return typeof e!=`number`||isNaN(e)?[{message:`Expected number, got ${typeof e}`,path:n}]:[];case`boolean`:return typeof e==`boolean`?[]:[{message:`Expected boolean, got ${typeof e}`,path:n}];case`array`:return Array.isArray(e)?[]:[{message:`Expected array, got ${typeof e}`,path:n}];case`set`:return!Array.isArray(e)||new Set(e).size!==e.length?[{message:`Expected unique array, got ${typeof e}`,path:n}]:[];case`enum`:return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:n}]:[{message:`Enum type requires 'values' definition`,path:n}];case`object`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected object, got ${typeof e}`,path:n}]:[];case`record`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];case`union`:return typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected union (object), got ${typeof e}`,path:n}]:[];case`dynamic`:return console.warn(`Deprecated: 'dynamic' type used. Use 'record' instead.`),typeof e!=`object`||!e||Array.isArray(e)?[{message:`Expected record (object), got ${typeof e}`,path:n}]:[];default:return[{message:`Unknown type '${t}'`,path:n}]}};function a(e,t,n,r,i){let o=[],s=e.rules.map((e,s)=>{let c=[...r,`rules[${s}]`],l=`${e.name}@${c.join(`.`)}`;if(`rules`in e){if(i.has(l))return!0;i.add(l);let r=a(e,t,n,c,i);return o.push(...r),i.delete(l),r.length===0}else{let r=n[e.predicate];if(!r)return o.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(F.has(i)){let t=F.get(i);return t||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return F.set(i,a),a||o.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:c}),a}});return(()=>{switch(e.operator){case`and`:return s.every(e=>e);case`or`:return s.some(e=>e);case`not`:return!s.every(e=>e);case`nor`:return!s.some(e=>e);case`xor`:return s.filter(e=>e).length===1}})()||o.push({message:`Constraint group '${e.name}' failed`,path:r}),o}function o(e,t,n,r,s,c=new Set){let l=[];if(`type`in t&&!(`fields`in t)){let o=r.length>0?e[r[r.length-1]]:e;return l.push(...i(o,t.type,r,{values:t.values})),t.constraints&&t.constraints.forEach((e,t)=>{if(`rules`in e)l.push(...a(e,{value:o},n,[...r,`constraints[${t}]`],c));else{let i=n[e.predicate];i?i({data:{value:o},field:`value`,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:[...r,`constraints[${t}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...r,`constraints[${t}]`]})}}),l}let u={};if(`concrete`in t)if(t.concrete===!0||!Array.isArray(t.fields))u=t.fields;else{let n=t.fields,i=n.find(e=>!e.when);i&&Object.assign(u,i.fields);let a=n.find(t=>t.when&&e[t.when.field]!==void 0&&e[t.when.field]===t.when.value);if(a)Object.assign(u,a.fields);else if(!i)return l.push({message:`No matching field set found for discriminated schema`,path:r}),l}else u=t.fields;let d=new Set(Object.values(u).map(e=>e.name));Object.entries(u).forEach(([t,u])=>{let d=[...r,u.name],f=Object.hasOwnProperty.call(e,u.name)?e[u.name]:u.default===void 0?void 0:u.default;u.required&&f==null&&l.push({message:`Field '${u.name}' is required`,path:d});let p=u.schema||u.nestedSchema;if(u.type===`object`&&p&&!Array.isArray(p)){let e=s[p.id];if(e)if(c.has(p.id))l.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=f&&typeof f==`object`&&!Array.isArray(f)?f:{};l.push(...o(t,e,n,d,s,c)),p.constraints?.forEach((e,r)=>{if(`rules`in e)l.push(...a(e,t,n,[...d,`constraints[${r}]`],c));else{let i=n[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||l.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${I(e.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}),c.delete(p.id)}else l.push({message:`Nested schema '${p.id}' not found`,path:d})}if(u.type===`union`&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach((r,i)=>{let l=s[r.id];if(l)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,i.toString()]});else{c.add(r.id);let i=f&&typeof f==`object`&&!Array.isArray(f)?f:{},u=o(i,l,n,d,s,new Set(c));u.length===0&&f!==void 0?(e=!0,r.constraints?.forEach((r,o)=>{if(`rules`in r){let s=a(r,i,n,[...d,`constraints[${o}]`],c);s.length>0&&(e=!1,t.push(...s))}else{let a=n[r.predicate];a&&!a({data:i,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${o}]`]}))}})):f===void 0&&t.push(...u.filter(e=>e.message.includes(`is required`))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,i.toString()]})}),!e&&f!==void 0?(l.push({message:`Value does not match any union schema`,path:d}),l.push(...t)):f===void 0&&l.push(...t)}f!==void 0&&(l.push(...i(f,u.type,d,{values:u.values})),(u.type===`array`||u.type===`set`)&&Array.isArray(f)&&(u.constraints?.forEach((e,t)=>{let r=n[e.predicate];r&&!r({data:{[u.name]:f},field:u.name,arguments:e.parameters})&&l.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${u.name}'`,path:[...d,`constraints[${t}]`]})}),u.itemsType&&f.forEach((e,t)=>l.push(...i(e,u.itemsType,[...d,t.toString()]))),p&&!Array.isArray(p)&&(s[p.id]?f.forEach((e,t)=>{typeof e==`object`&&e&&(c.has(p.id)?l.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),l.push(...o(e,s[p.id],n,[...d,t.toString()],s,c)),c.delete(p.id)))}):l.push({message:`Nested schema '${p.id}' not found`,path:d}))),u.constraints?.forEach((t,r)=>{if(`rules`in t)l.push(...a(t,e,n,[...d,`constraints[${r}]`],c));else{let i=n[t.predicate];i?i({data:e,field:u.name,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${u.name}' with params ${I(t.parameters)}`,path:[...d,`constraints[${r}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}}))});for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&l.push({message:`Unexpected field '${t}'`,path:[...r,t]});return t.constraints?.forEach((t,i)=>{if(`rules`in t)l.push(...a(t,e,n,[...r,`constraints[${i}]`],c));else{let a=n[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||l.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${I(t.parameters)}`,path:[...r,`constraints[${i}]`]}):l.push({message:`Predicate '${t.predicate}' not found`,path:[...r,`constraints[${i}]`]})}}),l}return e.version!==`1.0.0`&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:i=>{if(typeof i!=`object`||!i)return r([{message:`Input must be an object`,path:[]}]);let a=i,s=o(a,e,t,[],e.nestedSchemas||{});return s.length>0?r(s):n(a)},types:{input:{},output:{}}}}}var L=class extends Error{constructor(e,t){super(e),this.errors=t,this.name=`SchemaValidationError`}},R=e=>({value:e}),z=e=>({issues:e}),B=(e,t,n=!0)=>e===void 0&&!n?[]:typeof e!=`string`||e.trim()===``?[{message:`Must be a non-empty string`,path:[t]}]:[],V=(e,t)=>{let n=[`string`,`number`,`boolean`,`array`,`set`,`enum`,`object`,`record`,`union`,`dynamic`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:e===`dynamic`?[{message:`Field type 'dynamic' is deprecated; use 'record' instead`,path:[t]}]:[]},be=(e,t)=>{let n=[`normal`,`unique`,`btree`,`hash`,`spatial`,`fulltext`,`gi`,`expression`,`composite`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},xe=(e,t)=>{let n=[`and`,`or`,`not`,`nor`,`xor`];return typeof e!=`string`||!n.includes(e)?[{message:`Must be one of ${n.join(`, `)}`,path:[t]}]:[]},H=(e,t,n=!1)=>e===void 0&&!n||typeof e==`boolean`?[]:[{message:`Must be a boolean`,path:[t]}],Se=(e,t,n)=>[],U=(e,t,n)=>{let r=[],i=[`predicate`,`name`],a=[`type`,`predicate`,`field`,`parameters`,`name`,`description`,`errorMessage`],o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...B(e.name,`${n}.name`)),r.push(...B(e.predicate,`${n}.predicate`)),e.field!==void 0&&typeof e.field!=`string`&&r.push({message:`Field must be a string`,path:[`${n}.field`]}),e.parameters!==void 0&&r.push(...Se(e.parameters,t,`${n}.parameters`)),r.push(...B(e.description,`${n}.description`,!1)),r.push(...B(e.errorMessage,`${n}.errorMessage`,!1)),r},W=(e,t,n)=>{let r=[],i=[`name`,`operator`,`rules`],a=i,o=e;return i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${n}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${n}.${e}`]})}),r.push(...B(e.name,`${n}.name`)),r.push(...xe(e.operator,`${n}.operator`)),!Array.isArray(e.rules)||e.rules.length===0?r.push({message:`Rules must be a non-empty array`,path:[`${n}.rules`]}):e.rules.forEach((e,i)=>{`rules`in e?r.push(...W(e,t,`${n}.rules[${i}]`)):r.push(...U(e,t,`${n}.rules[${i}]`))}),r},G=(e,t,n)=>{if(!Array.isArray(e))return[{message:`Must be an array`,path:[n]}];let r=[];return e.forEach((e,i)=>{`rules`in e?r.push(...W(e,t,`${n}[${i}]`)):r.push(...U(e,t,`${n}[${i}]`))}),r},Ce=(e,t)=>{let n=[],r=[`operator`,`field`],i=[`operator`,`field`,`value`,`conditions`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...xe(e.operator,`${t}.operator`)),n.push(...B(e.field,`${t}.field`)),e.conditions!==void 0&&(Array.isArray(e.conditions)?e.conditions.forEach((e,r)=>n.push(...Ce(e,`${t}.conditions[${r}]`))):n.push({message:`Conditions must be an array`,path:[`${t}.conditions`]})),n},we=(e,t)=>{let n=[],r=[`fields`,`type`,`name`],i=[`fields`,`type`,`unique`,`partial`,`description`,`order`,`name`],a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),n.push(...be(e.type,`${t}.type`)),(!Array.isArray(e.fields)||e.fields.length===0||!e.fields.every(e=>typeof e==`string`))&&n.push({message:`Fields must be a non-empty array of strings`,path:[`${t}.fields`]}),n.push(...H(e.unique,`${t}.unique`,!1)),e.partial&&n.push(...Ce(e.partial,`${t}.partial`)),n.push(...B(e.description,`${t}.description`,!1)),e.order!==void 0&&![`asc`,`desc`].includes(e.order)&&n.push({message:`Order must be 'asc' or 'desc'`,path:[`${t}.order`]}),n},K=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e))return[{message:`Must be an array`,path:[t]}];let n=[];return e.forEach((e,r)=>n.push(...we(e,`${t}[${r}]`))),n},Te=(e,t,n,r,i)=>{let a=[];return e===void 0?[]:(n===`union`&&Array.isArray(e)?(e.length===0&&a.push({message:`Schema array must not be empty for union type`,path:[t]}),e.forEach((e,n)=>{let i=`${t}[${n}]`;a.push(...B(e.id,`${i}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${i}.id`]}),e.constraints&&a.push(...G(e.constraints,`dynamic`,`${i}.constraints`)),e.indexes&&a.push(...K(e.indexes,`${i}.indexes`))})):(n===`object`||n===`array`&&i===`object`)&&!Array.isArray(e)?(a.push(...B(e.id,`${t}.id`)),r.includes(e.id)||a.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&a.push(...G(e.constraints,`dynamic`,`${t}.constraints`)),e.indexes&&a.push(...K(e.indexes,`${t}.indexes`))):a.push({message:`Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'`,path:[t]}),a)},Ee=(e,t,n)=>{if(e===void 0)return[];switch(t){case`string`:if(typeof e!=`string`)return[{message:`Default must be a string`,path:[n]}];break;case`number`:if(typeof e!=`number`)return[{message:`Default must be a number`,path:[n]}];break;case`boolean`:if(typeof e!=`boolean`)return[{message:`Default must be a boolean`,path:[n]}];break;case`array`:case`set`:if(!Array.isArray(e))return[{message:`Default must be an array`,path:[n]}];break;case`enum`:if(!Array.isArray(e)||!e.every(e=>typeof e==`string`||typeof e==`number`))return[{message:`Default must be an array of strings or numbers`,path:[n]}];break;case`object`:case`record`:if(typeof e!=`object`||!e)return[{message:`Default must be an object`,path:[n]}];break;case`union`:case`dynamic`:return[]}return[]},De=(e,t)=>e===void 0?[]:typeof e!=`object`||!e?[{message:`Hint must be an object`,path:[t]}]:`input`in e&&typeof e.input!=`object`?[{message:`Hint.input must be an object`,path:[`${t}.input`]}]:[],q=(e,t,n)=>{let r=[],i=[`name`,`type`],a=[`name`,`type`,`required`,`constraints`,`default`,`values`,`schema`,`itemsType`,`nestedSchema`,`deprecated`,`reference`,`description`,`unique`,`hint`],o=e;if(i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...V(e.type,`${t}.type`)),r.push(...H(e.required,`${t}.required`,!1)),e.constraints&&r.push(...G(e.constraints,e.type,`${t}.constraints`)),r.push(...Ee(e.default,e.type,`${t}.default`)),e.values!==void 0&&(e.type===`enum`?(!Array.isArray(e.values)||e.values.length===0||!e.values.every(e=>typeof e==`string`||typeof e==`number`))&&r.push({message:`Values must be a non-empty array of strings or numbers`,path:[`${t}.values`]}):r.push({message:`Values is only valid for 'enum' type`,path:[`${t}.values`]})),e.schema!==void 0&&r.push(...Te(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...V(e.itemsType,`${t}.itemsType`)),e.nestedSchema){r.push({message:`nestedSchema is deprecated; use schema instead`,path:[`${t}.nestedSchema`]});let i=[`id`],a=[`id`,`constraints`,`indexes`],o=e.nestedSchema;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})}),r.push(...B(e.nestedSchema.id,`${t}.nestedSchema.id`)),n.includes(e.nestedSchema.id)||r.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&r.push(...G(e.nestedSchema.constraints,`dynamic`,`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...K(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...H(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:`reference is deprecated`,path:[`${t}.reference`]});let n=[`schema`,`field`],i=[`schema`,`field`],a=e.reference;n.forEach(e=>{a[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})}),r.push(...B(e.reference.schema,`${t}.reference.schema`)),r.push(...B(e.reference.field,`${t}.reference.field`))}return r.push(...B(e.description,`${t}.description`,!1)),r.push(...H(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...De(e.hint,`${t}.hint`)),r},Oe=(e,t,n)=>{let r=[];if(`type`in e&&[`string`,`number`,`boolean`,`array`,`set`,`enum`,`record`].includes(e.type)){let i=[`name`,`type`],a=[`name`,`type`,`default`,`schema`,`itemsType`,`constraints`,`description`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...V(e.type,`${t}.type`)),r.push(...Ee(e.default,e.type,`${t}.default`)),e.schema&&r.push(...Te(e.schema,`${t}.schema`,e.type,n,e.itemsType)),e.itemsType&&r.push(...V(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...G(e.constraints,e.type,`${t}.constraints`)),r.push(...B(e.description,`${t}.description`,!1)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}else{let i=[`name`],a=[`name`,`description`,`concrete`,`fields`,`indexes`,`constraints`,`metadata`],o=e;i.forEach(e=>{o[e]===void 0&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(o).forEach(e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),r.push(...B(e.name,`${t}.name`)),r.push(...H(o.concrete,`${t}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&r.push({message:`Fields must be an object when concrete is true`,path:[`${t}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&r.push({message:`Fields array must not be empty`,path:[`${t}.fields`]}),o.fields.forEach((e,i)=>{let a=`${t}.fields[${i}]`;if(typeof e!=`object`||!e||!(`fields`in e))r.push({message:`Each variant must have a 'fields' property`,path:[a]});else{let t=e.fields;typeof t!=`object`||!t?r.push({message:`Fields must be a non-empty object`,path:[`${a}.fields`]}):Object.entries(t).forEach(([e,t])=>{r.push(...q(t,`${a}.fields.${e}`,n))}),e.when!==void 0&&(typeof e.when!=`object`||e.when===null?r.push({message:`When must be an object`,path:[`${a}.when`]}):r.push(...B(e.when.field,`${a}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!=`object`||o.fields===null?r.push({message:`Fields must be a non-empty object`,path:[`${t}.fields`]}):Object.entries(o.fields).forEach(([e,i])=>{r.push(...q(i,`${t}.fields.${e}`,n))})),r.push(...B(e.description,`${t}.description`,!1)),e.indexes&&r.push(...K(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...G(o.constraints,`dynamic`,`${t}.constraints`)),e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)&&r.push({message:`Metadata must be an object`,path:[`${t}.metadata`]})}return r},ke=e=>{if(typeof e!=`object`||!e)return z([{message:`Schema must be an object`,path:[]}]);let t=e,n=[],r=[`name`,`version`,`fields`],i=[`name`,`version`,`description`,`fields`,`nestedSchemas`,`indexes`,`constraints`,`metadata`,`dependencies`,`migrations`,`mock`,`hint`],a=t;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[e]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[e]})}),n.push(...B(t.name,`name`)),n.push(...B(t.version,`version`)),typeof t.fields!=`object`||t.fields===null)n.push({message:`Fields must be a non-empty object`,path:[`fields`]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach(([t,r])=>{n.push(...q(r,`fields.${t}`,e))})}if(t.nestedSchemas!==void 0)if(typeof t.nestedSchemas!=`object`||t.nestedSchemas===null)n.push({message:`NestedSchemas must be an object`,path:[`nestedSchemas`]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach(([t,r])=>n.push(...Oe(r,`nestedSchemas.${t}`,e)))}return n.push(...B(t.description,`description`,!1)),t.indexes&&n.push(...K(t.indexes,`indexes`)),t.constraints&&n.push(...G(t.constraints,`dynamic`,`constraints`)),t.metadata!==void 0&&(typeof t.metadata!=`object`||t.metadata===null)&&n.push({message:`Metadata must be an object`,path:[`metadata`]}),t.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`dependencies`]})),t.migrations!==void 0&&(Array.isArray(t.migrations)?t.migrations.forEach((e,t)=>n.push(...je(e,`migrations[${t}]`))):n.push({message:`Migrations must be an array`,path:[`migrations`]})),t.mock!==void 0&&typeof t.mock!=`function`&&n.push({message:`Mock must be a function`,path:[`mock`]}),t.hint&&n.push(...De(t.hint,`hint`)),n.length>0?z(n):R(t)},J=(e,t)=>{let n=[];switch(e.type||n.push({message:`type is required`,path:[`${t}.type`]}),e.type){case`modifyProperty`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),(e.changes===void 0||typeof e.changes!=`object`)&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addField`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...q(e.definition,`${t}.definition`,[]));break}case`removeField`:case`deprecateField`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`));break}case`modifyField`:{let r=[`type`,`id`,`changes`],i=[`type`,`id`,`changes`,`nestedSchemaChanges`],a=e;if(r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]}),e.nestedSchemaChanges){let r=[`id`,`constraints`,`indexes`],i=e.nestedSchemaChanges;Object.keys(i).forEach(e=>{r.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})}),n.push(...B(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&n.push(...G(i.constraints,`dynamic`,`${t}.nestedSchemaChanges.constraints`)),i.indexes&&n.push(...K(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case`addIndex`:{let r=[`type`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...we(e.definition,`${t}.definition`));break}case`removeIndex`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`));break}case`modifyIndex`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addConstraint`:{let r=[`type`,`constraint`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),`rules`in e.constraint?n.push(...W(e.constraint,`dynamic`,`${t}.constraint`)):n.push(...U(e.constraint,`dynamic`,`${t}.constraint`));break}case`removeConstraint`:{let r=[`type`,`name`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`));break}case`modifyConstraint`:{let r=[`type`,`name`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.name,`${t}.name`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}case`addNestedSchema`:{let r=[`type`,`id`,`definition`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...Oe(e.definition,`${t}.definition`,[]));break}case`removeNestedSchema`:{let r=[`type`,`id`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`));break}case`modifyNestedSchema`:{let r=[`type`,`id`,`changes`],i=r,a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),typeof e.changes!=`object`&&n.push({message:`Changes must be an object`,path:[`${t}.changes`]});break}default:n.push({message:`Unknown schema change type`,path:[`${t}.type`]})}return n},Ae=(e,t)=>{let n=[],r=[`forward`,`backward`],i=r,a=e;return r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),typeof e.forward!=`function`&&n.push({message:`Forward must be a function`,path:[`${t}.forward`]}),typeof e.backward!=`function`&&n.push({message:`Backward must be a function`,path:[`${t}.backward`]}),n},je=(e,t)=>{let n=[],r=[`id`,`schemaVersion`,`changes`,`description`,`status`,`transform`,`createdAt`,`checksum`],i=[...r,`rollback`,`dependencies`],a=e;r.forEach(e=>{a[e]===void 0&&n.push({message:`${e} is required`,path:[`${t}.${e}`]})}),Object.keys(a).forEach(e=>{i.includes(e)||n.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})}),n.push(...B(e.id,`${t}.id`)),n.push(...B(e.schemaVersion,`${t}.schemaVersion`)),n.push(...B(e.description,`${t}.description`));let o=[`pending`,`applied`,`failed`];return o.includes(e.status)||n.push({message:`Status must be one of ${o.join(`, `)}`,path:[`${t}.status`]}),!Array.isArray(e.changes)||e.changes.length===0?n.push({message:`Changes must be a non-empty array`,path:[`${t}.changes`]}):e.changes.forEach((e,r)=>{n.push(...J(e,`${t}.changes[${r}]`))}),e.rollback!==void 0&&(Array.isArray(e.rollback)?e.rollback.forEach((e,r)=>n.push(...J(e,`${t}.rollback[${r}]`))):n.push({message:`Rollback must be an array`,path:[`${t}.rollback`]})),typeof e.transform==`string`?n.push(...B(e.transform,`${t}.transform`)):typeof e.transform==`object`&&e.transform!==null?n.push(...Ae(e.transform,`${t}.transform`)):n.push({message:`Transform must be a string or object`,path:[`${t}.transform`]}),n.push(...B(e.createdAt,`${t}.createdAt`)),n.push(...B(e.checksum,`${t}.checksum`)),e.dependencies!==void 0&&(n.push({message:`dependencies is deprecated; use DomainModel instead`,path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(e=>typeof e==`string`))&&n.push({message:`Dependencies must be an array of strings`,path:[`${t}.dependencies`]})),n},Me={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:ke,types:{input:{},output:{}}}},Ne={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(typeof e!=`object`||!e)return z([{message:`Migration must be an object`,path:[]}]);let t=e,n=je(t,``);return n.length>0?z(n):R(t)},types:{input:{},output:{}}}},Pe={"~standard":{version:1,vendor:`@asaidimu/anansi`,validate:e=>{if(!Array.isArray(e))return z([{message:`SchemaChanges must be an array`,path:[]}]);let t=e,n=[];return t.forEach((e,t)=>n.push(...J(e,`[${t}]`))),n.length>0?z(n):R(t)},types:{input:[],output:[]}}};function Fe(e){try{return!Ne[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid migration definition`,e instanceof Error?e:Error(String(e)))}}function Ie(e){try{return!Pe[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid schema change definition`,e instanceof Error?e:Error(String(e)))}}function Le(e){try{return!Me[`~standard`].validate(e).issues}catch(e){throw new L(`Invalid schema definition`,e instanceof Error?e:Error(String(e)))}}var Re=async e=>{if(typeof window<`u`&&crypto.subtle){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}else{let{createHash:t}=await import(`crypto`);return t(`sha256`).update(e).digest(`hex`)}};function ze(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw Error(`Invalid version format: ${e}. Expected format: major.minor.patch`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}}function Be(e,t){if(t&&`field`in e&&e.field){let n=t.fields[e.field];if(n)return n.type}if(`parameters`in e){let t=e.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]==`string`)return`string`;if(typeof t==`number`||Array.isArray(t)&&typeof t[0]==`number`)return`number`;if(typeof t==`boolean`)return`boolean`;if(typeof t==`object`&&t){if(`minItems`in t||`maxItems`in t)return`array`;if(`schema`in t)return`object`}}}function Ve(e){return e.required===!0||e.type!==void 0||e.itemsType!==void 0||e.nestedSchema!==void 0||e.reference!==void 0||e.unique===!0}function He(e,t,n){switch(n){case`string`:if(e instanceof RegExp&&t instanceof RegExp)return e.source!==t.source;if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`number`:if(typeof e==`object`&&typeof t==`object`&&`precision`in e&&`precision`in t)return t.precision<e.precision||(t.scale??0)<(e.scale??0);if(Array.isArray(e)&&Array.isArray(t))return t.length<e.length||!e.every(e=>t.includes(e));break;case`array`:if(typeof e==`object`&&typeof t==`object`&&`minItems`in e&&`maxItems`in e&&`minItems`in t&&`maxItems`in t)return t.minItems>e.minItems||t.maxItems<e.maxItems;break;case`object`:if(typeof e==`object`&&typeof t==`object`&&`schema`in e&&`schema`in t)return Object.keys(t.schema).length>Object.keys(e.schema).length;break}return!1}function Ue(e,t){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(t.operator&&n[t.operator]>n[e.operator]||t.rules&&t.rules.length>e.rules.length)}function We(e,t,n){if(!t)return!0;if(`rules`in t&&`rules`in e)return Ue(t,e);if(`predicate`in e&&e.predicate!==void 0)return!0;if(`parameters`in e&&e.parameters!==void 0){let r=Be(t,n);return r?He(t.parameters,e.parameters,r):!0}return!1}function Ge(e,t){switch(e.type){case`removeField`:case`removeIndex`:return`major`;case`modifyField`:return Ve(e.changes)?`major`:e.changes.deprecated?`minor`:`patch`;case`modifyIndex`:return e.changes.unique!==void 0||e.changes.fields!==void 0?`major`:`minor`;case`addConstraint`:return`major`;case`removeConstraint`:return`minor`;case`modifyConstraint`:let n=t?.constraints?.find(t=>`name`in t&&t.name===e.name);return We(e.changes,n,t)?`major`:`minor`;case`addField`:case`addIndex`:case`deprecateField`:return`minor`;default:throw Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Ke(e){let t=new Set,n=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case`addField`:if(n.has(a.id))throw Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case`removeField`:if(r.has(a.id))throw Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case`modifyField`:if(n.has(a.id))throw Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case`deprecateField`:if(n.has(a.id))throw Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id);break}}function qe(e){let t=new Set,n=new Set,r=new Set;for(let i of e)switch(i.type){case`addConstraint`:let e=i.constraint,a=(`name`in e,e.name);if(n.has(a))throw Error(`Cannot add previously removed constraint: ${a}`);if(t.has(a))throw Error(`Cannot add already modified constraint: ${a}`);r.add(a);break;case`removeConstraint`:if(r.has(i.name))throw Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw Error(`Cannot remove modified constraint: ${i.name}`);n.add(i.name);break;case`modifyConstraint`:if(n.has(i.name))throw Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name);break}}function Je(e,t,n){if(t.length===0)throw Error(`No changes provided`);Ke(t),qe(t);let r=ze(e),i=`patch`;for(let e of t){let t=Ge(e,n);if(t===`major`){i=`major`;break}else t===`minor`&&i===`patch`&&(i=`minor`)}switch(i){case`major`:return`${r.major+1}.0.0`;case`minor`:return`${r.major}.${r.minor+1}.0`;case`patch`:return`${r.major}.${r.minor}.${r.patch+1}`}}function Y(e,t){let n=e=>e.split(`.`).map(e=>parseInt(e,10)||0),[r,i,a]=n(e),[o,s,c]=n(t);return r-o||i-s||a-c}var X=class extends Error{constructor(e,t,n,r){super(e),this.code=t,this.migrationId=n,this.cause=r,this.name=`MigrationError`}},Ye=(e=>(e.INVALID_SCHEMA=`INVALID_SCHEMA`,e.INVALID_MIGRATION=`INVALID_MIGRATION`,e.CHECKSUM_MISMATCH=`CHECKSUM_MISMATCH`,e.TIMEOUT=`TIMEOUT`,e.MEMORY_LIMIT=`MEMORY_LIMIT`,e.CONCURRENT_OPERATION=`CONCURRENT_OPERATION`,e.TRANSFORM_ERROR=`TRANSFORM_ERROR`,e.VERSION_NOT_FOUND=`VERSION_NOT_FOUND`,e.CIRCULAR_DEPENDENCY=`CIRCULAR_DEPENDENCY`,e.STREAM_ERROR=`STREAM_ERROR`,e.ROLLBACK_ERROR=`ROLLBACK_ERROR`,e.MISSING_TRANSFORM=`MISSING_TRANSFORM`,e))(Ye||{}),Xe=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,n){try{if(!Le(e))throw new X(`Invalid initial schema`,`INVALID_SCHEMA`);if(this.currentSchema=e,t){if(!t.every(e=>Fe(e)))throw new X(`Invalid migration configuration`,`INVALID_MIGRATION`);this.migrations=t.sort((e,t)=>Y(e.schemaVersion,t.schemaVersion))}n&&(this.history=n.sort((e,t)=>Y(e.version,t.version)))}catch(e){throw e instanceof X?e:new X(`Failed to initialize MigrationEngine`,`INVALID_SCHEMA`,void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{return await Re(JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt}))}catch(t){throw new X(`Checksum generation failed`,`CHECKSUM_MISMATCH`,e.id,t)}}async add(e){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);if(!e.changes?.length)throw new X(`Migration must include changes`,`INVALID_MIGRATION`);try{e.changes.forEach(e=>Ie(e))}catch(e){throw new X(`Invalid schema changes`,`INVALID_MIGRATION`,void 0,e)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:`pending`,rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:``};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(t,n,r){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(n,r);return{newSchema:a.reduce((e,t)=>{let r=n===`forward`?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)},i),dataPreview:await e.processMigrationList(t,n,a)}}catch(e){throw e instanceof X?e:new X(`Dry run failed`,`INVALID_SCHEMA`,void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(n=>{let r=e===`forward`?`pending`:`applied`,i=t?Y(n.schemaVersion,t)>=0:!0;return n.status===r&&i}).sort((t,n)=>e===`forward`?t.id.localeCompare(n.id):n.id.localeCompare(t.id))}applySchemaChanges(e,t,n){try{let r=Je(e.version,t);return t.map(t=>{try{return he(t,e)}catch(e){throw new X(`Invalid schema change`,`INVALID_SCHEMA`,n,e)}}).reduce((e,t)=>{try{return me(e,t)}catch(e){throw new X(`Failed to apply patch`,`INVALID_SCHEMA`,n,e)}},{...e,version:r})}catch(e){throw e instanceof X?e:new X(`Schema update failed`,`INVALID_SCHEMA`,n,e)}}async prepareMigration(){let e=this.migrations.filter(e=>e.status===`pending`);return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema(`forward`);let r=await e.processMigrationList(t,`forward`,n);return this.markMigrationsApplied(n),r}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async e=>{let t=await this.generateChecksum(e);if(e.checksum!==t)throw new X(`Checksum mismatch`,`CHECKSUM_MISMATCH`,e.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(e=>e.id===t.id)?{...t,status:`applied`}:t)}async rollback(e){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);return this.migrations.filter(e=>e.status===`applied`).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,n){if(this.isProcessing)throw new X(`Concurrent operation`,`CONCURRENT_OPERATION`);try{let r=this.history.findIndex(e=>e.version===t);if(r===-1)throw Error(`Version ${t} not found in history`);let i=this.migrations.filter(e=>e.schemaVersion===t&&e.status===`applied`).sort((e,t)=>t.id.localeCompare(e.id)),a=this.history.length-r;if(a<0)return n;for(let e=0;e<a;e++)this.transformSchema(`backward`);let o=await e.processMigrationList(n,`backward`,i);return this.migrations=this.migrations.map(e=>e.schemaVersion===t&&e.status===`applied`?{...e,status:`pending`}:e),o}finally{this.isProcessing=!1}}static async processMigrationList(e,t,n){return(await Promise.all(n.map(async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new X(`Failed to resolve transform for migration ${e.id}`,`TRANSFORM_ERROR`,e.id,t)}}))).filter(e=>!!e.transform).reduce((e,{migration:t,transform:n})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await n(e);r.enqueue(t)}catch(e){r.error(new X(`Data transformation failed for migration ${t.id}`,`TRANSFORM_ERROR`,t.id,e))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform==`string`?e.transform.startsWith(`http://`)||e.transform.startsWith(`https://`)?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let n=await fetch(e);if(!n.ok)throw new X(`Failed to fetch transform module: ${e}`,`TRANSFORM_ERROR`,void 0);let r=await n.text();if(typeof window<`u`){let e=new Blob([r],{type:`application/javascript`});return(await import(URL.createObjectURL(e))).default[t]}else{let{runInNewContext:n}=await import(`vm`),i={module:{exports:{}},console};return n(r,i,e),i.module.exports[t]}}catch(t){throw new X(`Failed to load remote transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(t){throw new X(`Failed to import local transform module: ${e}`,`TRANSFORM_ERROR`,void 0,t)}}transformSchema(e){try{if(e===`backward`){let e=this.history.pop();if(!e)throw Error(`No previous version`);this.currentSchema=e;return}let t=this.migrations.filter(e=>e.status===`pending`).flatMap(e=>e.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((e,t)=>this.applySchemaChanges(e,[t]),this.currentSchema)}catch(e){throw e instanceof X?e:new X(`Schema transformation failed`,`INVALID_SCHEMA`,void 0,e)}}};typeof window<`u`&&(window.Buffer=r);var Ze=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let n=-1,r=i=>{if(i<=n)throw Error(`next() called multiple times`);n=i;let a=this.middlewares[i];if(i===this.middlewares.length)return t();try{return a(e,()=>r(i+1))}catch(e){return Promise.reject(e)}};return r(0)}wrap(e,t){let n=this;return new Proxy(e,{get(e,r,i){let a=Reflect.get(e,r,i);return typeof a==`function`?function(...i){let o={...t,operation:r.toString(),args:i};return n.execute(o,()=>a.apply(e,i))}:a}})}};const Qe=(e=3,t=100)=>async(n,r)=>{let i=0;for(;i<e;)try{return await r()}catch(n){if(n instanceof c&&n.type===`TRANSIENT_ERROR`){if(i++,i>=e)throw n;let r=t*2**i+Math.random()*50;await new Promise(e=>setTimeout(e,r))}else throw n}},$e=async(e,t)=>{let n=Date.now();try{let r=await t();return Z(e,n,r,null),r}catch(t){throw Z(e,n,void 0,t),t}};function Z(e,t,n,r){if(!e.eventBus)return;let i=Date.now()-t;e.eventBus.emit({name:`telemetry`,payload:{type:`telemetry`,method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:i},source:{level:e.documentId?`document`:e.collection?`collection`:`database`,collection:e.collection,document:e.documentId},result:r?void 0:{type:Array.isArray(n)?`array`:typeof n,size:Array.isArray(n)?n.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}async function et(e,t){let{offset:n,limit:r}=t,i=[],a=0;return await e(async e=>a<n?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,i.length>=r?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1})),i}async function tt(e,t){let{limit:n,direction:r}=t,i=[];return await e(async e=>(i.push(e),i.length>=n?{value:e,done:!0,offset:1}:{value:e,done:!1,offset:1}),r),i}const{match:nt}=(0,ue.createMatcher)({});async function Q(e){let{collection:t,initial:n,validator:r,store:i,bus:o,lockManager:s}=e,[u,d]=l(n),{value:f,issues:p}=r?await r[`~standard`].validate(u):{value:n,issues:void 0};if(p)throw new c(`INVALID_DATA`,`Invalid data for ${t}`,e.schema,p,p);let m={current:Object.assign(f,d),deleted:!1};m.current.$id===void 0&&(m.current=Object.assign(m.current,{$id:a(),$created:new Date().toJSON(),$version:1}));let h=e=>{let[t]=l(e);return t},g={save:async e=>{await s.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let a=await i.getById(n);if(a&&a.$version!==r)throw new c(`CONFLICT`,`Version mismatch on ${t}/${n}`);return m.current.$version=(r||0)+1,m.current.$updated=new Date().toJSON(),e?await e.addOp(i,`put`,m.current):await i.put(m.current),o.emit({name:`document:write`,payload:{type:`document:write`,data:m.current,timestamp:Date.now()}}),!0}finally{s.unlock()}},update:async(n,i)=>{let[a,s]=l(Object.assign({},m.current,n)),{value:u,issues:d}=r?await r[`~standard`].validate(a):{value:a,issues:void 0};if(d)throw new c(`INVALID_DATA`,`Invalid update for ${t}`,e.schema,d,d);m.current=Object.assign(u,s);let f=await g.save(i);return f&&o.emit({name:`document:update`,payload:{type:`document:update`,data:m.current,timestamp:Date.now()}}),f},delete:async e=>{await s.lock();try{let{$id:n,$version:r}=m.current;if(!n)throw Error(`Document ID missing.`);let a=await i.getById(n);if(a&&a.$version!==r)throw new c(`CONFLICT`,`Version mismatch on delete ${t}/${n}`);return e?await e.addOp(i,`delete`,n):await i.delete(n),o.emit({name:`document:delete`,payload:{type:`document:delete`,data:m.current,timestamp:Date.now()}}),m.deleted=!0,!0}finally{s.unlock()}},read:async()=>{let e=m.current.$id,t=await i.getById(e);if(!t)throw Error(`Document not found.`);return m.current={...t},o.emit({name:`document:read`,payload:{type:`document:read`,data:m.current,timestamp:Date.now()}}),m.current},state:()=>h(m.current),$metadata:()=>l(m.current)[1],subscribe:o.subscribe};return new Proxy({},{get(e,t){if([`update`,`delete`,`subscribe`,`read`,`state`,`save`,`$metadata`].includes(t)){let e=g[t];return(...t)=>{if(m.deleted)throw new c(`INVALID_OPERATION`,`Document has been deleted`);return e(...t)}}if(m.deleted)throw new c(`INVALID_OPERATION`,`Document has been deleted`);return Reflect.get(m.current,t)}})}function rt(e,t){return`field`in e&&`operator`in e&&e.operator===`eq`&&`value`in e?e.field:null}async function it({collection:e,validator:n,bus:r,store:i,pipeline:o,validate:s,schema:u}){let d=new t,f={collection:e,validator:s?n:void 0,schema:u,store:i,bus:r,pipeline:o,lockManager:d,valid:!0},p={async validate(e){let t=n[`~standard`].validate(e);return t instanceof Promise?await t:t},create:async(t,o)=>{let[d,p]=l(t),{value:m,issues:h}=s?await n[`~standard`].validate(d):{value:d,issues:void 0};if(h)throw new c(`INVALID_DATA`,`Invalid data for collection '${e}'`,u,h,h);let g=Object.assign(m,p,{$id:a(),$created:new Date().toJSON(),$version:1});o?await o.addOp(i,`add`,g):await i.add(g),r.emit({name:`document:create`,payload:{type:`document:create`,data:g,timestamp:Date.now()}});let _=await Q({...f,initial:g});return r.emit({name:`collection:read`,payload:{type:`collection:read`,model:e,timestamp:Date.now()}}),_},find:async t=>{let n,a=rt(t,i);if(a)try{let e=t.value;n=(await i.findByIndex(a,e))[0]}catch{n=void 0}if(n===void 0&&(n=await i.cursor(async e=>e&&nt(e,t)?{value:e,done:!0}:{value:null,done:!1})??void 0),!n)return null;let o=await Q({...f,initial:n});return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`find`,model:e,timestamp:Date.now()}}),o},filter:async t=>{let n=[],a=rt(t,i);if(a)try{let e=t.value;n=await i.findByIndex(a,e)}catch{n=[]}n.length===0&&await i.cursor(async e=>(e&&nt(e,t)&&n.push(e),{value:null,done:!1}));let o=await Promise.all(n.map(e=>Q({...f,initial:e})));return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`filter`,model:e,timestamp:Date.now()}}),o},update:async(t,a,o)=>{await d.lock();try{let l=await p.filter(t);if(l.length===0)return 0;let d=[];for(let t of l){let r=t.state(),i=Object.assign({},r,a);if(s){let t=await n[`~standard`].validate(i);if(t.issues)throw new c(`INVALID_DATA`,`Bulk update failed validation for ${e}`,u,t.issues,t.issues)}let o=t.$metadata(),l=Object.assign(i,t.$metadata(),{$updated:new Date().toJSON(),$version:(o.$version||0)+1});d.push(l)}return o?await o.addOp(i,`put`,d):await i.batch(d.map(e=>({type:`put`,data:e}))),d.forEach(e=>{r.emit({name:`document:update`,payload:{type:`document:update`,data:e,timestamp:Date.now()}})}),d.length}finally{d.unlock()}},delete:async(e,t)=>{await d.lock();try{let n=await p.filter(e),a=n.map(e=>e.$id);return a.length===0?0:(t?await t.addOp(i,`delete`,a):await i.delete(a),n.forEach(e=>{r.emit({name:`document:delete`,payload:{type:`document:delete`,data:e.state(),timestamp:Date.now()}})}),a.length)}finally{d.unlock()}},list:async t=>{let n={total:await i.count(),offset:t.type===`offset`?t.offset:0,limit:t.limit,cursor:t.type===`cursor`?t.cursor:void 0,count:0};return n.total===0?{async next(){return{value:[],done:!0}}}:{async next(){let a=t.type===`offset`?await et(i.cursor.bind(i),{...t,offset:n.offset}):await tt(i.cursor.bind(i),{...t,cursor:n.cursor});n.offset+=n.limit,n.count+=a.length;let o=await Promise.all(a.map(e=>Q({...f,initial:e})));return r.emit({name:`collection:read`,payload:{type:`collection:read`,method:`list`,model:e,timestamp:Date.now()}}),{value:o,done:n.count>=n.total}}}}},m={...o.wrap(p,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>f.valid=!1};return new Proxy(m,{get(t,n,r){let i=Reflect.get(t,n,r);return typeof i==`function`?(...r)=>{if(!f.valid&&n!==`invalidate`)throw new c(`INVALID_OPERATION`,`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}function at(e){return typeof e._getIDBConnection==`function`}var ot=class{id;staged=[];done=!1;constructor(){this.id=a()}async addOp(e,t,n){if(this.done)throw new c(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);this.staged.push({store:e,op:{type:t,data:n}})}async commit(){if(this.done)throw new c(`TRANSACTION_FAILED`,`TransactionContext has already been committed or rolled back.`);if(this.done=!0,this.staged.length===0)return;let e=new Map,t=new Map;for(let{store:n,op:r}of this.staged)at(n)?(e.has(n)||e.set(n,[]),e.get(n).push(r)):(t.has(n)||t.set(n,[]),t.get(n).push(r));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){let t=Array.from(e.keys()).map(e=>e.name()),n=await e.keys().next().value._getIDBConnection();await new Promise((r,i)=>{let a=n.transaction(t,`readwrite`);a.oncomplete=()=>r(),a.onerror=()=>i(a.error??Error(`IDB transaction error`)),a.onabort=()=>i(a.error??Error(`IDB transaction aborted`)),(async()=>{try{for(let[t,n]of e)await t.executeInTransaction(n,a)}catch(e){try{a.abort()}catch{}i(e)}})()})}async commitMemory(e){let t=[];try{for(let[n,r]of e){let e=n._snapshotMemory();t.push({store:n,snapshot:e}),await n.executeInTransaction(r,null)}}catch(e){for(let{store:e,snapshot:n}of t)try{e._rollbackMemory(n)}catch{}throw e}}completed(){return this.done}};function st(e,t,n){let r,i=!1;return new ReadableStream({async pull(a){if(i){a.close();return}let o=0,s=r===void 0?void 0:{lower:r,lowerOpen:!0};try{await t.cursor(async(e,t)=>(a.enqueue(e),r=t,o++,o>=n?{done:!0,value:e}:{done:!1,value:e}),`forward`,s),o<n&&(i=!0)}catch(t){a.error($(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}async function ct(e,t,n,r){let i=t.getReader(),a=[];try{for(;;){let{value:e,done:t}=await i.read();if(t)break;if(!e)continue;let{$version:o}=e;e.$version=(o||0)+1,e.$updated=new Date().toJSON(),a.push(e),a.length>=r&&(await n.batch([{type:`put`,data:a}]),a=[])}a.length>0&&await n.batch([{type:`put`,data:a}])}catch(t){throw $(t,e)}finally{i.releaseLock()}}function $(e,t){return e instanceof c?e:e instanceof Error?new c(`INTERNAL_ERROR`,`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new c(`INTERNAL_ERROR`,`An unexpected error occurred during migration of collection '${t}'`)}async function lt(e,t){let n=i(),r=new Map,a=new Ze;a.use(Qe()),e.enableTelemetry&&a.use($e);let o=new Map,s=t({...e,collection:`schemas`,keyPath:`name`},[]);await s.open();async function l(n,r=[]){let i=o.get(n);return i||(i=t({...e,collection:n,keyPath:`$id`},r),o.set(n,i)),await i.open(),i}async function u(t){if(r.has(t))return r.get(t);let i=await s.getById(t);if(!i)throw new c(`SCHEMA_NOT_FOUND`,`Collection '${t}' does not exist`);let o=await l(t,i.indexes??[]),u=await it({collection:t,bus:n,validator:ye(i,e.predicates||{}),validate:!!e.validate,store:o,pipeline:a,schema:i});return n.emit({name:`collection:read`,payload:{type:`collection:read`,schema:{name:t},timestamp:Date.now()}}),r.set(t,u),r.get(t)}async function d(e){return await s.put(e),n.emit({name:`collection:update`,payload:{type:`collection:update`,schema:e,timestamp:Date.now()}}),!0}let f={collection:u,createCollection:async e=>{if(await s.getById(e.name))throw new c(`SCHEMA_ALREADY_EXISTS`,`Collection '${e.name}' already exists`);if(!Le(e))throw new c(`INVALID_SCHEMA_DEFINITION`,`Invalid schema definition`);await s.put(e);let t=u(e.name);return n.emit({name:`collection:create`,payload:{type:`collection:create`,schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{let t=await s.getById(e);if(!t)throw new c(`SCHEMA_NOT_FOUND`,`Collection '${e}' does not exist`);return await(await l(e,t.indexes??[])).clear(),o.delete(e),await s.delete(e),r.delete(e),n.emit({name:`collection:delete`,payload:{type:`collection:delete`,schema:t,timestamp:Date.now()}}),!0},updateCollection:d,migrateCollection:async(e,t,n=100)=>{let i=r.get(e);i&&(i.invalidate(),r.delete(e));let a=await s.getById(e);if(!a)throw new c(`SCHEMA_NOT_FOUND`,`Schema for '${e}' not found`);let o=await l(e,a.indexes??[]),f=new Xe(a);await f.add(t);let p=(await f.dryRun(new ReadableStream({start(e){e.close()}}),`forward`)).newSchema,m=new Set((a.indexes??[]).map(e=>e.name)),h=p.indexes??[],g=new Set(h.map(e=>e.name)),_=h.filter(e=>!m.has(e.name)),v=(a.indexes??[]).filter(e=>!g.has(e.name));await d(p);try{let t=st(e,o,n);await ct(e,await f.migrate(t),o,n)}catch(t){throw $(t,e)}for(let e of _)await o.createIndex(e);for(let e of v)await o.dropIndex(e.name);return await u(e)}},p=a.wrap(f,{eventBus:n}),m={...p,transaction:async e=>{let t=new ot;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:n.subscribe,close:()=>{o.clear(),n.clear()},clear:async()=>{await s.clear(),await Promise.all(o.values().map(e=>e.clear())),o.clear()},ensureCollection:async e=>{try{await p.createCollection(e)}catch(e){if(e instanceof c&&e.type===`SCHEMA_ALREADY_EXISTS`)return;throw e}},setupCollections:async e=>{for(let t of e)await m.ensureCollection(t)}};return m}export{h as ConnectionManager,o as DEFAULT_KEYPATH,lt as DatabaseConnection,c as DatabaseError,s as DatabaseErrorType,_ as IndexedDBStore,Q as createDocument,m as createEphemeralStore,y as createIndexedDbStore,it as openCollection};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/utils-database",
3
- "version": "3.1.10",
3
+ "version": "3.1.11",
4
4
  "description": "A collection of database utilities.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -38,7 +38,8 @@
38
38
  "@asaidimu/anansi": "4.0.2",
39
39
  "@asaidimu/query": "^1.1.2",
40
40
  "@asaidimu/utils-events": "^1.0.0",
41
- "uuid": "^14.0.0"
41
+ "uuid": "^14.0.0",
42
+ "@asaidimu/utils-sync": "^1.0.0"
42
43
  },
43
44
  "publishConfig": {
44
45
  "registry": "https://registry.npmjs.org/",
@@ -64,5 +65,6 @@
64
65
  }
65
66
  ]
66
67
  ]
67
- }
68
+ },
69
+ "peerDependencies": {}
68
70
  }