@asaidimu/utils-persistence 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +1 -1
  2. package/index.mjs +1 -1
  3. package/package.json +1 -1
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,s=require("buffer"),r=require("uuid"),i=Object.create,a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},d=(e,t,s,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of o(t))h.call(e,i)||i===s||a(e,i,{get:()=>t[i],enumerable:!(r=n(t,i))||r.enumerable});return e},u=(e,t,s)=>(s=null!=e?i(c(e)):{},d(e&&e.__esModule?s:a(s,"default",{value:e,enumerable:!0}),e)),p=e=>d(a({},"__esModule",{value:!0}),e),m=l({"node_modules/@asaidimu/events/index.js"(e,t){var s,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(r({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],r=0,i=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},h=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-r)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const r=t.get(e);return r.add(s),d(e),()=>{r.delete(s),0===r.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async)return s.push({name:t,payload:r}),s.length>=e.batchSize?h():l(),void(o&&o.postMessage({name:t,payload:r}));const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(r))),o&&o.postMessage({name:t,payload:r})}catch(s){e.errorHandler({...s,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(),n.clear(),s=[],r=0,i=0,a.clear(),o&&(o.close(),o=null)}}}}}),f=l({"node_modules/@asaidimu/query/index.js"(e,t){var s,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>l,createPaginator:()=>E,createProjector:()=>$,createSorter:()=>_}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))!n.call(e,c)&&c!==s&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(r({},"__esModule",{value:!0}),s));var c=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,s){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:s},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,s){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:s}),this}join(e,t,s){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:s,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 h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?r(t,e):function(e){return"computed"===e?.type}(t)?r(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let s of t.conditions)if(i(e,s.when))return s.then;return t.else}(e,t):t}let s=new Map([["and",(e,t)=>t.every((t=>i(e,t)))],["or",(e,t)=>t.some((t=>i(e,t)))],["not",(e,t)=>!t.every((t=>i(e,t)))],["nor",(e,t)=>!t.some((t=>i(e,t)))],["xor",(e,t)=>1===t.filter((t=>i(e,t))).length]]);function r(s,r){let i=s.arguments.map((e=>t(r,e)));if(e[s.function])return e[s.function](...i);throw new Error(`Function ${s.function} not found!`)}function i(r,i){if(function(e){return!!e&&void 0!==e.conditions}(i))return function(e,t){let{operator:r,conditions:i}=t,a=s.get(r);if(a)return a(e,i);throw new Error(`Unsupported logical operator: ${r}`)}(r,i);if(!i||!i.field)return!1;let{field:a,operator:n,value:o}=i,c=r[a],h=t(r,o),l=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)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[n]||l.get(n);if(d)return d(c,h);throw new Error(`Unsupported comparison operator: ${n}`)}return{resolve:t,evaluate:i}}function l(e){let{evaluate:t}=h(e),s=new WeakMap;function r(e,r){let i=s.get(e);i||(i=new Map,s.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let n=t(e,r);return i.set(a,n),n}return{matcher:r,match:r}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},u=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(u(e)&&e){let s=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:s}}if((e=>"operator"in e&&"conditions"in e)(e)){let s={...e};return e.conditions&&(s.conditions=e.conditions.map((e=>p(e,t)))),s}return e}},m=async(e,t,s,r)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(s,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let i,a=e[s.relation];return s.query?.filters&&u(s.query.filters)&&(i=((e,t)=>{let s=new Map;return e.forEach((e=>{let r=e[t];s.has(r)||s.set(r,[]),s.get(r).push(e)})),s})(a,s.query.filters.field)),(await Promise.all(t.map((async e=>{let t,n=((e,t)=>{if(!e)return{};let s=p(e.filters,t);return{...e,filters:s}})(s.query,e);return t=n.filters&&u(n.filters)&&i?.has(n.filters.value)?i.get(n.filters.value)||[]:a.filter((e=>r.matcher(e,n.filters))),((e,t,s)=>{let r=s.alias||s.relation;return[{...e,[r]:t}]})(e,await[e=>n.sort?r.sorter(e,n.sort):e,e=>n.projection?r.projector(e,n.projection):e,async e=>n.pagination?await r.paginator(e,n.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),s)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,s,r)=>s.reduce((async(t,s)=>m(e,await t,s,r)),Promise.resolve(t));function y(){return{join:f}}var g=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},w=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function v(e,t,s){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===s?-1:1:"asc"===s?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===s?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===s?e-t:t-e;throw new g(e,t)}function b(e,t){let s=Array.from(e);return 0===t.length?s:s.sort(((e,s)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],n=s[t];try{if("asc"!==i&&"desc"!==i)throw new w(i);let e=v(a,n,i);if(0!==e)return e}catch(e){throw e instanceof g||e instanceof w?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function _(){return{sort:b}}function $(e){let{resolve:t}=h(e);function s(e,r){let i={};return r.include?.length&&function(e,t,r){for(let i of t)if("string"!=typeof i){for(let[t,a]of Object.entries(i))if(Object.prototype.hasOwnProperty.call(e,t)){let i=s(e[t],a);r[t]=i}}else{let t=i;r[t]=e[t]}}(e,r.include,i),r.exclude?.length&&function(e,t,r){0===Object.keys(r).length&&Object.assign(r,e);for(let e of t)if("string"!=typeof e)for(let[t,i]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(r,t))continue;let e=r[t];e&&"object"==typeof e?r[t]=s(e,i):delete r[t]}else delete r[e]}(e,r.exclude,i),r.computed?.length&&function(e,s,r){for(let i of s)r[i.alias]=t(e,i)}(e,r.computed,i),i}return{project:s}}async function*k(e,t,s=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:s,limit:r}=t,i=0,a=r,n=[];for await(let t of e)a<=0&&(yield n,n=[],a=r),i<s?i++:(n.push(t),a--);n.length>0&&(yield n)}(e,t):yield*async function*(e,t,s){let{cursor:r,limit:i,direction:a}=t,n=i,o=void 0===r,c=[];if("forward"===a)for await(let t of e)n<=0&&(yield c,c=[],n=i),o?(c.push(t),n--):o=s(t)===r;else{let t=[];for await(let s of e)t.push(s);for(let e=t.length-1;e>=0;e--){let a=t[e];o?(c.push(a),n--,n<=0&&(yield c,c=[],n=i)):o=s(a)===r}}c.length>0&&(yield c)}(e,t,s)}function E(){return{paginate:k}}}}),y=l({"node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,s;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?s:(t=!0,s=e.apply(this,arguments))}}}}),g=l({"node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),w=l({"node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,s){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,n=s&&!r;return clearTimeout(r),r=setTimeout((function(){if(r=null,!n)return e.apply(i,a)}),t),n?e.apply(this,arguments):void 0}}}}),v=l({"node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function s(e){if(0===e.length)return".";let t=i(e);return t=t.reduce(a,[]),r(...t)}function r(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function i(e){if(0===e.length)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 a(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new 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:r,normalize:s,split:i,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let i of e)t=i.startsWith("/")?i:s(r(t,i));return t}}}}),b=l({"node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function s(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var r=s("EEXIST"),i=s("ENOENT"),a=s("ENOTDIR"),n=s("ENOTEMPTY"),o=s("ETIMEDOUT"),c=s("EISDIR");t.exports={EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,ETIMEDOUT:o,EISDIR:c}}}),_=l({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var s=v(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,EISDIR:o}=b();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){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):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[s,r]of e)0!==s&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[s,r]of e)0!==s&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get("/")){let t="";const s=(e,r)=>{for(let[i,a]of e){if(0===i)continue;let e=a.get(0),n=e.mode.toString(8);t+=`${"\t".repeat(r)}${i}\t${n}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",s(a,r+1))}};return s(e,0),t}parse(e){let t=0;function s(e){const s=++t,r=1===e.length?"dir":"file";let[i,a,n]=e;return i=parseInt(i,8),a=a?parseInt(a):0,n=n?parseInt(n):Date.now(),new Map([[0,{mode:i,type:r,size:a,mtimeMs:n,ino:s}]])}let r=e.trim().split("\n"),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("\t"),n=s(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:n}),a[a.length-2].node.set(r,n)}return i}_lookup(e,t=!0){let r=this._root,a="/",n=s.split(e);for(let o=0;o<n.length;++o){let c=n[o];if(r=r.get(c),!r)throw new i(e);if(t||o<n.length-1){const e=r.get(0);if("symlink"===e.type){let t=s.resolve(a,e.target);r=this._lookup(t)}a=a?s.join(a,c):c}}return r}mkdir(e,{mode:t}){if("/"===e)throw new r;let i=this._lookup(s.dirname(e)),a=s.basename(e);if(i.has(a))throw new r;let n=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};n.set(0,o),i.set(a,n)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;if(t.size>1)throw new n;let r=this._lookup(s.dirname(e)),i=s.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;return[...t.keys()].filter((e=>"string"==typeof e))}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch(e){}if(void 0!==a){if("dir"===a.type)throw new o;null==r&&(r=a.mode),i=a.ino}null==r&&(r=438),null==i&&(i=this.autoinc());let n=this._lookup(s.dirname(e)),c=s.basename(e),h={mode:r,type:"file",size:t,mtimeMs:Date.now(),ino:i},l=new Map;return l.set(0,h),n.set(c,l),h}unlink(e){let t=this._lookup(s.dirname(e)),r=s.basename(e);t.delete(r)}rename(e,t){let r=s.basename(t),i=this._lookup(e);this._lookup(s.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);null===i&&(i=e.mode),r=e.ino}catch(e){}null==i&&(i=40960),null==r&&(r=this.autoinc());let a=this._lookup(s.dirname(t)),n=s.basename(t),o={mode:i,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,o),a.set(n,c),o}_du(e){let t=0;for(const[s,r]of e.entries())t+=0===s?r.size:this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),$={};function k(){return t||(t=new e),t}function E(e,t=k()){let s;return t._withIDBStore("readwrite",(t=>{s=t.get(e)})).then((()=>s.result))}function S(e,t,s=k()){return s._withIDBStore("readwrite",(s=>{s.put(t,e)}))}function I(e,t,s=k()){return s._withIDBStore("readwrite",(s=>{const r=s.get(e);r.onsuccess=()=>{s.put(t(r.result),e)}}))}function O(e,t=k()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function A(e=k()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function N(e=k()){const 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 x(e=k()){return e._close()}((e,t)=>{for(var s in t)a(e,s,{get:t[s],enumerable:!0})})($,{Store:()=>e,clear:()=>A,close:()=>x,del:()=>O,get:()=>E,keys:()=>N,set:()=>S,update:()=>I});var j,C,T=(j={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){e=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise(((e,t)=>{const s=indexedDB.open(this._dbName);s.onerror=()=>t(s.error),s.onsuccess=()=>e(s.result),s.onupgradeneeded=()=>{s.result.createObjectStore(this._storeName)}})))}_withIDBStore(e,t){return this._init(),this._dbp.then((s=>new Promise(((r,i)=>{const a=s.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}))}}}},function(){return j&&(C=(0,j[o(j)[0]])(j=0)),C}),M=l({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var s=(T(),p($));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new s.Store(this._database,this._storename)}saveSuperblock(e){return s.set("!root",e,this._store)}loadSuperblock(){return s.get("!root",this._store)}readFile(e){return s.get(e,this._store)}writeFile(e,t){return s.set(e,t,this._store)}unlink(e){return s.del(e,this._store)}wipe(){return s.clear(this._store)}close(){return s.close(this._store)}}}}),R=l({"node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(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){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),D=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var s=(T(),p($)),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 s.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await s.update("lock",(s=>{const r=Date.now()+e;return t=s&&s.holder===this._id,this._lock=t?{holder:this._id,expires:r}:s,this._lock}),this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await s.update("lock",(s=>{const a=Date.now(),n=a+e;return r=s&&s.expires<a,t=void 0===s||r,i=s&&s.holder===this._id,this._lock=t?{holder:this._id,expires:n}:s,this._lock}),this._store),i)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:s}={}){for(;t--;){if(await this.acquire({ttl:s}))return!0;await r(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,r,i;if(await s.update("lock",(s=>(t=e||s&&s.holder===this._id,r=void 0===s,i=s&&s.holder!==this._id,this._lock=t?void 0:s,this._lock)),this._store),await s.close(this._store),!t&&!e){if(r)throw new Error("Mutex double-freed");if(i)throw new Error("Mutex lost ownership")}return t}}}}),P=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(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,s)=>{const r=new AbortController;setTimeout((()=>{r.abort(),s(new 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))}}}}),q=l({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:s,decode:r}=g(),i=w(),a=_(),{ENOENT:n,ENOTEMPTY:o,ETIMEDOUT:c}=b(),h=M(),l=R(),d=D(),u=P(),p=v();t.exports=class{constructor(){this.saveSuperblock=i((()=>{this.flush()}),500)}async init(e,{wipe:t,url:s,urlauto:r,fileDbName:i=e,db:n=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=n||new h(i,o),this._mutex=navigator.locks?new u(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:s},this._needsWipe=!!t,s&&(this._http=new l(s),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();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const 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,s){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(e){}}return this._cache.writeStat(e,t,s)}async readFile(e,t){const s="string"==typeof t?t:t&&t.encoding;if(s&&"utf8"!==s)throw new 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(;"symlink"===t.type;)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()),"utf8"===s?i=r(i):i.toString=()=>r(i)),!a)throw new n(e);return i}async writeFile(e,t,r){const{mode:i,encoding:a="utf8"}=r;if("string"==typeof t){if("utf8"!==a)throw new Error('Only "utf8" encoding is supported in writeFile');t=s(t)}const n=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(n.ino,t)}async unlink(e,t){const s=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==s.type&&await this._idb.unlink(s.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:s=511}=t;this._cache.mkdir(e,{mode:s})}rmdir(e,t){if("/"===e)throw new o;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 s=await this._http.sizeFile(e);await this._writeStat(e,s,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),F=l({"node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(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"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),B=l({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var s=q(),r=F(),i=v();function a(e,t,...s){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=i.normalize(e),t,...s]}function n(e,t,s,...r){return void 0!==s&&"function"!=typeof s||(s={}),"string"==typeof s&&(s={encoding:s}),[e=i.normalize(e),t,s,...r]}function o(e,t,...s){return[i.normalize(e),i.normalize(t),...s]}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,n,!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,o,!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,o,!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 s,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(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,s){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),s&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(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,s){return await this._backend.writeFile(e,t,s),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){const s=await this._backend.stat(e,t);return new r(s)}async lstat(e,t){const s=await this._backend.lstat(e,t);return new r(s)}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()}}}}),z=l({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var s=y(),r=B();function i(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=s(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,s){const[r,a]=i(t,s);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,s,r){const[a,n]=i(s,r);this.promises.writeFile(e,t,s).then(a).catch(n)}unlink(e,t,s){const[r,a]=i(t,s);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,s){const[r,a]=i(t,s);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,s){const[r,a]=i(t,s);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,s){const[r,a]=i(t,s);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,s){const[r,a]=i(s);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,s){const[r,a]=i(t,s);this.promises.stat(e).then(r).catch(a)}lstat(e,t,s){const[r,a]=i(t,s);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,s){const[r,a]=i(t,s);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,s){const[r,a]=i(s);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,s){const[r,a]=i(t,s);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){const[s,r]=i(t);this.promises.du(e).then(s).catch(r)}flush(e){const[t,s]=i(e);this.promises.flush().then(t).catch(s)}}}}),U=u(m()),L=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},V=class extends L{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},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)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const s=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await s;let r;await Promise.race([s.then((()=>clearTimeout(r))),new Promise(((s,i)=>{r=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),i(new V("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},J=class{mutex=new H({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}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{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{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){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new 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()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const 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()}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this.isReady()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}currentExecution(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,s="Operation timed out"){if(null==t)return e;let r;return Promise.race([e.then((e=>(clearTimeout(r),e))),new Promise(((e,i)=>{r=setTimeout((()=>i(new V(s))),t)}))])}},K=class{_delay;_leading;_timer;_pendingFn;_pendingResolvers=[];_leadingFired=!1;constructor(e){this._delay=e?.delay??300,this._leading=e?.leading??!1}do(e){return new Promise((t=>{this._enqueue(e,t)}))}fire(e){this._enqueue(e,void 0)}_enqueue(e,t){if(this._pendingFn=e,t&&this._pendingResolvers.push(t),this._leading&&!this._leadingFired)return this._leadingFired=!0,this._fire(),clearTimeout(this._timer),void(this._timer=setTimeout((()=>{this._leadingFired=!1,void 0!==this._pendingFn&&this._fire()}),this._delay));clearTimeout(this._timer),this._timer=setTimeout((()=>{this._leadingFired=!1,this._fire()}),this._delay)}cancel(){clearTimeout(this._timer),this._timer=void 0,this._pendingFn=void 0,this._leadingFired=!1;const e=this._pendingResolvers.splice(0);for(const t of e)t({status:"cancelled"})}async flush(){return this._pendingFn?(clearTimeout(this._timer),this._timer=void 0,this._leadingFired=!1,this._fire()):null}pending(){return void 0!==this._pendingFn}async _fire(){const e=this._pendingFn,t=this._pendingResolvers.splice(0);let s;this._pendingFn=void 0;try{s={status:"ok",value:await e()}}catch(e){s={status:"error",error:e}}for(const e of t)e(s);return s}};function W(e){const t=e??{},{deferred:s,batchSize:r,batchDelay:i,errorHandler:a,broadcast:n,channel:o}={deferred:null!=t.batch?.size,batchSize:t.batch?.size,batchDelay:t.batch?.delay||16,errorHandler:t.errorHandler||(e=>console.error("EventBus Error:",e)),broadcast:null!=t.broadcast?.channel&&t.broadcast.channel.length>0,channel:null!=t.broadcast?.channel&&t.broadcast.channel.length>0?t.broadcast?.channel:"event-bus-channel"},c=new Map;let h=[],l=0,d=0;const u=new Map,p=()=>{if(!n)return null;if("undefined"==typeof BroadcastChannel)return console.warn("EventBus: BroadcastChannel is not supported in this environment. Cross-tab notifications are disabled."),null;const e=new BroadcastChannel(o);return e.onmessage=e=>{const{name:t,payload:s}=e.data;y(t,s)},e};let m=p();const f=(e,t)=>{l++,d+=t,u.set(e,(u.get(e)??0)+1)},y=(e,t)=>{const s=c.get(e);if(s&&0!==s.size)for(const r of Array.from(s))try{r(t)}catch(s){const r=s instanceof Error?s:Object.assign(new Error(String(s)),{cause:s}),i=Object.assign(r,{eventName:e,payload:t});a(i)}},g=()=>{const e=h;h=[];for(const{name:t,payload:s}of e){const e=performance.now();y(t,s),f(t,performance.now()-e)}},w=new K({delay:i});return{subscribe:(e,t)=>{c.has(e)||c.set(e,new Set);const s=c.get(e);return s.add(t),()=>{s.delete(t),0===s.size&&c.delete(e)}},once:(e,t)=>{let s;const r=e=>{s(),t(e)};return s=(()=>{c.has(e)||c.set(e,new Set);const t=c.get(e);return t.add(r),()=>{t.delete(r),0===t.size&&c.delete(e)}})(),s},emit:({name:e,payload:t})=>{if(s)return h.push({name:e,payload:t}),h.length>=r?(w.cancel(),void g()):(w.fire((()=>g())),void m?.postMessage({name:e,payload:t}));const i=performance.now();y(e,t),f(e,performance.now()-i),m?.postMessage({name:e,payload:t})},metrics:()=>({totalEvents:l,activeSubscriptions:Array.from(c.values()).reduce(((e,t)=>e+t.size),0),eventCounts:u,averageEmitDuration:l>0?d/l:0}),clear:()=>{c.clear(),h=[],w.cancel(),l=0,d=0,u.clear(),m?.close(),m=p()}}}var Y=class extends Error{type;schema;constructor(e,t,s,r){super(t,{cause:r}),this.type=e,this.schema=s,this.name="DatabaseError"}},G=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function X(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce(((e,[s,r])=>(s.startsWith("$")?t[s]=r:e[s]=r,e)),{}),t]}function Q(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new Y("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}var Z=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new J({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const s=indexedDB.open(this.config.database);s.onerror=()=>t(new Error(`Failed to open database: ${s.error?.message}`)),s.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},s.onsuccess=()=>e(s.result)}))}async upgradeDatabase(e,t){const s=e.version+1;return e.close(),new Promise(((e,r)=>{const i=indexedDB.open(this.config.database,s);i.onerror=()=>r(new Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{const s=e.target.result,r=e.target.transaction;t(s,r)},i.onsuccess=()=>e(i.result)}))}async ensureStore(e,t="$id",s=[]){(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)){const i=r.createObjectStore(e,{keyPath:t});for(const e of s){const t=1===e.fields.length?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}}))}async createStoreIndex(e,t){await this.upgrade(((s,r)=>{const i=r.objectStore(e);if(i.indexNames.contains(t.name))return;const a=1===t.fields.length?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})}))}async dropStoreIndex(e,t){await this.upgrade(((s,r)=>{const i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new Y("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){const t=await this.getConnection();this.connectionInitializer.reset();const s=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(t,e)));if(s.error)throw new Y("INTERNAL_ERROR",`Database upgrade failed for ${this.config.database}`,void 0,s.error);return s.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function ee(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var te=class{constructor(e,t,s="$id",r=[]){this.connectionManager=e,this.collection=t,this.keyPath=s,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 s=>{const r=s.index(e);return this.requestToPromise(r.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async s=>{const r=s.index(e);return this.requestToPromise(r.getAll(ee(t)))}))}async findByIndex(e,t){return this.withTx("readonly",(async s=>{const r=s.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))}))}async put(e){return this.withTx("readwrite",(async t=>{const s=e[this.keyPath];if(void 0!==s){Q(await this.requestToPromise(t.get(s)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const s=Array.isArray(e)?e:[e],r=[];for(const e of s){const s=await this.requestToPromise(t.add(e));r.push(s)}return Array.isArray(e)?r:r[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const s of e)if("put"===s.type||"add"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const r of e)if("put"===s.type){const e=r[this.keyPath];if(void 0!==e){Q(await this.requestToPromise(t.get(e)),r)}await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{const e=Array.isArray(s.data)?s.data:[s.data];for(const s of e)await this.requestToPromise(t.delete(s))}}))}async delete(e){return this.withTx("readwrite",(async t=>{const s=Array.isArray(e)?e:[e];for(const e of s)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 Y("INTERNAL_ERROR",`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);const s=t.objectStore(this.collection);for(const t of e)if("put"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e){const e=t[this.keyPath];if(void 0!==e){Q(await this.requestToPromise(s.get(e)),t)}await this.requestToPromise(s.put(t))}}else if("add"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(s.add(t))}else{const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(s.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",s){return this.withTx("readonly",(async r=>{const i="forward"===t?"next":"prev",a=r.openCursor(ee(s),i);return new Promise(((t,s)=>{let r=null;a.onsuccess=async i=>{const a=i.target.result;if(!a)return t(r);try{const{value:s,done:i,offset:n}=await e(a.value,a.key,a);r=s,i?t(r):n&&n>0?a.advance(n):a.continue()}catch(e){s(e)}},a.onerror=()=>s(this.mapError(a.error))}))}))}mapError(e){if(e instanceof Y)return e;const t=e?.message||"Unknown IndexedDB Error",s=e?.name||"";return"QuotaExceededError"===s?new Y("INTERNAL_ERROR","Storage quota exceeded"):new Y("VersionError"===s?"CONFLICT":"InvalidStateError"===s||"TransactionInactiveError"===s?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const s=await this.connectionManager.getConnection();return new Promise((async(r,i)=>{const a=s.transaction(this.collection,e),n=a.objectStore(this.collection);let o,c;a.oncomplete=()=>{c?i(c):r(o)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{const e=t(n,a);o=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}},se=new Map,re=e=>{let t=se.get(e.database);t||(t=new J({retry:!0,throws:!0}),se.set(e.database,t));try{const{value:s,error:r}=t.doSync((()=>new Z(e)));if(r)throw new Y("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,r);return new te(s,e.collection,e.keyPath)}catch(e){if(e instanceof Y)throw e;throw new Y("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}};u(m()),u(m()),u(f()),u(z()),u(z());var ie=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ae(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(ne).join("/"):"/"+e.split(".").map(ne).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(oe)}function ne(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function oe(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var ce=new Map;function he(e,t){let s=e;for(let e of t){if(null===s||"object"!=typeof s)throw new ie(`Invalid path - parent not found at ${e}`);if(Array.isArray(s)){let t="-"===e?s.length:parseInt(e);if(isNaN(t)||t<0||t>s.length)throw new ie(`Invalid array index: ${e}`);s=s[t]}else{if(!s.hasOwnProperty(e))throw new ie(`Property ${e} not found`);s=s[e]}}return s}function le(e,t){let s=ce.get(t)||ae(t);if(ce.set(t,s),0===s.length)return e;let r=he(e,s.slice(0,-1)),i=s[s.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new ie(`Invalid array index: ${i}`);return r[e]}return r[i]}function de(e,t,s){let r=ce.get(t)||ae(t);ce.set(t,r);let i=he(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter((e=>e!==s))):i[a]===s&&delete i[a],e}function ue(e,t,s){let r=ce.get(t)||ae(t);if(ce.set(t,r),0===r.length)return s;let i=r.slice(0,-1),a=r[r.length-1],n=he(e,i);if(Array.isArray(n))if("-"===a)n.push(s);else{let e=parseInt(a);if(e<0||e>n.length)throw new ie(`Invalid array index: ${a}`);n.splice(e,0,s)}else n[a]=s;return e}function pe(e,t){let s=ce.get(t)||ae(t);if(ce.set(t,s),0===s.length)return;let r=he(e,s.slice(0,-1)),i=s[s.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 s=[];switch(e.type){case"addField":s.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":s.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach((([e,r])=>{"object"!=typeof r||null===r||Array.isArray(r),s.push({op:"replace",path:`${t}/${e}`,value:r})}));break}case"deprecateField":s.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||s.push({op:"add",path:"/indexes",value:[]}),s.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let r=t.indexes?.findIndex((t=>t.name===e.name));void 0!==r&&r>=0&&s.push({op:"remove",path:`/indexes/${r}`});break}case"modifyIndex":{let r=t.indexes?.findIndex((t=>t.name===e.name));void 0!==r&&r>=0&&Object.entries(e.changes).forEach((([e,t])=>{s.push({op:"replace",path:`/indexes/${r}/${e}`,value:t})}));break}case"addConstraint":t.constraints||s.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach((e=>{s.push({op:"add",path:"/constraints/-",value:e})})):s.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));void 0!==r&&r>=0&&s.push({op:"remove",path:`/constraints/${r}`});break}case"modifyConstraint":{let r=function(e,t){if(!e.constraints)return null;for(let s=0;s<e.constraints.length;s++){let r=e.constraints[s];if(r.name===t)return`/constraints/${s}`;if(fe(r)){let e=ye(r.rules,t);if(e)return`/constraints/${s}${e}`}}return null}(t,e.name);r&&Object.entries(e.changes).forEach((([e,t])=>{s.push({op:"replace",path:`${r}/${e}`,value:t})}));break}}return s}function fe(e){return e&&"operator"in e&&"rules"in e}function ye(e,t){for(let s=0;s<e.length;s++){let r=e[s];if("name"in r&&r.name===t)return`/rules/${s}`;if(fe(r)){let e=ye(r.rules,t);if(e)return`/rules/${s}${e}`}}return null}var ge=new Map;function we(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ve(e,t){let s=e=>({issues:e}),r=(e,t,s,r)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:s}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:s}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:s}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:s}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:s}];case"enum":return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:s}]:[{message:"Enum type requires 'values' definition",path:s}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:s}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:s}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:s}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:s}]:[];default:return[{message:`Unknown type '${t}'`,path:s}]}};function i(e,t,s,r,a){let n=[],o=e.rules.map(((e,o)=>{let c=[...r,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(a.has(h))return!0;a.add(h);let r=i(e,t,s,c,a);return n.push(...r),a.delete(h),0===r.length}{let r=s[e.predicate];if(!r)return n.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(ge.has(i)){let t=ge.get(i);return t||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return ge.set(i,a),a||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:c}),a}}));return(()=>{switch(e.operator){case"and":return o.every((e=>e));case"or":return o.some((e=>e));case"not":return!o.every((e=>e));case"nor":return!o.some((e=>e));case"xor":return 1===o.filter((e=>e)).length}})()||n.push({message:`Constraint group '${e.name}' failed`,path:r}),n}function a(e,t,s,n,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let a=n.length>0?e[n[n.length-1]]:e;return h.push(...r(a,t.type,n,{values:t.values})),t.constraints&&t.constraints.forEach(((e,t)=>{if("rules"in e)h.push(...i(e,{value:a},s,[...n,`constraints[${t}]`],c));else{let r=s[e.predicate];r?r({data:{value:a},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:[...n,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...n,`constraints[${t}]`]})}})),h}let l={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let s=t.fields,r=s.find((e=>!e.when));r&&Object.assign(l,r.fields);let i=s.find((t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value));if(i)Object.assign(l,i.fields);else if(!r)return h.push({message:"No matching field set found for discriminated schema",path:n}),h}else l=t.fields;else l=t.fields;let d=new Set(Object.values(l).map((e=>e.name)));Object.entries(l).forEach((([t,l])=>{let d=[...n,l.name],u=Object.hasOwnProperty.call(e,l.name)?e[l.name]:void 0!==l.default?l.default:void 0;l.required&&null==u&&h.push({message:`Field '${l.name}' is required`,path:d});let p=l.schema||l.nestedSchema;if("object"===l.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=u&&"object"==typeof u&&!Array.isArray(u)?u:{};h.push(...a(t,e,s,d,o,c)),p.constraints?.forEach(((e,r)=>{if("rules"in e)h.push(...i(e,t,s,[...d,`constraints[${r}]`],c));else{let i=s[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:[...d,`constraints[${r}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:d})}if("union"===l.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach(((r,n)=>{let h=o[r.id];if(h)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,n.toString()]});else{c.add(r.id);let n=u&&"object"==typeof u&&!Array.isArray(u)?u:{},l=a(n,h,s,d,o,new Set(c));0===l.length&&void 0!==u?(e=!0,r.constraints?.forEach(((r,a)=>{if("rules"in r){let o=i(r,n,s,[...d,`constraints[${a}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let i=s[r.predicate];i&&!i({data:n,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${a}]`]}))}}))):void 0===u&&t.push(...l.filter((e=>e.message.includes("is required")))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,n.toString()]})})),e||void 0===u?void 0===u&&h.push(...t):(h.push({message:"Value does not match any union schema",path:d}),h.push(...t))}void 0!==u&&(h.push(...r(u,l.type,d,{values:l.values})),("array"===l.type||"set"===l.type)&&Array.isArray(u)&&(l.constraints?.forEach(((e,t)=>{let r=s[e.predicate];r&&!r({data:{[l.name]:u},field:l.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${l.name}'`,path:[...d,`constraints[${t}]`]})})),l.itemsType&&u.forEach(((e,t)=>h.push(...r(e,l.itemsType,[...d,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?u.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),h.push(...a(e,o[p.id],s,[...d,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:d}))),l.constraints?.forEach(((t,r)=>{if("rules"in t)h.push(...i(t,e,s,[...d,`constraints[${r}]`],c));else{let i=s[t.predicate];i?i({data:e,field:l.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${l.name}' with params ${we(t.parameters)}`,path:[...d,`constraints[${r}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...n,t]});return t.constraints?.forEach(((t,r)=>{if("rules"in t)h.push(...i(t,e,s,[...n,`constraints[${r}]`],c));else{let i=s[t.predicate];i?i({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${we(t.parameters)}`,path:[...n,`constraints[${r}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...n,`constraints[${r}]`]})}})),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:r=>{if("object"!=typeof r||null===r)return s([{message:"Input must be an object",path:[]}]);let i=r,n=a(i,e,t,[],e.nestedSchemas||{});return n.length>0?s(n):(e=>({value:e}))(i)},types:{input:{},output:{}}}}}var be=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},_e=e=>({value:e}),$e=e=>({issues:e}),ke=(e,t,s=!0)=>(void 0!==e||s)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],Ee=(e,t)=>{let s=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&s.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${s.join(", ")}`,path:[t]}]},Se=(e,t)=>{let s=["and","or","not","nor","xor"];return"string"==typeof e&&s.includes(e)?[]:[{message:`Must be one of ${s.join(", ")}`,path:[t]}]},Ie=(e,t,s=!1)=>(void 0!==e||s)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Oe=(e,t,s)=>{let r=[],i=["type","predicate","field","parameters","name","description","errorMessage"],a=e;return["predicate","name"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${s}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${s}.${e}`]})})),r.push(...ke(e.name,`${s}.name`)),r.push(...ke(e.predicate,`${s}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&r.push({message:"Field must be a string",path:[`${s}.field`]}),void 0!==e.parameters&&r.push(...(e.parameters,[])),r.push(...ke(e.description,`${s}.description`,!1)),r.push(...ke(e.errorMessage,`${s}.errorMessage`,!1)),r},Ae=(e,t,s)=>{let r=[],i=["name","operator","rules"],a=i,n=e;return i.forEach((e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${s}.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${s}.${e}`]})})),r.push(...ke(e.name,`${s}.name`)),r.push(...Se(e.operator,`${s}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,i)=>{"rules"in e?r.push(...Ae(e,t,`${s}.rules[${i}]`)):r.push(...Oe(e,0,`${s}.rules[${i}]`))})):r.push({message:"Rules must be a non-empty array",path:[`${s}.rules`]}),r},Ne=(e,t,s)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[s]}];let r=[];return e.forEach(((e,i)=>{"rules"in e?r.push(...Ae(e,t,`${s}[${i}]`)):r.push(...Oe(e,0,`${s}[${i}]`))})),r},xe=(e,t)=>{let s=[],r=["operator","field","value","conditions"],i=e;return["operator","field"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Se(e.operator,`${t}.operator`)),s.push(...ke(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,r)=>s.push(...xe(e,`${t}.conditions[${r}]`)))):s.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),s},je=(e,t)=>{let s=[],r=["fields","type","unique","partial","description","order","name"],i=e;return["fields","type","name"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`)),s.push(...((e,t)=>{let s=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&s.includes(e)?[]:[{message:`Must be one of ${s.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every((e=>"string"==typeof e)))&&s.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),s.push(...Ie(e.unique,`${t}.unique`,!1)),e.partial&&s.push(...xe(e.partial,`${t}.partial`)),s.push(...ke(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&s.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),s},Ce=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let s=[];return e.forEach(((e,r)=>s.push(...je(e,`${t}[${r}]`)))),s},Te=(e,t,s,r,i)=>{let a=[];return void 0===e?[]:("union"===s&&Array.isArray(e)?(0===e.length&&a.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach(((e,s)=>{let i=`${t}[${s}]`;a.push(...ke(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(...Ne(e.constraints,"dynamic",`${i}.constraints`)),e.indexes&&a.push(...Ce(e.indexes,`${i}.indexes`))}))):"object"!==s&&("array"!==s||"object"!==i)||Array.isArray(e)?a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(a.push(...ke(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(...Ne(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&a.push(...Ce(e.indexes,`${t}.indexes`))),a)},Me=(e,t,s)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[s]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[s]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[s]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[s]}];break;case"enum":if(!Array.isArray(e)||!e.every((e=>"string"==typeof e||"number"==typeof e)))return[{message:"Default must be an array of strings or numbers",path:[s]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[s]}];break;case"union":case"dynamic":return[]}return[]},Re=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],De=(e,t,s)=>{let r=[],i=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],a=e;if(["name","type"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`)),r.push(...Ee(e.type,`${t}.type`)),r.push(...Ie(e.required,`${t}.required`,!1)),e.constraints&&r.push(...Ne(e.constraints,e.type,`${t}.constraints`)),r.push(...Me(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every((e=>"string"==typeof e||"number"==typeof e)))&&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`]})),void 0!==e.schema&&r.push(...Te(e.schema,`${t}.schema`,e.type,s,e.itemsType)),e.itemsType&&r.push(...Ee(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"],n=e.nestedSchema;i.forEach((e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})})),r.push(...ke(e.nestedSchema.id,`${t}.nestedSchema.id`)),s.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(...Ne(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...Ce(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...Ie(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:"reference is deprecated",path:[`${t}.reference`]});let s=["schema","field"],i=["schema","field"],a=e.reference;s.forEach((e=>{void 0===a[e]&&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(...ke(e.reference.schema,`${t}.reference.schema`)),r.push(...ke(e.reference.field,`${t}.reference.field`))}return r.push(...ke(e.description,`${t}.description`,!1)),r.push(...Ie(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...Re(e.hint,`${t}.hint`)),r},Pe=(e,t,s)=>{let r=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let i=["name","type","default","schema","itemsType","constraints","description","metadata"],a=e;["name","type"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`)),r.push(...Ee(e.type,`${t}.type`)),r.push(...Me(e.default,e.type,`${t}.default`)),e.schema&&r.push(...Te(e.schema,`${t}.schema`,e.type,s,e.itemsType)),e.itemsType&&r.push(...Ee(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...Ne(e.constraints,e.type,`${t}.constraints`)),r.push(...ke(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&r.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let i=["name","description","concrete","fields","indexes","constraints","metadata"],a=e;["name"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`)),r.push(...Ie(a.concrete,`${t}.concrete`,!1)),a.concrete&&Array.isArray(a.fields)&&r.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(a.fields)?(0===a.fields.length&&r.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),a.fields.forEach(((e,i)=>{let a=`${t}.fields[${i}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?r.push({message:"Fields must be a non-empty object",path:[`${a}.fields`]}):Object.entries(t).forEach((([e,t])=>{r.push(...De(t,`${a}.fields.${e}`,s))})),void 0!==e.when&&("object"!=typeof e.when||null===e.when?r.push({message:"When must be an object",path:[`${a}.when`]}):r.push(...ke(e.when.field,`${a}.when.field`)))}else r.push({message:"Each variant must have a 'fields' property",path:[a]})}))):void 0!==a.fields&&("object"!=typeof a.fields||null===a.fields?r.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(a.fields).forEach((([e,i])=>{r.push(...De(i,`${t}.fields.${e}`,s))}))),r.push(...ke(e.description,`${t}.description`,!1)),e.indexes&&r.push(...Ce(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...Ne(a.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&r.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return r},qe=(e,t)=>{let s=[];switch(e.type||s.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let r=["type","id","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&s.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=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`)),s.push(...De(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let r=["type","id"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`));break}case"modifyField":{let r=["type","id","changes","nestedSchemaChanges"],i=e;if(["type","id","changes"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`)),"object"!=typeof e.changes&&s.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)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})})),s.push(...ke(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&s.push(...Ne(i.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),i.indexes&&s.push(...Ce(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let r=["type","definition"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...je(e.definition,`${t}.definition`));break}case"removeIndex":{let r=["type","name"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`));break}case"modifyIndex":{let r=["type","name","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`)),"object"!=typeof e.changes&&s.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let r=["type","constraint"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"rules"in e.constraint?s.push(...Ae(e.constraint,"dynamic",`${t}.constraint`)):s.push(...Oe(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let r=["type","name"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`));break}case"modifyConstraint":{let r=["type","name","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`)),"object"!=typeof e.changes&&s.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=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`)),s.push(...Pe(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let r=["type","id"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`));break}case"modifyNestedSchema":{let r=["type","id","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`)),"object"!=typeof e.changes&&s.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:s.push({message:"Unknown schema change type",path:[`${t}.type`]})}return s},Fe=(e,t)=>{let s=[],r=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],i=[...r,"rollback","dependencies"],a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.id,`${t}.id`)),s.push(...ke(e.schemaVersion,`${t}.schemaVersion`)),s.push(...ke(e.description,`${t}.description`));let n=["pending","applied","failed"];return n.includes(e.status)||s.push({message:`Status must be one of ${n.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach(((e,r)=>{s.push(...qe(e,`${t}.changes[${r}]`))})):s.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach(((e,r)=>s.push(...qe(e,`${t}.rollback[${r}]`)))):s.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?s.push(...ke(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?s.push(...((e,t)=>{let s=[],r=["forward","backward"],i=r,a=e;return r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"function"!=typeof e.forward&&s.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&s.push({message:"Backward must be a function",path:[`${t}.backward`]}),s})(e.transform,`${t}.transform`)):s.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),s.push(...ke(e.createdAt,`${t}.createdAt`)),s.push(...ke(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(s.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every((e=>"string"==typeof e)))&&s.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),s},Be={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Schema must be an object",path:[]}]);let t=e,s=[],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],i=t;if(["name","version","fields"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[e]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[e]})})),s.push(...ke(t.name,"name")),s.push(...ke(t.version,"version")),"object"!=typeof t.fields||null===t.fields)s.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])=>{s.push(...De(r,`fields.${t}`,e))}))}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)s.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach((([t,r])=>s.push(...Pe(r,`nestedSchemas.${t}`,e))))}return s.push(...ke(t.description,"description",!1)),t.indexes&&s.push(...Ce(t.indexes,"indexes")),t.constraints&&s.push(...Ne(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&s.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(s.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every((e=>"string"==typeof e)))&&s.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach(((e,t)=>s.push(...Fe(e,`migrations[${t}]`)))):s.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&s.push({message:"Mock must be a function",path:["mock"]}),t.hint&&s.push(...Re(t.hint,"hint")),s.length>0?$e(s):_e(t)},types:{input:{},output:{}}},ze={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Migration must be an object",path:[]}]);let t=e,s=Fe(t,"");return s.length>0?$e(s):_e(t)},types:{input:{},output:{}}},Ue={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return $e([{message:"SchemaChanges must be an array",path:[]}]);let t=e,s=[];return t.forEach(((e,t)=>s.push(...qe(e,`[${t}]`)))),s.length>0?$e(s):_e(t)},types:{input:[],output:[]}};function Le(e){try{return!Be.validate(e).issues}catch(e){throw new be("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function Ve(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function He(e,t,s){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,s=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case"addField":if(s.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case"removeField":if(r.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);s.add(a.id);break;case"modifyField":if(s.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case"deprecateField":if(s.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id)}})(t),function(e){let t=new Set,s=new Set,r=new Set;for(let i of e)switch(i.type){case"addConstraint":let e=i.constraint.name;if(s.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);r.add(e);break;case"removeConstraint":if(r.has(i.name))throw new Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot remove modified constraint: ${i.name}`);s.add(i.name);break;case"modifyConstraint":if(s.has(i.name))throw new Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name)}}(t);let r=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new 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)}}(e),i="patch";for(let e of t){let t=Ve(e);if("major"===t){i="major";break}"minor"===t&&"patch"===i&&(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 Je(e,t){let s=e=>e.split(".").map((e=>parseInt(e,10)||0)),[r,i,a]=s(e),[n,o,c]=s(t);return r-n||i-o||a-c}var Ke,We=class extends Error{constructor(e,t,s,r){super(e),this.code=t,this.migrationId=s,this.cause=r,this.name="MigrationError"}},Ye=((Ke=Ye||{}).INVALID_SCHEMA="INVALID_SCHEMA",Ke.INVALID_MIGRATION="INVALID_MIGRATION",Ke.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Ke.TIMEOUT="TIMEOUT",Ke.MEMORY_LIMIT="MEMORY_LIMIT",Ke.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Ke.TRANSFORM_ERROR="TRANSFORM_ERROR",Ke.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Ke.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Ke.STREAM_ERROR="STREAM_ERROR",Ke.ROLLBACK_ERROR="ROLLBACK_ERROR",Ke.MISSING_TRANSFORM="MISSING_TRANSFORM",Ke),Ge=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,s){try{if(!Le(e))throw new We("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!ze.validate(e).issues}catch(e){throw new be("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new We("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>Je(e.schemaVersion,t.schemaVersion)))}s&&(this.history=s.sort(((e,t)=>Je(e.version,t.version))))}catch(e){throw e instanceof We?e:new We("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map((e=>e.toString(16).padStart(2,"0"))).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new We("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new We("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!Ue.validate(e).issues}catch(e){throw new be("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new We("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,s,r){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(s,r);return{newSchema:a.reduce(((e,t)=>{let r="forward"===s?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)}),i),dataPreview:await e.processMigrationList(t,s,a)}}catch(e){throw e instanceof We?e:new We("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter((s=>{let r="forward"===e?"pending":"applied",i=!t||Je(s.schemaVersion,t)>=0;return s.status===r&&i})).sort(((t,s)=>"forward"===e?t.id.localeCompare(s.id):s.id.localeCompare(t.id)))}applySchemaChanges(e,t,s){try{let r=He(e.version,t);return t.map((t=>{try{return me(t,e)}catch(e){throw new We("Invalid schema change","INVALID_SCHEMA",s,e)}})).reduce(((e,t)=>{try{return function(e,t){let s=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":s=ue(s,e.path,e.value);break;case"remove":s=pe(s,e.path);break;case"removeValue":s=de(s,e.path,e.value);break;case"replace":s=ue(pe(s,e.path),e.path,e.value);break;case"copy":{let t=le(s,e.from);s=ue(s,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=le(s,e.from);s=ue(s,e.path,t),s=pe(s,e.from);break}case"test":{let t=le(s,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ie("Test operation failed");break}default:throw new ie(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ie&&(t.operation=e),t}return s}(e,t)}catch(e){throw new We("Failed to apply patch","INVALID_SCHEMA",s,e)}}),{...e,version:r})}catch(e){throw e instanceof We?e:new We("Schema update failed","INVALID_SCHEMA",s,e)}}async prepareMigration(){let e=this.migrations.filter((e=>"pending"===e.status));return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");let s=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let r=await e.processMigrationList(t,"forward",s);return this.markMigrationsApplied(s),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 We("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 We("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter((e=>"applied"===e.status)).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,s){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");try{let r=this.history.findIndex((e=>e.version===t));if(-1===r)throw new Error(`Version ${t} not found in history`);let i=this.migrations.filter((e=>e.schemaVersion===t&&"applied"===e.status)).sort(((e,t)=>t.id.localeCompare(e.id))),a=this.history.length-r;if(a<0)return s;for(let e=0;e<a;e++)this.transformSchema("backward");let n=await e.processMigrationList(s,"backward",i);return this.migrations=this.migrations.map((e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e)),n}finally{this.isProcessing=!1}}static async processMigrationList(e,t,s){return(await Promise.all(s.map((async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new We(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}})))).filter((e=>!!e.transform)).reduce(((e,{migration:t,transform:s})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await s(e);r.enqueue(t)}catch(e){r.error(new We(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}}))),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?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 s=await fetch(e);if(!s.ok)throw new We(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await s.text();if(typeof window<"u"){let e=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:s}=await import("vm"),i={module:{exports:{}},console:console};return s(r,i,e),i.module.exports[t]}}catch(t){throw new We(`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 We(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter((e=>"pending"===e.status)).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 We?e:new We("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=s.Buffer);var Xe=u(f()),Qe=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let s=-1;const r=i=>{if(i<=s)throw new Error("next() called multiple times");s=i;const 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){const s=this;return new Proxy(e,{get(e,r,i){const a=Reflect.get(e,r,i);return"function"==typeof a?function(...i){const n={...t,operation:r.toString(),args:i};return s.execute(n,(()=>a.apply(e,i)))}:a}})}},Ze=async(e,t)=>{const s=Date.now();try{const r=await t();return et(e,s,r,null),r}catch(t){throw et(e,s,void 0,t),t}};function et(e,t,s,r){if(!e.eventBus)return;const 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(s)?"array":typeof s,size:Array.isArray(s)?s.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}var{match:tt}=(0,Xe.createMatcher)({});async function st(e){const{collection:t,initial:s,validator:i,store:a,bus:n,lockManager:o}=e,[c,h]=X(s),{value:l,issues:d}=i?await i["~standard"].validate(c):{value:s,issues:void 0};if(d)throw console.warn({issues:d}),new Y("INVALID_DATA",`Invalid data for ${t}`);const u={current:Object.assign(l,h),deleted:!1};void 0===u.current.$id&&(u.current=Object.assign(u.current,{$id:r.v7(),$created:(new Date).toJSON(),$version:1}));const p={save:async e=>{const s=await o.acquire();try{const{$id:s,$version:r}=u.current;if(!s)throw new Error("Document ID missing.");const i=await a.getById(s);if(i&&i.$version!==r)throw new Y("CONFLICT",`Version mismatch on ${t}/${s}`);return u.current.$version=(r||0)+1,u.current.$updated=(new Date).toJSON(),e?await e.addOp(a,"put",u.current):await a.put(u.current),n.emit({name:"document:write",payload:{type:"document:write",data:u.current,timestamp:Date.now()}}),!0}finally{s()}},update:async(e,s)=>{const[r,a]=X(Object.assign({},u.current,e)),{value:o,issues:c}=i?await i["~standard"].validate(r):{value:r,issues:void 0};if(c)throw new Y("INVALID_DATA",`Invalid update for ${t}`);u.current=Object.assign(o,a);const h=await p.save(s);return h&&n.emit({name:"document:update",payload:{type:"document:update",data:u.current,timestamp:Date.now()}}),h},delete:async e=>{const s=await o.acquire();try{const{$id:s,$version:r}=u.current;if(!s)throw new Error("Document ID missing.");const i=await a.getById(s);if(i&&i.$version!==r)throw new Y("CONFLICT",`Version mismatch on delete ${t}/${s}`);return e?await e.addOp(a,"delete",s):await a.delete(s),n.emit({name:"document:delete",payload:{type:"document:delete",data:u.current,timestamp:Date.now()}}),u.deleted=!0,!0}finally{s()}},read:async()=>{const e=u.current.$id,t=await a.getById(e);if(!t)throw new Error("Document not found.");return u.current={...t},n.emit({name:"document:read",payload:{type:"document:read",data:u.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=X(e);return t})(u.current),subscribe:n.subscribe};return new Proxy({},{get(e,t){if(["update","delete","subscribe","read","state","save"].includes(t)){const e=p[t];return(...t)=>{if(u.deleted)throw new Y("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(u.deleted)throw new Y("INVALID_OPERATION","Document has been deleted");return Reflect.get(u.current,t)}})}function rt(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}function it(e){return"function"==typeof e._getIDBConnection}var at=class{id;staged=[];done=!1;constructor(){this.id=r.v7()}async addOp(e,t,s){if(this.done)throw new Y("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");this.staged.push({store:e,op:{type:t,data:s}})}async commit(){if(this.done)throw new Y("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");if(this.done=!0,0===this.staged.length)return;const e=new Map,t=new Map;for(const{store:s,op:r}of this.staged)it(s)?(e.has(s)||e.set(s,[]),e.get(s).push(r)):(t.has(s)||t.set(s,[]),t.get(s).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){const t=Array.from(e.keys()).map((e=>e.name())),s=e.keys().next().value,r=await s._getIDBConnection();await new Promise(((s,i)=>{const a=r.transaction(t,"readwrite");a.oncomplete=()=>s(),a.onerror=()=>i(a.error??new Error("IDB transaction error")),a.onabort=()=>i(a.error??new Error("IDB transaction aborted")),(async()=>{try{for(const[t,s]of e)await t.executeInTransaction(s,a)}catch(e){try{a.abort()}catch(e){}i(e)}})()}))}async commitMemory(e){const t=[];try{for(const[s,r]of e){const e=s._snapshotMemory();t.push({store:s,snapshot:e}),await s.executeInTransaction(r,null)}}catch(e){for(const{store:e,snapshot:s}of t)try{e._rollbackMemory(s)}catch(e){}throw e}}completed(){return this.done}};function nt(e,t){return e instanceof Y?e:e instanceof Error?new Y("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new Y("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}async function ot(e,t){const s=W(),i=new Map,a=new Qe;a.use(((e=3,t=100)=>async(s,r)=>{let i=0;for(;i<e;)try{return await r()}catch(s){if(!(s instanceof Y&&"TRANSIENT_ERROR"===s.type))throw s;{if(i++,i>=e)throw s;const r=t*Math.pow(2,i)+50*Math.random();await new Promise((e=>setTimeout(e,r)))}}})()),e.enableTelemetry&&a.use(Ze);const n=new Map,o=t({...e,collection:"schemas",keyPath:"name"},[]);async function c(s,r=[]){let i=n.get(s);return i||(i=t({...e,collection:s,keyPath:"$id"},r),n.set(s,i)),await i.open(),i}async function h(t){if(i.has(t))return i.get(t);const n=await o.getById(t);if(!n)throw new Y("SCHEMA_NOT_FOUND",`Collection '${t}' does not exist`);const h=await c(t,n.indexes??[]),l=ve(n,e.predicates||{}),d=await async function({collection:e,validator:t,bus:s,store:i,pipeline:a,validate:n}){const o=new G,c={collection:e,validator:n?t:void 0,store:i,bus:s,pipeline:a,lockManager:o,valid:!0},h={async validate(e){const s=t["~standard"].validate(e);return s instanceof Promise?await s:s},create:async(a,o)=>{const[h,l]=X(a),{value:d,issues:u}=n?await t["~standard"].validate(h):{value:h,issues:void 0};if(u)throw new Y("INVALID_DATA",`Invalid data for collection '${e}'`);const p=Object.assign(d,l,{$id:r.v7(),$created:(new Date).toJSON(),$version:1});o?await o.addOp(i,"add",p):await i.add(p),s.emit({name:"document:create",payload:{type:"document:create",data:p,timestamp:Date.now()}});const m=await st({...c,initial:p});return s.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),m},find:async t=>{let r;const a=rt(t);if(a)try{const e=t.value;r=(await i.findByIndex(a,e))[0]}catch{r=void 0}if(void 0===r&&(r=await i.cursor((async e=>e&&tt(e,t)?{value:e,done:!0}:{value:null,done:!1}))??void 0),!r)return null;const n=await st({...c,initial:r});return s.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),n},filter:async t=>{let r=[];const a=rt(t);if(a)try{const e=t.value;r=await i.findByIndex(a,e)}catch{r=[]}0===r.length&&await i.cursor((async e=>(e&&tt(e,t)&&r.push(e),{value:null,done:!1})));const n=await Promise.all(r.map((e=>st({...c,initial:e}))));return s.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),n},list:async t=>{const r={total:await i.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return 0===r.total?{next:async()=>({value:[],done:!0})}:{async next(){const a="offset"===t.type?await async function(e,t){const{offset:s,limit:r}=t,i=[];let a=0,n=!1;for(;!(n||(await e((async e=>a<s?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,a>=s+r?(n=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),i.length>=r)););return i}(i.cursor.bind(i),{...t,offset:r.offset}):await async function(e,t){const{limit:s,direction:r}=t,i=[];let a=!1;for(;!a;)await e((async e=>(i.push(e),i.length>=s?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),r);return i}(i.cursor.bind(i),{...t});r.offset+=r.limit,r.count+=a.length;const n=await Promise.all(a.map((e=>st({...c,initial:e}))));return s.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:n,done:r.count>=r.total}}}}},l={...a.wrap(h,{collection:e,eventBus:s}),subscribe:s.subscribe,invalidate:()=>c.valid=!1};return new Proxy(l,{get(t,s,r){const i=Reflect.get(t,s,r);return"function"==typeof i?(...r)=>{if(!c.valid&&"invalidate"!==s)throw new Y("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}({collection:t,bus:s,validator:l,validate:Boolean(e.validate),store:h,pipeline:a});return s.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),i.set(t,d),i.get(t)}async function l(e){return await o.put(e),s.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await o.open();const d={collection:h,createCollection:async e=>{if(await o.getById(e.name))throw new Y("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!Le(e))throw new Y("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await o.put(e);const t=h(e.name);return s.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await o.getById(e);if(!t)throw new Y("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const r=await c(e,t.indexes??[]);return await r.clear(),n.delete(e),await o.delete(e),i.delete(e),s.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:l,migrateCollection:async(e,t,s=100)=>{const r=i.get(e);r&&(r.invalidate(),i.delete(e));const a=await o.getById(e);if(!a)throw new Y("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const n=await c(e,a.indexes??[]),d=new Ge(a);await d.add(t);const u=(await d.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema,p=new Set((a.indexes??[]).map((e=>e.name))),m=u.indexes??[],f=new Set(m.map((e=>e.name))),y=m.filter((e=>!p.has(e.name))),g=(a.indexes??[]).filter((e=>!f.has(e.name)));await l(u);try{const t=function(e,t,s){let r,i=!1;return new ReadableStream({async pull(a){if(i)return void a.close();let n=0;const o=void 0!==r?{lower:r,lowerOpen:!0}:void 0;try{await t.cursor((async(e,t)=>(a.enqueue(e),r=t,n++,n>=s?{done:!0,value:e}:{done:!1,value:e})),"forward",o),n<s&&(i=!0)}catch(t){a.error(nt(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,n,s),r=await d.migrate(t);await async function(e,t,s,r){const i=t.getReader();let a=[];try{for(;;){const{value:e,done:t}=await i.read();if(t)break;if(!e)continue;const{$version:n}=e;e.$version=(n||0)+1,e.$updated=(new Date).toJSON(),a.push(e),a.length>=r&&(await s.batch([{type:"put",data:a}]),a=[])}a.length>0&&await s.batch([{type:"put",data:a}])}catch(t){throw nt(t,e)}finally{i.releaseLock()}}(e,r,n,s)}catch(t){throw nt(t,e)}for(const e of y)await n.createIndex(e);for(const e of g)await n.dropIndex(e.name);return await h(e)}},u=a.wrap(d,{eventBus:s}),p={...u,transaction:async e=>{const t=new at;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:s.subscribe,close:()=>{n.clear(),s.clear()},clear:async()=>{await o.clear(),await Promise.all(n.values().map((e=>e.clear())))},ensureCollection:async e=>{try{await u.createCollection(e)}catch(e){if(e instanceof Y&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await p.ensureCollection(t)}};return p}var ct=u(f()),ht=class e{static dbInstances=new Map;static collectionInstances=new Map;static eventBusMap=new Map;static defaultModelName="stores";static getDatabase(t){const{database:s,enableTelemetry:r=!1,collection:i=e.defaultModelName}=t;if(!e.dbInstances.has(s)){const t=ot({database:s,enableTelemetry:r},re).then((async e=>{try{await e.createCollection({name:i,version:"1.0.0",nestedSchemas:{},fields:{store:{name:"store",type:"string",required:!0},data:{name:"data",type:"object",required:!0},version:{name:"version",type:"string",required:!0},app:{name:"app",type:"string",required:!0}}})}catch(e){if(e instanceof Y&&"SCHEMA_ALREADY_EXISTS"!==e.type)throw e}return e}));e.dbInstances.set(s,t)}return e.dbInstances.get(s)}static getEventBus(t,s){const r=`${t}_store_${s}`;return e.eventBusMap.has(r)||e.eventBusMap.set(r,W({batch:{size:5,delay:16},errorHandler:e=>console.error(`Event bus error for ${t}:${s}:`,e),broadcast:{channel:r}})),e.eventBusMap.get(r)}static getCollection(t){const{database:s,collection:r=e.defaultModelName}=t,i=`${s}:${r}`;if(!e.collectionInstances.has(i)){const s=e.getDatabase(t).then((e=>e.collection(r)));e.collectionInstances.set(i,s)}return e.collectionInstances.get(i)}static async closeDatabase(t){const s=e.dbInstances.get(t);if(s){(await s).close(),e.dbInstances.delete(t);const r=[];e.collectionInstances.forEach(((e,s)=>{s.startsWith(`${t}:`)&&r.push(s)})),r.forEach((t=>e.collectionInstances.delete(t)));const i=[];e.eventBusMap.forEach(((e,s)=>{s.startsWith(`${t}_store_`)&&(e.clear(),i.push(s))})),i.forEach((t=>e.eventBusMap.delete(t)))}}static async closeAll(){const t=Array.from(e.dbInstances.keys()).map((t=>e.closeDatabase(t)));await Promise.all(t)}static getActiveDatabases(){return Array.from(e.dbInstances.keys())}};exports.IndexedDBPersistence=class{collection=null;collectionPromise;config;eventBus;initialized=!1;initializationCallbacks=[];doc=null;getStoreName(){return`_${this.config.app}_${this.config.store}_`}constructor(e){this.config=e,this.collectionPromise=ht.getCollection(this.config),this.collectionPromise.then((e=>{this.collection=e,this.initialize()})).catch((e=>{console.error(`Failed to initialize collection for store ${this.getStoreName()}:`,e)})),this.eventBus=ht.getEventBus(this.config.database,this.getStoreName())}async initialize(){try{const e=await this._get();if(e&&e.version!==this.config.version&&this.config.onUpgrade){const{state:t}=await this.config.onUpgrade({data:e.data,version:e.version,app:e.app});await this.set("migration",t)}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize and upgrade store ${this.getStoreName()}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}async getCollection(){return this.collection?this.collection:this.collectionPromise}async set(e,t){try{const s=await this.getCollection(),r=await this._read(),i={store:this.getStoreName(),data:t,version:this.config.version,app:this.config.app};let a;return r?a=await r.update(i):(this.doc=await s.create(i),a=!0),a&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.getStoreName(),instanceId:e,state:t,version:this.config.version,app:this.config.app}}),a}catch(t){return console.error(`Failed to set state for store ${this.getStoreName()} in database ${this.config.database} by instance ${e}:`,t),!1}}async _read(){if(this.doc)return this.doc;const e=await this.getCollection(),t=(new ct.QueryBuilder).where({field:"store",operator:"eq",value:this.getStoreName()}).build(),s=await e.find(t.filters);return this.doc=s,this.doc}async _get(){try{const e=await this._read();return e?e.read().then((()=>e)):null}catch(e){return console.error(`Failed to get state for store ${this.getStoreName()} in database ${this.config.database}:`,e),null}}async get(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));const e=await this._get();return e?e.data:null}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:s,instanceId:r,state:i})=>{s===this.getStoreName()&&r!==e&&t(i)}))}async clear(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));try{const e=await this._read();return!e||!await e.delete()||(this.doc=null,!0)}catch(e){return console.error(`Failed to clear state for store ${this.getStoreName()} in database ${this.config.database}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}async close(){await ht.closeDatabase(this.config.database)}},exports.WebStoragePersistence=class{eventBus;storage;config;initialized=!1;initializationCallbacks=[];constructor(e){this.config=e,this.storage=e.session?sessionStorage:localStorage,this.eventBus=this.initializeEventBus(),this.initialize(),e.session||this.setupStorageEventListener()}async initialize(){try{const e=this.storage.getItem(this.getStoreName());if(e){const t=JSON.parse(e);if(t.version!==this.config.version&&this.config.onUpgrade){const{state:e}=await this.config.onUpgrade({data:t.state,version:t.version,app:t.app});this.set("migration",e)}}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize WebStoragePersistence for ${this.config.storageKey}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}initializeEventBus(){return(0,U.createEventBus)({async:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${this.config.storageKey}:`,e),crossTab:"undefined"==typeof process||"test"!==process.env.NODE_ENV,channelName:`storage_${this.getStoreName()}`})}getStoreName(){return`_${this.config.app}_${this.config.storageKey}_`}setupStorageEventListener(){window.addEventListener("storage",(e=>{if(e.key===this.getStoreName()&&e.newValue)try{const t=JSON.parse(e.newValue);t&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"external",state:t.state,version:t.version,app:t.app}})}catch(e){console.error("Failed to parse storage event data:",e)}}))}set(e,t){try{const s={state:structuredClone(t),version:this.config.version,app:this.config.app},r=JSON.stringify(s);return this.storage.setItem(this.getStoreName(),r),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:e,state:t,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to persist state to web storage for ${this.config.storageKey}:`,e),!1}}_get(){try{const e=this.storage.getItem(this.getStoreName());if(!e)return null;return JSON.parse(e).state}catch(e){return console.error(`Failed to retrieve state from web storage for ${this.config.storageKey}:`,e),null}}async get(){return this.initialized||await new Promise((e=>{this._onInitialized(e)})),this._get()}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:s,instanceId:r,state:i})=>{s===this.config.storageKey&&r!==e&&t(i)}))}clear(){try{return this.storage.removeItem(this.getStoreName()),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"clear-initiator",state:null,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to clear persisted state for ${this.config.storageKey}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}};
1
+ "use strict";var e,t,r=require("buffer"),s=require("uuid"),a=Object.create,i=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},d=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))h.call(e,a)||a===r||i(e,a,{get:()=>t[a],enumerable:!(s=n(t,a))||s.enumerable});return e},u=(e,t,r)=>(r=null!=e?a(c(e)):{},d(e&&e.__esModule?r:i(r,"default",{value:e,enumerable:!0}),e)),p=e=>d(i({},"__esModule",{value:!0}),e),m=l({"node_modules/@asaidimu/events/index.js"(e,t){var r,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of i(t))n.call(e,c)||c===r||s(e,c,{get:()=>t[c],enumerable:!(o=a(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,a=0;const i=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,a+=t,i.set(e,(i.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const s=performance.now();try{(n.get(t)||[]).forEach((e=>e(r)))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?n.set(e,Array.from(r)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(n.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),d(e),()=>{s.delete(r),0===s.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:s})=>{if(e.async)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():l(),void(o&&o.postMessage({name:t,payload:s}));const a=performance.now();try{(n.get(t)||[]).forEach((e=>e(s))),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-a)},getMetrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:i,averageEmitDuration:s>0?a/s:0}),clear:()=>{t.clear(),n.clear(),r=[],s=0,a=0,i.clear(),o&&(o.close(),o=null)}}}}}),f=l({"node_modules/@asaidimu/query/index.js"(e,t){var r,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>l,createPaginator:()=>E,createProjector:()=>_,createSorter:()=>$}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of i(t))!n.call(e,c)&&c!==r&&s(e,c,{get:()=>t[c],enumerable:!(o=a(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=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,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},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,r){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:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,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 h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?s(t,e):function(e){return"computed"===e?.type}(t)?s(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(a(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every((t=>a(e,t)))],["or",(e,t)=>t.some((t=>a(e,t)))],["not",(e,t)=>!t.every((t=>a(e,t)))],["nor",(e,t)=>!t.some((t=>a(e,t)))],["xor",(e,t)=>1===t.filter((t=>a(e,t))).length]]);function s(r,s){let a=r.arguments.map((e=>t(s,e)));if(e[r.function])return e[r.function](...a);throw new Error(`Function ${r.function} not found!`)}function a(s,a){if(function(e){return!!e&&void 0!==e.conditions}(a))return function(e,t){let{operator:s,conditions:a}=t,i=r.get(s);if(i)return i(e,a);throw new Error(`Unsupported logical operator: ${s}`)}(s,a);if(!a||!a.field)return!1;let{field:i,operator:n,value:o}=a,c=s[i],h=t(s,o),l=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)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[n]||l.get(n);if(d)return d(c,h);throw new Error(`Unsupported comparison operator: ${n}`)}return{resolve:t,evaluate:a}}function l(e){let{evaluate:t}=h(e),r=new WeakMap;function s(e,s){let a=r.get(e);a||(a=new Map,r.set(e,a));let i=JSON.stringify(s);if(a.has(i))return a.get(i);let n=t(e,s);return a.set(i,n),n}return{matcher:s,match:s}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},u=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(u(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map((e=>p(e,t)))),r}return e}},m=async(e,t,r,s)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let a,i=e[r.relation];return r.query?.filters&&u(r.query.filters)&&(a=((e,t)=>{let r=new Map;return e.forEach((e=>{let s=e[t];r.has(s)||r.set(s,[]),r.get(s).push(e)})),r})(i,r.query.filters.field)),(await Promise.all(t.map((async e=>{let t,n=((e,t)=>{if(!e)return{};let r=p(e.filters,t);return{...e,filters:r}})(r.query,e);return t=n.filters&&u(n.filters)&&a?.has(n.filters.value)?a.get(n.filters.value)||[]:i.filter((e=>s.matcher(e,n.filters))),((e,t,r)=>{let s=r.alias||r.relation;return[{...e,[s]:t}]})(e,await[e=>n.sort?s.sorter(e,n.sort):e,e=>n.projection?s.projector(e,n.projection):e,async e=>n.pagination?await s.paginator(e,n.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),r)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,r,s)=>r.reduce((async(t,r)=>m(e,await t,r,s)),Promise.resolve(t));function y(){return{join:f}}var g=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},w=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new g(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort(((e,r)=>{for(let s of t){let{field:t,direction:a}=s,i=e[t],n=r[t];try{if("asc"!==a&&"desc"!==a)throw new w(a);let e=b(i,n,a);if(0!==e)return e}catch(e){throw e instanceof g||e instanceof w?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function $(){return{sort:v}}function _(e){let{resolve:t}=h(e);function r(e,s){let a={};return s.include?.length&&function(e,t,s){for(let a of t)if("string"!=typeof a){for(let[t,i]of Object.entries(a))if(Object.prototype.hasOwnProperty.call(e,t)){let a=r(e[t],i);s[t]=a}}else{let t=a;s[t]=e[t]}}(e,s.include,a),s.exclude?.length&&function(e,t,s){0===Object.keys(s).length&&Object.assign(s,e);for(let e of t)if("string"!=typeof e)for(let[t,a]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(s,t))continue;let e=s[t];e&&"object"==typeof e?s[t]=r(e,a):delete s[t]}else delete s[e]}(e,s.exclude,a),s.computed?.length&&function(e,r,s){for(let a of r)s[a.alias]=t(e,a)}(e,s.computed,a),a}return{project:r}}async function*k(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:s}=t,a=0,i=s,n=[];for await(let t of e)i<=0&&(yield n,n=[],i=s),a<r?a++:(n.push(t),i--);n.length>0&&(yield n)}(e,t):yield*async function*(e,t,r){let{cursor:s,limit:a,direction:i}=t,n=a,o=void 0===s,c=[];if("forward"===i)for await(let t of e)n<=0&&(yield c,c=[],n=a),o?(c.push(t),n--):o=r(t)===s;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let i=t[e];o?(c.push(i),n--,n<=0&&(yield c,c=[],n=a)):o=r(i)===s}}c.length>0&&(yield c)}(e,t,r)}function E(){return{paginate:k}}}}),y=l({"node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,r;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?r:(t=!0,r=e.apply(this,arguments))}}}}),g=l({"node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),w=l({"node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,r){var s;return function(){if(!t)return e.apply(this,arguments);var a=this,i=arguments,n=r&&!s;return clearTimeout(s),s=setTimeout((function(){if(s=null,!n)return e.apply(a,i)}),t),n?e.apply(this,arguments):void 0}}}}),b=l({"node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function r(e){if(0===e.length)return".";let t=a(e);return t=t.reduce(i,[]),s(...t)}function s(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function a(e){if(0===e.length)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 i(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new 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:s,normalize:r,split:a,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let a of e)t=a.startsWith("/")?a:r(s(t,a));return t}}}}),v=l({"node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function r(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var s=r("EEXIST"),a=r("ENOENT"),i=r("ENOTDIR"),n=r("ENOTEMPTY"),o=r("ETIMEDOUT"),c=r("EISDIR");t.exports={EEXIST:s,ENOENT:a,ENOTDIR:i,ENOTEMPTY:n,ETIMEDOUT:o,EISDIR:c}}}),$=l({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=b(),{EEXIST:s,ENOENT:a,ENOTDIR:i,ENOTEMPTY:n,EISDIR:o}=v();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){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):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[r,s]of e)0!==r&&(t+=this._countInodes(s));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[r,s]of e)0!==r&&(t=Math.max(t,this._maxInode(s)));return t}print(e=this._root.get("/")){let t="";const r=(e,s)=>{for(let[a,i]of e){if(0===a)continue;let e=i.get(0),n=e.mode.toString(8);t+=`${"\t".repeat(s)}${a}\t${n}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",r(i,s+1))}};return r(e,0),t}parse(e){let t=0;function r(e){const r=++t,s=1===e.length?"dir":"file";let[a,i,n]=e;return a=parseInt(a,8),i=i?parseInt(i):0,n=n?parseInt(n):Date.now(),new Map([[0,{mode:a,type:s,size:i,mtimeMs:n,ino:r}]])}let s=e.trim().split("\n"),a=this._makeRoot(),i=[{indent:-1,node:a},{indent:0,node:null}];for(let e of s){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[s,...a]=e.split("\t"),n=r(a);if(t<=i[i.length-1].indent)for(;t<=i[i.length-1].indent;)i.pop();i.push({indent:t,node:n}),i[i.length-2].node.set(s,n)}return a}_lookup(e,t=!0){let s=this._root,i="/",n=r.split(e);for(let o=0;o<n.length;++o){let c=n[o];if(s=s.get(c),!s)throw new a(e);if(t||o<n.length-1){const e=s.get(0);if("symlink"===e.type){let t=r.resolve(i,e.target);s=this._lookup(t)}i=i?r.join(i,c):c}}return s}mkdir(e,{mode:t}){if("/"===e)throw new s;let a=this._lookup(r.dirname(e)),i=r.basename(e);if(a.has(i))throw new s;let n=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};n.set(0,o),a.set(i,n)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new i;if(t.size>1)throw new n;let s=this._lookup(r.dirname(e)),a=r.basename(e);s.delete(a)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new i;return[...t.keys()].filter((e=>"string"==typeof e))}writeStat(e,t,{mode:s}){let a,i;try{i=this.stat(e)}catch(e){}if(void 0!==i){if("dir"===i.type)throw new o;null==s&&(s=i.mode),a=i.ino}null==s&&(s=438),null==a&&(a=this.autoinc());let n=this._lookup(r.dirname(e)),c=r.basename(e),h={mode:s,type:"file",size:t,mtimeMs:Date.now(),ino:a},l=new Map;return l.set(0,h),n.set(c,l),h}unlink(e){let t=this._lookup(r.dirname(e)),s=r.basename(e);t.delete(s)}rename(e,t){let s=r.basename(t),a=this._lookup(e);this._lookup(r.dirname(t)).set(s,a),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 s,a;try{let e=this.stat(t);null===a&&(a=e.mode),s=e.ino}catch(e){}null==a&&(a=40960),null==s&&(s=this.autoinc());let i=this._lookup(r.dirname(t)),n=r.basename(t),o={mode:a,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:s},c=new Map;return c.set(0,o),i.set(n,c),o}_du(e){let t=0;for(const[r,s]of e.entries())t+=0===r?s.size:this._du(s);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),_={};function k(){return t||(t=new e),t}function E(e,t=k()){let r;return t._withIDBStore("readwrite",(t=>{r=t.get(e)})).then((()=>r.result))}function S(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{r.put(t,e)}))}function I(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}}))}function O(e,t=k()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function A(e=k()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function N(e=k()){const 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 x(e=k()){return e._close()}((e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})})(_,{Store:()=>e,clear:()=>A,close:()=>x,del:()=>O,get:()=>E,keys:()=>N,set:()=>S,update:()=>I});var j,C,T=(j={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){e=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise(((e,t)=>{const r=indexedDB.open(this._dbName);r.onerror=()=>t(r.error),r.onsuccess=()=>e(r.result),r.onupgradeneeded=()=>{r.result.createObjectStore(this._storeName)}})))}_withIDBStore(e,t){return this._init(),this._dbp.then((r=>new Promise(((s,a)=>{const i=r.transaction(this.storeName,e);i.oncomplete=()=>s(),i.onabort=i.onerror=()=>a(i.error),t(i.objectStore(this.storeName))}))))}_close(){return this._init(),this._dbp.then((e=>{e.close(),this._dbp=void 0}))}}}},function(){return j&&(C=(0,j[o(j)[0]])(j=0)),C}),M=l({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(T(),p(_));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename)}saveSuperblock(e){return r.set("!root",e,this._store)}loadSuperblock(){return r.get("!root",this._store)}readFile(e){return r.get(e,this._store)}writeFile(e,t){return r.set(e,t,this._store)}unlink(e){return r.del(e,this._store)}wipe(){return r.clear(this._store)}close(){return r.close(this._store)}}}}),R=l({"node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(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){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),D=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(T(),p(_)),s=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 r.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await r.update("lock",(r=>{const s=Date.now()+e;return t=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:s}:r,this._lock}),this._store),t}async acquire({ttl:e=5e3}={}){let t,s,a;if(await r.update("lock",(r=>{const i=Date.now(),n=i+e;return s=r&&r.expires<i,t=void 0===r||s,a=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:n}:r,this._lock}),this._store),a)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:r}={}){for(;t--;){if(await this.acquire({ttl:r}))return!0;await s(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,s,a;if(await r.update("lock",(r=>(t=e||r&&r.holder===this._id,s=void 0===r,a=r&&r.holder!==this._id,this._lock=t?void 0:r,this._lock)),this._store),await r.close(this._store),!t&&!e){if(s)throw new Error("Mutex double-freed");if(a)throw new Error("Mutex lost ownership")}return t}}}}),P=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(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,r)=>{const s=new AbortController;setTimeout((()=>{s.abort(),r(new Error("Mutex timeout"))}),e),navigator.locks.request(this._database+"_lock",{signal:s.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))}}}}),q=l({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=g(),a=w(),i=$(),{ENOENT:n,ENOTEMPTY:o,ETIMEDOUT:c}=v(),h=M(),l=R(),d=D(),u=P(),p=b();t.exports=class{constructor(){this.saveSuperblock=a((()=>{this.flush()}),500)}async init(e,{wipe:t,url:r,urlauto:s,fileDbName:a=e,db:n=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=n||new h(a,o),this._mutex=navigator.locks?new u(e):new d(c,p),this._cache=new i(e),this._opts={wipe:t,url:r},this._needsWipe=!!t,r&&(this._http=new l(r),this._urlauto=!!s)}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();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const 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,r){let s=p.split(p.dirname(e)),a=s.shift();for(let e of s){a=p.join(a,e);try{this._cache.mkdir(a,{mode:511})}catch(e){}}return this._cache.writeStat(e,t,r)}async readFile(e,t){const r="string"==typeof t?t:t&&t.encoding;if(r&&"utf8"!==r)throw new Error('Only "utf8" encoding is supported in readFile');let a=null,i=null;try{i=this._cache.stat(e),a=await this._idb.readFile(i.ino)}catch(e){if(!this._urlauto)throw e}if(!a&&this._http){let t=this._cache.lstat(e);for(;"symlink"===t.type;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);a=await this._http.readFile(e)}if(a&&(i&&i.size==a.byteLength||(i=await this._writeStat(e,a.byteLength,{mode:i?i.mode:438}),this.saveSuperblock()),"utf8"===r?a=s(a):a.toString=()=>s(a)),!i)throw new n(e);return a}async writeFile(e,t,s){const{mode:a,encoding:i="utf8"}=s;if("string"==typeof t){if("utf8"!==i)throw new Error('Only "utf8" encoding is supported in writeFile');t=r(t)}const n=await this._cache.writeStat(e,t.byteLength,{mode:a});await this._idb.writeFile(n.ino,t)}async unlink(e,t){const r=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==r.type&&await this._idb.unlink(r.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:r=511}=t;this._cache.mkdir(e,{mode:r})}rmdir(e,t){if("/"===e)throw new o;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 r=await this._http.sizeFile(e);await this._writeStat(e,r,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),F=l({"node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(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"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),B=l({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=q(),s=F(),a=b();function i(e,t,...r){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=a.normalize(e),t,...r]}function n(e,t,r,...s){return void 0!==r&&"function"!=typeof r||(r={}),"string"==typeof r&&(r={encoding:r}),[e=a.normalize(e),t,r,...s]}function o(e,t,...r){return[a.normalize(e),a.normalize(t),...r]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,i,!1),this.writeFile=this._wrap(this.writeFile,n,!0),this.unlink=this._wrap(this.unlink,i,!0),this.readdir=this._wrap(this.readdir,i,!1),this.mkdir=this._wrap(this.mkdir,i,!0),this.rmdir=this._wrap(this.rmdir,i,!0),this.rename=this._wrap(this.rename,o,!0),this.stat=this._wrap(this.stat,i,!1),this.lstat=this._wrap(this.lstat,i,!1),this.readlink=this._wrap(this.readlink,i,!1),this.symlink=this._wrap(this.symlink,o,!0),this.backFile=this._wrap(this.backFile,i,!0),this.du=this._wrap(this.du,i,!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 r,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(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,r){return async(...s)=>{s=t(...s);let a={name:e.name,args:s};this._operations.add(a);try{return await this._activate(),await e.apply(this,s)}finally{this._operations.delete(a),r&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(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,r){return await this._backend.writeFile(e,t,r),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){const r=await this._backend.stat(e,t);return new s(r)}async lstat(e,t){const r=await this._backend.lstat(e,t);return new s(r)}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()}}}}),z=l({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=y(),s=B();function a(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=r(t)]}t.exports=class{constructor(...e){this.promises=new s(...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,r){const[s,i]=a(t,r);this.promises.readFile(e,t).then(s).catch(i)}writeFile(e,t,r,s){const[i,n]=a(r,s);this.promises.writeFile(e,t,r).then(i).catch(n)}unlink(e,t,r){const[s,i]=a(t,r);this.promises.unlink(e,t).then(s).catch(i)}readdir(e,t,r){const[s,i]=a(t,r);this.promises.readdir(e,t).then(s).catch(i)}mkdir(e,t,r){const[s,i]=a(t,r);this.promises.mkdir(e,t).then(s).catch(i)}rmdir(e,t,r){const[s,i]=a(t,r);this.promises.rmdir(e,t).then(s).catch(i)}rename(e,t,r){const[s,i]=a(r);this.promises.rename(e,t).then(s).catch(i)}stat(e,t,r){const[s,i]=a(t,r);this.promises.stat(e).then(s).catch(i)}lstat(e,t,r){const[s,i]=a(t,r);this.promises.lstat(e).then(s).catch(i)}readlink(e,t,r){const[s,i]=a(t,r);this.promises.readlink(e).then(s).catch(i)}symlink(e,t,r){const[s,i]=a(r);this.promises.symlink(e,t).then(s).catch(i)}backFile(e,t,r){const[s,i]=a(t,r);this.promises.backFile(e,t).then(s).catch(i)}du(e,t){const[r,s]=a(t);this.promises.du(e).then(r).catch(s)}flush(e){const[t,r]=a(e);this.promises.flush().then(t).catch(r)}}}}),U=u(m()),L=(e={batch:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,a=0;const i=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,a+=t,i.set(e,(i.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const s=performance.now();try{(n.get(t)||[]).forEach((e=>e(r)))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?n.set(e,Array.from(r)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(n.get(t)||[]).forEach((e=>e(r)))}),{once:(e,r)=>{let s;const a=e=>{s(),r(e)};return s=(()=>{t.has(e)||t.set(e,new Set);const r=t.get(e);return r.add(a),()=>{r.delete(a),0===r.size&&t.delete(e)}})(),s},subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),d(e),()=>{s.delete(r),0===s.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:s})=>{if(e.batch)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():l(),void(o&&o.postMessage({name:t,payload:s}));const a=performance.now();try{(n.get(t)||[]).forEach((e=>e(s))),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-a)},metrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:i,averageEmitDuration:s>0?a/s:0}),clear:()=>{t.clear(),n.clear(),r=[],s=0,a=0,i.clear(),o&&(o.close(),o=null)}}},V=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}},H=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function J(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce(((e,[r,s])=>(r.startsWith("$")?t[r]=s:e[r]=s,e)),{}),t]}function K(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new V("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}var W=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},Y=class extends W{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},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)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await r;let s;await Promise.race([r.then((()=>clearTimeout(s))),new Promise(((r,a)=>{s=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),a(new Y("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},X=class{mutex=new G({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}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){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new 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()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const 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 null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new 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,r="Operation timed out"){if(null==t)return e;let s;return Promise.race([e.then((e=>(clearTimeout(s),e))),new Promise(((e,a)=>{s=setTimeout((()=>a(new Y(r))),t)}))])}},Q=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new X({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const r=indexedDB.open(this.config.database);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)}))}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise(((e,s)=>{const a=indexedDB.open(this.config.database,r);a.onerror=()=>s(new Error(`Failed to upgrade database: ${a.error?.message}`)),a.onupgradeneeded=e=>{const r=e.target.result,s=e.target.transaction;t(r,s)},a.onsuccess=()=>e(a.result)}))}async ensureStore(e,t="$id",r=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade((s=>{if(s.objectStoreNames.contains(this.schemasStoreName)||s.createObjectStore(this.schemasStoreName,{keyPath:"name"}),!s.objectStoreNames.contains(e)){const a=s.createObjectStore(e,{keyPath:t});for(const e of r){const t=1===e.fields.length?e.fields[0]:e.fields;a.createIndex(e.name,t,{unique:e.unique??!1})}}}))}async createStoreIndex(e,t){await this.upgrade(((r,s)=>{const a=s.objectStore(e);if(a.indexNames.contains(t.name))return;const i=1===t.fields.length?t.fields[0]:t.fields;a.createIndex(t.name,i,{unique:t.unique??!1})}))}async dropStoreIndex(e,t){await this.upgrade(((r,s)=>{const a=s.objectStore(e);a.indexNames.contains(t)&&a.deleteIndex(t)}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new V("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){const t=await this.getConnection();this.connectionInitializer.reset();const r=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(t,e)));if(r.error)throw new V("INTERNAL_ERROR",`Database upgrade failed for ${this.config.database}`,void 0,r.error);return r.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function Z(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var ee=class{constructor(e,t,r="$id",s=[]){this.connectionManager=e,this.collection=t,this.keyPath=r,this.indexes=s}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 r=>{const s=r.index(e);return this.requestToPromise(s.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(Z(t)))}))}async findByIndex(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e),a=IDBKeyRange.only(t);return this.requestToPromise(s.getAll(a))}))}async put(e){return this.withTx("readwrite",(async t=>{const r=e[this.keyPath];if(void 0!==r){K(await this.requestToPromise(t.get(r)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const r of e)if("put"===r.type||"add"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const s of e)if("put"===r.type){const e=s[this.keyPath];if(void 0!==e){K(await this.requestToPromise(t.get(e)),s)}await this.requestToPromise(t.put(s))}else await this.requestToPromise(t.add(s))}else{const e=Array.isArray(r.data)?r.data:[r.data];for(const r of e)await this.requestToPromise(t.delete(r))}}))}async delete(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)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 V("INTERNAL_ERROR",`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);const r=t.objectStore(this.collection);for(const t of e)if("put"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e){const e=t[this.keyPath];if(void 0!==e){K(await this.requestToPromise(r.get(e)),t)}await this.requestToPromise(r.put(t))}}else if("add"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(r.add(t))}else{const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(r.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",r){return this.withTx("readonly",(async s=>{const a="forward"===t?"next":"prev",i=s.openCursor(Z(r),a);return new Promise(((t,r)=>{let s=null;i.onsuccess=async a=>{const i=a.target.result;if(!i)return t(s);try{const{value:r,done:a,offset:n}=await e(i.value,i.key,i);s=r,a?t(s):n&&n>0?i.advance(n):i.continue()}catch(e){r(e)}},i.onerror=()=>r(this.mapError(i.error))}))}))}mapError(e){if(e instanceof V)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new V("INTERNAL_ERROR","Storage quota exceeded"):new V("VersionError"===r?"CONFLICT":"InvalidStateError"===r||"TransactionInactiveError"===r?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const r=await this.connectionManager.getConnection();return new Promise((async(s,a)=>{const i=r.transaction(this.collection,e),n=i.objectStore(this.collection);let o,c;i.oncomplete=()=>{c?a(c):s(o)},i.onerror=()=>a(this.mapError(i.error)),i.onabort=()=>a(this.mapError(i.error));try{const e=t(n,i);o=e instanceof Promise?await e:e}catch(e){c=e;try{i.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}},te=new Map,re=e=>{let t=te.get(e.database);t||(t=new X({retry:!0,throws:!0}),te.set(e.database,t));try{const{value:r,error:s}=t.doSync((()=>new Q(e)));if(s)throw new V("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,s);return new ee(r,e.collection,e.keyPath)}catch(e){if(e instanceof V)throw e;throw new V("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}};u(m()),u(m()),u(f()),u(z()),u(z());var se=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ae(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(ie).join("/"):"/"+e.split(".").map(ie).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(ne)}function ie(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ne(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var oe=new Map;function ce(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new se(`Invalid path - parent not found at ${e}`);if(Array.isArray(r)){let t="-"===e?r.length:parseInt(e);if(isNaN(t)||t<0||t>r.length)throw new se(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new se(`Property ${e} not found`);r=r[e]}}return r}function he(e,t){let r=oe.get(t)||ae(t);if(oe.set(t,r),0===r.length)return e;let s=ce(e,r.slice(0,-1)),a=r[r.length-1];if(Array.isArray(s)){let e=parseInt(a);if(isNaN(e)||e<0||e>=s.length)throw new se(`Invalid array index: ${a}`);return s[e]}return s[a]}function le(e,t,r){let s=oe.get(t)||ae(t);oe.set(t,s);let a=ce(e,s.slice(0,-1)),i=s[s.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter((e=>e!==r))):a[i]===r&&delete a[i],e}function de(e,t,r){let s=oe.get(t)||ae(t);if(oe.set(t,s),0===s.length)return r;let a=s.slice(0,-1),i=s[s.length-1],n=ce(e,a);if(Array.isArray(n))if("-"===i)n.push(r);else{let e=parseInt(i);if(e<0||e>n.length)throw new se(`Invalid array index: ${i}`);n.splice(e,0,r)}else n[i]=r;return e}function ue(e,t){let r=oe.get(t)||ae(t);if(oe.set(t,r),0===r.length)return;let s=ce(e,r.slice(0,-1)),a=r[r.length-1];if(Array.isArray(s)){let e=parseInt(a);s.splice(e,1)}else delete s[a];return e}function pe(e,t){let r=[];switch(e.type){case"addField":r.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":r.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach((([e,s])=>{"object"!=typeof s||null===s||Array.isArray(s),r.push({op:"replace",path:`${t}/${e}`,value:s})}));break}case"deprecateField":r.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||r.push({op:"add",path:"/indexes",value:[]}),r.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/indexes/${s}`});break}case"modifyIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`/indexes/${s}/${e}`,value:t})}));break}case"addConstraint":t.constraints||r.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach((e=>{r.push({op:"add",path:"/constraints/-",value:e})})):r.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let s=t.constraints?.findIndex((t=>Array.isArray(t)?t.some((t=>t.name===e.name)):t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/constraints/${s}`});break}case"modifyConstraint":{let s=function(e,t){if(!e.constraints)return null;for(let r=0;r<e.constraints.length;r++){let s=e.constraints[r];if(s.name===t)return`/constraints/${r}`;if(me(s)){let e=fe(s.rules,t);if(e)return`/constraints/${r}${e}`}}return null}(t,e.name);s&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`${s}/${e}`,value:t})}));break}}return r}function me(e){return e&&"operator"in e&&"rules"in e}function fe(e,t){for(let r=0;r<e.length;r++){let s=e[r];if("name"in s&&s.name===t)return`/rules/${r}`;if(me(s)){let e=fe(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var ye=new Map;function ge(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function we(e,t){let r=e=>({issues:e}),s=(e,t,r,s)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:r}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:r}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:r}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:r}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:r}];case"enum":return s?.values?s.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(s.values)}, got ${e}`,path:r}]:[{message:"Enum type requires 'values' definition",path:r}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:r}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:r}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];default:return[{message:`Unknown type '${t}'`,path:r}]}};function a(e,t,r,s,i){let n=[],o=e.rules.map(((e,o)=>{let c=[...s,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(i.has(h))return!0;i.add(h);let s=a(e,t,r,c,i);return n.push(...s),i.delete(h),0===s.length}{let s=r[e.predicate];if(!s)return n.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let a=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(ye.has(a)){let t=ye.get(a);return t||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ge(e.parameters)}`,path:c}),t}let i=s({data:t,field:e.field,arguments:e.parameters});return ye.set(a,i),i||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ge(e.parameters)}`,path:c}),i}}));return(()=>{switch(e.operator){case"and":return o.every((e=>e));case"or":return o.some((e=>e));case"not":return!o.every((e=>e));case"nor":return!o.some((e=>e));case"xor":return 1===o.filter((e=>e)).length}})()||n.push({message:`Constraint group '${e.name}' failed`,path:s}),n}function i(e,t,r,n,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let i=n.length>0?e[n[n.length-1]]:e;return h.push(...s(i,t.type,n,{values:t.values})),t.constraints&&t.constraints.forEach(((e,t)=>{if("rules"in e)h.push(...a(e,{value:i},r,[...n,`constraints[${t}]`],c));else{let s=r[e.predicate];s?s({data:{value:i},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ge(e.parameters)}`,path:[...n,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...n,`constraints[${t}]`]})}})),h}let l={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let r=t.fields,s=r.find((e=>!e.when));s&&Object.assign(l,s.fields);let a=r.find((t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value));if(a)Object.assign(l,a.fields);else if(!s)return h.push({message:"No matching field set found for discriminated schema",path:n}),h}else l=t.fields;else l=t.fields;let d=new Set(Object.values(l).map((e=>e.name)));Object.entries(l).forEach((([t,l])=>{let d=[...n,l.name],u=Object.hasOwnProperty.call(e,l.name)?e[l.name]:void 0!==l.default?l.default:void 0;l.required&&null==u&&h.push({message:`Field '${l.name}' is required`,path:d});let p=l.schema||l.nestedSchema;if("object"===l.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=u&&"object"==typeof u&&!Array.isArray(u)?u:{};h.push(...i(t,e,r,d,o,c)),p.constraints?.forEach(((e,s)=>{if("rules"in e)h.push(...a(e,t,r,[...d,`constraints[${s}]`],c));else{let a=r[e.predicate];a?a({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${ge(e.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:d})}if("union"===l.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach(((s,n)=>{let h=o[s.id];if(h)if(c.has(s.id))t.push({message:`Circular reference detected at '${s.id}'`,path:[...d,n.toString()]});else{c.add(s.id);let n=u&&"object"==typeof u&&!Array.isArray(u)?u:{},l=i(n,h,r,d,o,new Set(c));0===l.length&&void 0!==u?(e=!0,s.constraints?.forEach(((s,i)=>{if("rules"in s){let o=a(s,n,r,[...d,`constraints[${i}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let a=r[s.predicate];a&&!a({data:n,field:void 0,arguments:s.parameters})&&(e=!1,t.push({message:s.errorMessage||`Constraint '${s.name}' failed`,path:[...d,`constraints[${i}]`]}))}}))):void 0===u&&t.push(...l.filter((e=>e.message.includes("is required")))),c.delete(s.id)}else t.push({message:`Nested schema '${s.id}' not found`,path:[...d,n.toString()]})})),e||void 0===u?void 0===u&&h.push(...t):(h.push({message:"Value does not match any union schema",path:d}),h.push(...t))}void 0!==u&&(h.push(...s(u,l.type,d,{values:l.values})),("array"===l.type||"set"===l.type)&&Array.isArray(u)&&(l.constraints?.forEach(((e,t)=>{let s=r[e.predicate];s&&!s({data:{[l.name]:u},field:l.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${l.name}'`,path:[...d,`constraints[${t}]`]})})),l.itemsType&&u.forEach(((e,t)=>h.push(...s(e,l.itemsType,[...d,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?u.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),h.push(...i(e,o[p.id],r,[...d,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:d}))),l.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...a(t,e,r,[...d,`constraints[${s}]`],c));else{let a=r[t.predicate];a?a({data:e,field:l.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${l.name}' with params ${ge(t.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...n,t]});return t.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...a(t,e,r,[...n,`constraints[${s}]`],c));else{let a=r[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${ge(t.parameters)}`,path:[...n,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...n,`constraints[${s}]`]})}})),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if("object"!=typeof s||null===s)return r([{message:"Input must be an object",path:[]}]);let a=s,n=i(a,e,t,[],e.nestedSchemas||{});return n.length>0?r(n):(e=>({value:e}))(a)},types:{input:{},output:{}}}}}var be=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},ve=e=>({value:e}),$e=e=>({issues:e}),_e=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],ke=(e,t)=>{let r=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&r.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Ee=(e,t)=>{let r=["and","or","not","nor","xor"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Se=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Ie=(e,t,r)=>{let s=[],a=["type","predicate","field","parameters","name","description","errorMessage"],i=e;return["predicate","name"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(..._e(e.name,`${r}.name`)),s.push(..._e(e.predicate,`${r}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&s.push({message:"Field must be a string",path:[`${r}.field`]}),void 0!==e.parameters&&s.push(...(e.parameters,[])),s.push(..._e(e.description,`${r}.description`,!1)),s.push(..._e(e.errorMessage,`${r}.errorMessage`,!1)),s},Oe=(e,t,r)=>{let s=[],a=["name","operator","rules"],i=a,n=e;return a.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(n).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(..._e(e.name,`${r}.name`)),s.push(...Ee(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,a)=>{"rules"in e?s.push(...Oe(e,t,`${r}.rules[${a}]`)):s.push(...Ie(e,0,`${r}.rules[${a}]`))})):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},Ae=(e,t,r)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[r]}];let s=[];return e.forEach(((e,a)=>{"rules"in e?s.push(...Oe(e,t,`${r}[${a}]`)):s.push(...Ie(e,0,`${r}[${a}]`))})),s},Ne=(e,t)=>{let r=[],s=["operator","field","value","conditions"],a=e;return["operator","field"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Ee(e.operator,`${t}.operator`)),r.push(..._e(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,s)=>r.push(...Ne(e,`${t}.conditions[${s}]`)))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},xe=(e,t)=>{let r=[],s=["fields","type","unique","partial","description","order","name"],a=e;return["fields","type","name"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`)),r.push(...((e,t)=>{let r=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every((e=>"string"==typeof e)))&&r.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),r.push(...Se(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...Ne(e.partial,`${t}.partial`)),r.push(..._e(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&r.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),r},je=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let r=[];return e.forEach(((e,s)=>r.push(...xe(e,`${t}[${s}]`)))),r},Ce=(e,t,r,s,a)=>{let i=[];return void 0===e?[]:("union"===r&&Array.isArray(e)?(0===e.length&&i.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach(((e,r)=>{let a=`${t}[${r}]`;i.push(..._e(e.id,`${a}.id`)),s.includes(e.id)||i.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${a}.id`]}),e.constraints&&i.push(...Ae(e.constraints,"dynamic",`${a}.constraints`)),e.indexes&&i.push(...je(e.indexes,`${a}.indexes`))}))):"object"!==r&&("array"!==r||"object"!==a)||Array.isArray(e)?i.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(i.push(..._e(e.id,`${t}.id`)),s.includes(e.id)||i.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&i.push(...Ae(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&i.push(...je(e.indexes,`${t}.indexes`))),i)},Te=(e,t,r)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[r]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[r]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[r]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[r]}];break;case"enum":if(!Array.isArray(e)||!e.every((e=>"string"==typeof e||"number"==typeof e)))return[{message:"Default must be an array of strings or numbers",path:[r]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[r]}];break;case"union":case"dynamic":return[]}return[]},Me=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],Re=(e,t,r)=>{let s=[],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],i=e;if(["name","type"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(..._e(e.name,`${t}.name`)),s.push(...ke(e.type,`${t}.type`)),s.push(...Se(e.required,`${t}.required`,!1)),e.constraints&&s.push(...Ae(e.constraints,e.type,`${t}.constraints`)),s.push(...Te(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every((e=>"string"==typeof e||"number"==typeof e)))&&s.push({message:"Values must be a non-empty array of strings or numbers",path:[`${t}.values`]}):s.push({message:"Values is only valid for 'enum' type",path:[`${t}.values`]})),void 0!==e.schema&&s.push(...Ce(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ke(e.itemsType,`${t}.itemsType`)),e.nestedSchema){s.push({message:"nestedSchema is deprecated; use schema instead",path:[`${t}.nestedSchema`]});let a=["id"],i=["id","constraints","indexes"],n=e.nestedSchema;a.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})})),Object.keys(n).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})})),s.push(..._e(e.nestedSchema.id,`${t}.nestedSchema.id`)),r.includes(e.nestedSchema.id)||s.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&s.push(...Ae(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...je(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(...Se(e.deprecated,`${t}.deprecated`,!1)),e.reference){s.push({message:"reference is deprecated",path:[`${t}.reference`]});let r=["schema","field"],a=["schema","field"],i=e.reference;r.forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})})),s.push(..._e(e.reference.schema,`${t}.reference.schema`)),s.push(..._e(e.reference.field,`${t}.reference.field`))}return s.push(..._e(e.description,`${t}.description`,!1)),s.push(...Se(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...Me(e.hint,`${t}.hint`)),s},De=(e,t,r)=>{let s=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let a=["name","type","default","schema","itemsType","constraints","description","metadata"],i=e;["name","type"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(..._e(e.name,`${t}.name`)),s.push(...ke(e.type,`${t}.type`)),s.push(...Te(e.default,e.type,`${t}.default`)),e.schema&&s.push(...Ce(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...ke(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...Ae(e.constraints,e.type,`${t}.constraints`)),s.push(..._e(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let a=["name","description","concrete","fields","indexes","constraints","metadata"],i=e;["name"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(..._e(e.name,`${t}.name`)),s.push(...Se(i.concrete,`${t}.concrete`,!1)),i.concrete&&Array.isArray(i.fields)&&s.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(i.fields)?(0===i.fields.length&&s.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),i.fields.forEach(((e,a)=>{let i=`${t}.fields[${a}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?s.push({message:"Fields must be a non-empty object",path:[`${i}.fields`]}):Object.entries(t).forEach((([e,t])=>{s.push(...Re(t,`${i}.fields.${e}`,r))})),void 0!==e.when&&("object"!=typeof e.when||null===e.when?s.push({message:"When must be an object",path:[`${i}.when`]}):s.push(..._e(e.when.field,`${i}.when.field`)))}else s.push({message:"Each variant must have a 'fields' property",path:[i]})}))):void 0!==i.fields&&("object"!=typeof i.fields||null===i.fields?s.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(i.fields).forEach((([e,a])=>{s.push(...Re(a,`${t}.fields.${e}`,r))}))),s.push(..._e(e.description,`${t}.description`,!1)),e.indexes&&s.push(...je(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...Ae(i.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return s},Pe=(e,t)=>{let r=[];switch(e.type||r.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let s=["type","id","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addField":{let s=["type","id","definition"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),r.push(...Re(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let s=["type","id"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`));break}case"modifyField":{let s=["type","id","changes","nestedSchemaChanges"],a=e;if(["type","id","changes"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]}),e.nestedSchemaChanges){let s=["id","constraints","indexes"],a=e.nestedSchemaChanges;Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})})),r.push(..._e(a.id,`${t}.nestedSchemaChanges.id`,!1)),a.constraints&&r.push(...Ae(a.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),a.indexes&&r.push(...je(a.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let s=["type","definition"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...xe(e.definition,`${t}.definition`));break}case"removeIndex":{let s=["type","name"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`));break}case"modifyIndex":{let s=["type","name","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let s=["type","constraint"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"rules"in e.constraint?r.push(...Oe(e.constraint,"dynamic",`${t}.constraint`)):r.push(...Ie(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let s=["type","name"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`));break}case"modifyConstraint":{let s=["type","name","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addNestedSchema":{let s=["type","id","definition"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),r.push(...De(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let s=["type","id"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`));break}case"modifyNestedSchema":{let s=["type","id","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:r.push({message:"Unknown schema change type",path:[`${t}.type`]})}return r},qe=(e,t)=>{let r=[],s=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...s,"rollback","dependencies"],i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(..._e(e.id,`${t}.id`)),r.push(..._e(e.schemaVersion,`${t}.schemaVersion`)),r.push(..._e(e.description,`${t}.description`));let n=["pending","applied","failed"];return n.includes(e.status)||r.push({message:`Status must be one of ${n.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach(((e,s)=>{r.push(...Pe(e,`${t}.changes[${s}]`))})):r.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach(((e,s)=>r.push(...Pe(e,`${t}.rollback[${s}]`)))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(..._e(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?r.push(...((e,t)=>{let r=[],s=["forward","backward"],a=s,i=e;return s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"function"!=typeof e.forward&&r.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&r.push({message:"Backward must be a function",path:[`${t}.backward`]}),r})(e.transform,`${t}.transform`)):r.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),r.push(..._e(e.createdAt,`${t}.createdAt`)),r.push(..._e(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),r},Fe={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Schema must be an object",path:[]}]);let t=e,r=[],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],a=t;if(["name","version","fields"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[e]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[e]})})),r.push(..._e(t.name,"name")),r.push(..._e(t.version,"version")),"object"!=typeof t.fields||null===t.fields)r.push({message:"Fields must be a non-empty object",path:["fields"]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach((([t,s])=>{r.push(...Re(s,`fields.${t}`,e))}))}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)r.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach((([t,s])=>r.push(...De(s,`nestedSchemas.${t}`,e))))}return r.push(..._e(t.description,"description",!1)),t.indexes&&r.push(...je(t.indexes,"indexes")),t.constraints&&r.push(...Ae(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&r.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach(((e,t)=>r.push(...qe(e,`migrations[${t}]`)))):r.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&r.push({message:"Mock must be a function",path:["mock"]}),t.hint&&r.push(...Me(t.hint,"hint")),r.length>0?$e(r):ve(t)},types:{input:{},output:{}}},Be={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return $e([{message:"Migration must be an object",path:[]}]);let t=e,r=qe(t,"");return r.length>0?$e(r):ve(t)},types:{input:{},output:{}}},ze={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return $e([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach(((e,t)=>r.push(...Pe(e,`[${t}]`)))),r.length>0?$e(r):ve(t)},types:{input:[],output:[]}};function Ue(e){try{return!Fe.validate(e).issues}catch(e){throw new be("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function Le(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Ve(e,t,r){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,r=new Set,s=new Set,a=new Set;for(let i of e)switch(i.type){case"addField":if(r.has(i.id))throw new Error(`Cannot add previously removed field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot add already modified field: ${i.id}`);if(a.has(i.id))throw new Error(`Cannot add deprecated field: ${i.id}`);s.add(i.id);break;case"removeField":if(s.has(i.id))throw new Error(`Cannot remove newly added field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot remove modified field: ${i.id}`);if(a.has(i.id))throw new Error(`Cannot remove field that is being deprecated: ${i.id}`);r.add(i.id);break;case"modifyField":if(r.has(i.id))throw new Error(`Cannot modify removed field: ${i.id}`);if(s.has(i.id))throw new Error(`Cannot modify newly added field: ${i.id}`);if(a.has(i.id))throw new Error(`Cannot modify field that is being deprecated: ${i.id}`);t.add(i.id);break;case"deprecateField":if(r.has(i.id))throw new Error(`Cannot deprecate removed field: ${i.id}`);if(s.has(i.id))throw new Error(`Cannot deprecate newly added field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot deprecate modified field: ${i.id}`);a.add(i.id)}})(t),function(e){let t=new Set,r=new Set,s=new Set;for(let a of e)switch(a.type){case"addConstraint":let e=a.constraint.name;if(r.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);s.add(e);break;case"removeConstraint":if(s.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(t.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);r.add(a.name);break;case"modifyConstraint":if(r.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(s.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);t.add(a.name)}}(t);let s=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new 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)}}(e),a="patch";for(let e of t){let t=Le(e);if("major"===t){a="major";break}"minor"===t&&"patch"===a&&(a="minor")}switch(a){case"major":return`${s.major+1}.0.0`;case"minor":return`${s.major}.${s.minor+1}.0`;case"patch":return`${s.major}.${s.minor}.${s.patch+1}`}}function He(e,t){let r=e=>e.split(".").map((e=>parseInt(e,10)||0)),[s,a,i]=r(e),[n,o,c]=r(t);return s-n||a-o||i-c}var Je,Ke=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},We=((Je=We||{}).INVALID_SCHEMA="INVALID_SCHEMA",Je.INVALID_MIGRATION="INVALID_MIGRATION",Je.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Je.TIMEOUT="TIMEOUT",Je.MEMORY_LIMIT="MEMORY_LIMIT",Je.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Je.TRANSFORM_ERROR="TRANSFORM_ERROR",Je.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Je.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Je.STREAM_ERROR="STREAM_ERROR",Je.ROLLBACK_ERROR="ROLLBACK_ERROR",Je.MISSING_TRANSFORM="MISSING_TRANSFORM",Je),Ye=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!Ue(e))throw new Ke("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!Be.validate(e).issues}catch(e){throw new be("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new Ke("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>He(e.schemaVersion,t.schemaVersion)))}r&&(this.history=r.sort(((e,t)=>He(e.version,t.version))))}catch(e){throw e instanceof Ke?e:new Ke("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new Ke("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new Ke("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!ze.validate(e).issues}catch(e){throw new be("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new Ke("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,r,s){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},i=this.getRelevantMigrations(r,s);return{newSchema:i.reduce(((e,t)=>{let s="forward"===r?t.changes:t.rollback||[];return this.applySchemaChanges(e,s,t.id)}),a),dataPreview:await e.processMigrationList(t,r,i)}}catch(e){throw e instanceof Ke?e:new Ke("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter((r=>{let s="forward"===e?"pending":"applied",a=!t||He(r.schemaVersion,t)>=0;return r.status===s&&a})).sort(((t,r)=>"forward"===e?t.id.localeCompare(r.id):r.id.localeCompare(t.id)))}applySchemaChanges(e,t,r){try{let s=Ve(e.version,t);return t.map((t=>{try{return pe(t,e)}catch(e){throw new Ke("Invalid schema change","INVALID_SCHEMA",r,e)}})).reduce(((e,t)=>{try{return function(e,t){let r=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":r=de(r,e.path,e.value);break;case"remove":r=ue(r,e.path);break;case"removeValue":r=le(r,e.path,e.value);break;case"replace":r=de(ue(r,e.path),e.path,e.value);break;case"copy":{let t=he(r,e.from);r=de(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=he(r,e.from);r=de(r,e.path,t),r=ue(r,e.from);break}case"test":{let t=he(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new se("Test operation failed");break}default:throw new se(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof se&&(t.operation=e),t}return r}(e,t)}catch(e){throw new Ke("Failed to apply patch","INVALID_SCHEMA",r,e)}}),{...e,version:s})}catch(e){throw e instanceof Ke?e:new Ke("Schema update failed","INVALID_SCHEMA",r,e)}}async prepareMigration(){let e=this.migrations.filter((e=>"pending"===e.status));return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");let r=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let s=await e.processMigrationList(t,"forward",r);return this.markMigrationsApplied(r),s}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 Ke("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 Ke("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter((e=>"applied"===e.status)).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,r){if(this.isProcessing)throw new Ke("Concurrent operation","CONCURRENT_OPERATION");try{let s=this.history.findIndex((e=>e.version===t));if(-1===s)throw new Error(`Version ${t} not found in history`);let a=this.migrations.filter((e=>e.schemaVersion===t&&"applied"===e.status)).sort(((e,t)=>t.id.localeCompare(e.id))),i=this.history.length-s;if(i<0)return r;for(let e=0;e<i;e++)this.transformSchema("backward");let n=await e.processMigrationList(r,"backward",a);return this.migrations=this.migrations.map((e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e)),n}finally{this.isProcessing=!1}}static async processMigrationList(e,t,r){return(await Promise.all(r.map((async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Ke(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}})))).filter((e=>!!e.transform)).reduce(((e,{migration:t,transform:r})=>e.pipeThrough(new TransformStream({async transform(e,s){try{let t=await r(e);s.enqueue(t)}catch(e){s.error(new Ke(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}}))),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?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 r=await fetch(e);if(!r.ok)throw new Ke(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await r.text();if(typeof window<"u"){let e=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console:console};return r(s,a,e),a.module.exports[t]}}catch(t){throw new Ke(`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 Ke(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter((e=>"pending"===e.status)).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 Ke?e:new Ke("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=r.Buffer);var Ge=u(f()),Xe=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let r=-1;const s=a=>{if(a<=r)throw new Error("next() called multiple times");r=a;const i=this.middlewares[a];if(a===this.middlewares.length)return t();try{return i(e,(()=>s(a+1)))}catch(e){return Promise.reject(e)}};return s(0)}wrap(e,t){const r=this;return new Proxy(e,{get(e,s,a){const i=Reflect.get(e,s,a);return"function"==typeof i?function(...a){const n={...t,operation:s.toString(),args:a};return r.execute(n,(()=>i.apply(e,a)))}:i}})}},Qe=async(e,t)=>{const r=Date.now();try{const s=await t();return Ze(e,r,s,null),s}catch(t){throw Ze(e,r,void 0,t),t}};function Ze(e,t,r,s){if(!e.eventBus)return;const a=Date.now()-t;e.eventBus.emit({name:"telemetry",payload:{type:"telemetry",method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:a},source:{level:e.documentId?"document":e.collection?"collection":"database",collection:e.collection,document:e.documentId},result:s?void 0:{type:Array.isArray(r)?"array":typeof r,size:Array.isArray(r)?r.length:void 0},error:s?{message:s.message,name:s.name,stack:s.stack}:null}}})}var{match:et}=(0,Ge.createMatcher)({});async function tt(e){const{collection:t,initial:r,validator:a,store:i,bus:n,lockManager:o}=e,[c,h]=J(r),{value:l,issues:d}=a?await a["~standard"].validate(c):{value:r,issues:void 0};if(d)throw console.warn({issues:d}),new V("INVALID_DATA",`Invalid data for ${t}`);const u={current:Object.assign(l,h),deleted:!1};void 0===u.current.$id&&(u.current=Object.assign(u.current,{$id:s.v7(),$created:(new Date).toJSON(),$version:1}));const p={save:async e=>{const r=await o.acquire();try{const{$id:r,$version:s}=u.current;if(!r)throw new Error("Document ID missing.");const a=await i.getById(r);if(a&&a.$version!==s)throw new V("CONFLICT",`Version mismatch on ${t}/${r}`);return u.current.$version=(s||0)+1,u.current.$updated=(new Date).toJSON(),e?await e.addOp(i,"put",u.current):await i.put(u.current),n.emit({name:"document:write",payload:{type:"document:write",data:u.current,timestamp:Date.now()}}),!0}finally{r()}},update:async(e,r)=>{const[s,i]=J(Object.assign({},u.current,e)),{value:o,issues:c}=a?await a["~standard"].validate(s):{value:s,issues:void 0};if(c)throw new V("INVALID_DATA",`Invalid update for ${t}`);u.current=Object.assign(o,i);const h=await p.save(r);return h&&n.emit({name:"document:update",payload:{type:"document:update",data:u.current,timestamp:Date.now()}}),h},delete:async e=>{const r=await o.acquire();try{const{$id:r,$version:s}=u.current;if(!r)throw new Error("Document ID missing.");const a=await i.getById(r);if(a&&a.$version!==s)throw new V("CONFLICT",`Version mismatch on delete ${t}/${r}`);return e?await e.addOp(i,"delete",r):await i.delete(r),n.emit({name:"document:delete",payload:{type:"document:delete",data:u.current,timestamp:Date.now()}}),u.deleted=!0,!0}finally{r()}},read:async()=>{const e=u.current.$id,t=await i.getById(e);if(!t)throw new Error("Document not found.");return u.current={...t},n.emit({name:"document:read",payload:{type:"document:read",data:u.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=J(e);return t})(u.current),subscribe:n.subscribe};return new Proxy({},{get(e,t){if(["update","delete","subscribe","read","state","save"].includes(t)){const e=p[t];return(...t)=>{if(u.deleted)throw new V("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(u.deleted)throw new V("INVALID_OPERATION","Document has been deleted");return Reflect.get(u.current,t)}})}function rt(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}function st(e){return"function"==typeof e._getIDBConnection}var at=class{id;staged=[];done=!1;constructor(){this.id=s.v7()}async addOp(e,t,r){if(this.done)throw new V("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");this.staged.push({store:e,op:{type:t,data:r}})}async commit(){if(this.done)throw new V("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");if(this.done=!0,0===this.staged.length)return;const e=new Map,t=new Map;for(const{store:r,op:s}of this.staged)st(r)?(e.has(r)||e.set(r,[]),e.get(r).push(s)):(t.has(r)||t.set(r,[]),t.get(r).push(s));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){const t=Array.from(e.keys()).map((e=>e.name())),r=e.keys().next().value,s=await r._getIDBConnection();await new Promise(((r,a)=>{const i=s.transaction(t,"readwrite");i.oncomplete=()=>r(),i.onerror=()=>a(i.error??new Error("IDB transaction error")),i.onabort=()=>a(i.error??new Error("IDB transaction aborted")),(async()=>{try{for(const[t,r]of e)await t.executeInTransaction(r,i)}catch(e){try{i.abort()}catch(e){}a(e)}})()}))}async commitMemory(e){const t=[];try{for(const[r,s]of e){const e=r._snapshotMemory();t.push({store:r,snapshot:e}),await r.executeInTransaction(s,null)}}catch(e){for(const{store:e,snapshot:r}of t)try{e._rollbackMemory(r)}catch(e){}throw e}}completed(){return this.done}};function it(e,t){return e instanceof V?e:e instanceof Error?new V("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new V("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}async function nt(e,t){const r=L(),a=new Map,i=new Xe;i.use(((e=3,t=100)=>async(r,s)=>{let a=0;for(;a<e;)try{return await s()}catch(r){if(!(r instanceof V&&"TRANSIENT_ERROR"===r.type))throw r;{if(a++,a>=e)throw r;const s=t*Math.pow(2,a)+50*Math.random();await new Promise((e=>setTimeout(e,s)))}}})()),e.enableTelemetry&&i.use(Qe);const n=new Map,o=t({...e,collection:"schemas",keyPath:"name"},[]);async function c(r,s=[]){let a=n.get(r);return a||(a=t({...e,collection:r,keyPath:"$id"},s),n.set(r,a)),await a.open(),a}async function h(t){if(a.has(t))return a.get(t);const n=await o.getById(t);if(!n)throw new V("SCHEMA_NOT_FOUND",`Collection '${t}' does not exist`);const h=await c(t,n.indexes??[]),l=we(n,e.predicates||{}),d=await async function({collection:e,validator:t,bus:r,store:a,pipeline:i,validate:n}){const o=new H,c={collection:e,validator:n?t:void 0,store:a,bus:r,pipeline:i,lockManager:o,valid:!0},h={async validate(e){const r=t["~standard"].validate(e);return r instanceof Promise?await r:r},create:async(i,o)=>{const[h,l]=J(i),{value:d,issues:u}=n?await t["~standard"].validate(h):{value:h,issues:void 0};if(u)throw new V("INVALID_DATA",`Invalid data for collection '${e}'`);const p=Object.assign(d,l,{$id:s.v7(),$created:(new Date).toJSON(),$version:1});o?await o.addOp(a,"add",p):await a.add(p),r.emit({name:"document:create",payload:{type:"document:create",data:p,timestamp:Date.now()}});const m=await tt({...c,initial:p});return r.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),m},find:async t=>{let s;const i=rt(t);if(i)try{const e=t.value;s=(await a.findByIndex(i,e))[0]}catch{s=void 0}if(void 0===s&&(s=await a.cursor((async e=>e&&et(e,t)?{value:e,done:!0}:{value:null,done:!1}))??void 0),!s)return null;const n=await tt({...c,initial:s});return r.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),n},filter:async t=>{let s=[];const i=rt(t);if(i)try{const e=t.value;s=await a.findByIndex(i,e)}catch{s=[]}0===s.length&&await a.cursor((async e=>(e&&et(e,t)&&s.push(e),{value:null,done:!1})));const n=await Promise.all(s.map((e=>tt({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),n},list:async t=>{const s={total:await a.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return 0===s.total?{next:async()=>({value:[],done:!0})}:{async next(){const i="offset"===t.type?await async function(e,t){const{offset:r,limit:s}=t,a=[];let i=0,n=!1;for(;!(n||(await e((async e=>i<r?(i++,{value:e,done:!1,offset:1}):(a.push(e),i++,i>=r+s?(n=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),a.length>=s)););return a}(a.cursor.bind(a),{...t,offset:s.offset}):await async function(e,t){const{limit:r,direction:s}=t,a=[];let i=!1;for(;!i;)await e((async e=>(a.push(e),a.length>=r?(i=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),s);return a}(a.cursor.bind(a),{...t});s.offset+=s.limit,s.count+=i.length;const n=await Promise.all(i.map((e=>tt({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:n,done:s.count>=s.total}}}}},l={...i.wrap(h,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>c.valid=!1};return new Proxy(l,{get(t,r,s){const a=Reflect.get(t,r,s);return"function"==typeof a?(...s)=>{if(!c.valid&&"invalidate"!==r)throw new V("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return a.apply(t,s)}:a}})}({collection:t,bus:r,validator:l,validate:Boolean(e.validate),store:h,pipeline:i});return r.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:t},timestamp:Date.now()}}),a.set(t,d),a.get(t)}async function l(e){return await o.put(e),r.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await o.open();const d={collection:h,createCollection:async e=>{if(await o.getById(e.name))throw new V("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!Ue(e))throw new V("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await o.put(e);const t=h(e.name);return r.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await o.getById(e);if(!t)throw new V("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const s=await c(e,t.indexes??[]);return await s.clear(),n.delete(e),await o.delete(e),a.delete(e),r.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:l,migrateCollection:async(e,t,r=100)=>{const s=a.get(e);s&&(s.invalidate(),a.delete(e));const i=await o.getById(e);if(!i)throw new V("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const n=await c(e,i.indexes??[]),d=new Ye(i);await d.add(t);const u=(await d.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema,p=new Set((i.indexes??[]).map((e=>e.name))),m=u.indexes??[],f=new Set(m.map((e=>e.name))),y=m.filter((e=>!p.has(e.name))),g=(i.indexes??[]).filter((e=>!f.has(e.name)));await l(u);try{const t=function(e,t,r){let s,a=!1;return new ReadableStream({async pull(i){if(a)return void i.close();let n=0;const o=void 0!==s?{lower:s,lowerOpen:!0}:void 0;try{await t.cursor((async(e,t)=>(i.enqueue(e),s=t,n++,n>=r?{done:!0,value:e}:{done:!1,value:e})),"forward",o),n<r&&(a=!0)}catch(t){i.error(it(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,n,r),s=await d.migrate(t);await async function(e,t,r,s){const a=t.getReader();let i=[];try{for(;;){const{value:e,done:t}=await a.read();if(t)break;if(!e)continue;const{$version:n}=e;e.$version=(n||0)+1,e.$updated=(new Date).toJSON(),i.push(e),i.length>=s&&(await r.batch([{type:"put",data:i}]),i=[])}i.length>0&&await r.batch([{type:"put",data:i}])}catch(t){throw it(t,e)}finally{a.releaseLock()}}(e,s,n,r)}catch(t){throw it(t,e)}for(const e of y)await n.createIndex(e);for(const e of g)await n.dropIndex(e.name);return await h(e)}},u=i.wrap(d,{eventBus:r}),p={...u,transaction:async e=>{const t=new at;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:r.subscribe,close:()=>{n.clear(),r.clear()},clear:async()=>{await o.clear(),await Promise.all(n.values().map((e=>e.clear())))},ensureCollection:async e=>{try{await u.createCollection(e)}catch(e){if(e instanceof V&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await p.ensureCollection(t)}};return p}var ot=u(f()),ct=class e{static dbInstances=new Map;static collectionInstances=new Map;static eventBusMap=new Map;static defaultModelName="stores";static getDatabase(t){const{database:r,enableTelemetry:s=!1,collection:a=e.defaultModelName}=t;if(!e.dbInstances.has(r)){const t=nt({database:r,enableTelemetry:s},re).then((async e=>{try{await e.createCollection({name:a,version:"1.0.0",nestedSchemas:{},fields:{store:{name:"store",type:"string",required:!0},data:{name:"data",type:"object",required:!0},version:{name:"version",type:"string",required:!0},app:{name:"app",type:"string",required:!0}}})}catch(e){if(e instanceof V&&"SCHEMA_ALREADY_EXISTS"!==e.type)throw e}return e}));e.dbInstances.set(r,t)}return e.dbInstances.get(r)}static getEventBus(t,r){const s=`${t}_store_${r}`;return e.eventBusMap.has(s)||e.eventBusMap.set(s,L({batch:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${t}:${r}:`,e),crossTab:!0,channelName:s})),e.eventBusMap.get(s)}static getCollection(t){const{database:r,collection:s=e.defaultModelName}=t,a=`${r}:${s}`;if(!e.collectionInstances.has(a)){const r=e.getDatabase(t).then((e=>e.collection(s)));e.collectionInstances.set(a,r)}return e.collectionInstances.get(a)}static async closeDatabase(t){const r=e.dbInstances.get(t);if(r){(await r).close(),e.dbInstances.delete(t);const s=[];e.collectionInstances.forEach(((e,r)=>{r.startsWith(`${t}:`)&&s.push(r)})),s.forEach((t=>e.collectionInstances.delete(t)));const a=[];e.eventBusMap.forEach(((e,r)=>{r.startsWith(`${t}_store_`)&&(e.clear(),a.push(r))})),a.forEach((t=>e.eventBusMap.delete(t)))}}static async closeAll(){const t=Array.from(e.dbInstances.keys()).map((t=>e.closeDatabase(t)));await Promise.all(t)}static getActiveDatabases(){return Array.from(e.dbInstances.keys())}};exports.IndexedDBPersistence=class{collection=null;collectionPromise;config;eventBus;initialized=!1;initializationCallbacks=[];doc=null;getStoreName(){return`_${this.config.app}_${this.config.store}_`}constructor(e){this.config=e,this.collectionPromise=ct.getCollection(this.config),this.collectionPromise.then((e=>{this.collection=e,this.initialize()})).catch((e=>{console.error(`Failed to initialize collection for store ${this.getStoreName()}:`,e)})),this.eventBus=ct.getEventBus(this.config.database,this.getStoreName())}async initialize(){try{const e=await this._get();if(e&&e.version!==this.config.version&&this.config.onUpgrade){const{state:t}=await this.config.onUpgrade({data:e.data,version:e.version,app:e.app});await this.set("migration",t)}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize and upgrade store ${this.getStoreName()}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}async getCollection(){return this.collection?this.collection:this.collectionPromise}async set(e,t){try{const r=await this.getCollection(),s=await this._read(),a={store:this.getStoreName(),data:t,version:this.config.version,app:this.config.app};let i;return s?i=await s.update(a):(this.doc=await r.create(a),i=!0),i&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.getStoreName(),instanceId:e,state:t,version:this.config.version,app:this.config.app}}),i}catch(t){return console.error(`Failed to set state for store ${this.getStoreName()} in database ${this.config.database} by instance ${e}:`,t),!1}}async _read(){if(this.doc)return this.doc;const e=await this.getCollection(),t=(new ot.QueryBuilder).where({field:"store",operator:"eq",value:this.getStoreName()}).build(),r=await e.find(t.filters);return this.doc=r,this.doc}async _get(){try{const e=await this._read();return e?e.read().then((()=>e)):null}catch(e){return console.error(`Failed to get state for store ${this.getStoreName()} in database ${this.config.database}:`,e),null}}async get(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));const e=await this._get();return e?e.data:null}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:s,state:a})=>{r===this.getStoreName()&&s!==e&&t(a)}))}async clear(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));try{const e=await this._read();return!e||!await e.delete()||(this.doc=null,!0)}catch(e){return console.error(`Failed to clear state for store ${this.getStoreName()} in database ${this.config.database}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}async close(){await ct.closeDatabase(this.config.database)}},exports.WebStoragePersistence=class{eventBus;storage;config;initialized=!1;initializationCallbacks=[];constructor(e){this.config=e,this.storage=e.session?sessionStorage:localStorage,this.eventBus=this.initializeEventBus(),this.initialize(),e.session||this.setupStorageEventListener()}async initialize(){try{const e=this.storage.getItem(this.getStoreName());if(e){const t=JSON.parse(e);if(t.version!==this.config.version&&this.config.onUpgrade){const{state:e}=await this.config.onUpgrade({data:t.state,version:t.version,app:t.app});this.set("migration",e)}}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize WebStoragePersistence for ${this.config.storageKey}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}initializeEventBus(){return(0,U.createEventBus)({async:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${this.config.storageKey}:`,e),crossTab:"undefined"==typeof process||"test"!==process.env.NODE_ENV,channelName:`storage_${this.getStoreName()}`})}getStoreName(){return`_${this.config.app}_${this.config.storageKey}_`}setupStorageEventListener(){window.addEventListener("storage",(e=>{if(e.key===this.getStoreName()&&e.newValue)try{const t=JSON.parse(e.newValue);t&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"external",state:t.state,version:t.version,app:t.app}})}catch(e){console.error("Failed to parse storage event data:",e)}}))}set(e,t){try{const r={state:structuredClone(t),version:this.config.version,app:this.config.app},s=JSON.stringify(r);return this.storage.setItem(this.getStoreName(),s),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:e,state:t,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to persist state to web storage for ${this.config.storageKey}:`,e),!1}}_get(){try{const e=this.storage.getItem(this.getStoreName());if(!e)return null;return JSON.parse(e).state}catch(e){return console.error(`Failed to retrieve state from web storage for ${this.config.storageKey}:`,e),null}}async get(){return this.initialized||await new Promise((e=>{this._onInitialized(e)})),this._get()}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:s,state:a})=>{r===this.config.storageKey&&s!==e&&t(a)}))}clear(){try{return this.storage.removeItem(this.getStoreName()),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"clear-initiator",state:null,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to clear persisted state for ${this.config.storageKey}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}};
package/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Buffer as e}from"buffer";import{v7 as t}from"uuid";var s,r,i=Object.create,a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},d=(e,t,s,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of o(t))h.call(e,i)||i===s||a(e,i,{get:()=>t[i],enumerable:!(r=n(t,i))||r.enumerable});return e},u=(e,t,s)=>(s=null!=e?i(c(e)):{},d(e&&e.__esModule?s:a(s,"default",{value:e,enumerable:!0}),e)),p=e=>d(a({},"__esModule",{value:!0}),e),m=l({"node_modules/@asaidimu/events/index.js"(e,t){var s,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(r({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],r=0,i=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{r++,i+=t,a.set(e,(a.get(e)||0)+1)},h=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-r)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const r=t.get(e);return r.add(s),d(e),()=>{r.delete(s),0===r.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:r})=>{if(e.async)return s.push({name:t,payload:r}),s.length>=e.batchSize?h():l(),void(o&&o.postMessage({name:t,payload:r}));const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(r))),o&&o.postMessage({name:t,payload:r})}catch(s){e.errorHandler({...s,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(),n.clear(),s=[],r=0,i=0,a.clear(),o&&(o.close(),o=null)}}}}}),f=l({"node_modules/@asaidimu/query/index.js"(e,t){var s,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)r(e,s,{get:t[s],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>l,createPaginator:()=>E,createProjector:()=>$,createSorter:()=>_}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))!n.call(e,c)&&c!==s&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e})(r({},"__esModule",{value:!0}),s));var c=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,s){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:s},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,s){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:s}),this}join(e,t,s){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:s,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 h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?r(t,e):function(e){return"computed"===e?.type}(t)?r(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let s of t.conditions)if(i(e,s.when))return s.then;return t.else}(e,t):t}let s=new Map([["and",(e,t)=>t.every((t=>i(e,t)))],["or",(e,t)=>t.some((t=>i(e,t)))],["not",(e,t)=>!t.every((t=>i(e,t)))],["nor",(e,t)=>!t.some((t=>i(e,t)))],["xor",(e,t)=>1===t.filter((t=>i(e,t))).length]]);function r(s,r){let i=s.arguments.map((e=>t(r,e)));if(e[s.function])return e[s.function](...i);throw new Error(`Function ${s.function} not found!`)}function i(r,i){if(function(e){return!!e&&void 0!==e.conditions}(i))return function(e,t){let{operator:r,conditions:i}=t,a=s.get(r);if(a)return a(e,i);throw new Error(`Unsupported logical operator: ${r}`)}(r,i);if(!i||!i.field)return!1;let{field:a,operator:n,value:o}=i,c=r[a],h=t(r,o),l=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)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[n]||l.get(n);if(d)return d(c,h);throw new Error(`Unsupported comparison operator: ${n}`)}return{resolve:t,evaluate:i}}function l(e){let{evaluate:t}=h(e),s=new WeakMap;function r(e,r){let i=s.get(e);i||(i=new Map,s.set(e,i));let a=JSON.stringify(r);if(i.has(a))return i.get(a);let n=t(e,r);return i.set(a,n),n}return{matcher:r,match:r}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},u=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(u(e)&&e){let s=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:s}}if((e=>"operator"in e&&"conditions"in e)(e)){let s={...e};return e.conditions&&(s.conditions=e.conditions.map((e=>p(e,t)))),s}return e}},m=async(e,t,s,r)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(s,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let i,a=e[s.relation];return s.query?.filters&&u(s.query.filters)&&(i=((e,t)=>{let s=new Map;return e.forEach((e=>{let r=e[t];s.has(r)||s.set(r,[]),s.get(r).push(e)})),s})(a,s.query.filters.field)),(await Promise.all(t.map((async e=>{let t,n=((e,t)=>{if(!e)return{};let s=p(e.filters,t);return{...e,filters:s}})(s.query,e);return t=n.filters&&u(n.filters)&&i?.has(n.filters.value)?i.get(n.filters.value)||[]:a.filter((e=>r.matcher(e,n.filters))),((e,t,s)=>{let r=s.alias||s.relation;return[{...e,[r]:t}]})(e,await[e=>n.sort?r.sorter(e,n.sort):e,e=>n.projection?r.projector(e,n.projection):e,async e=>n.pagination?await r.paginator(e,n.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),s)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,s,r)=>s.reduce((async(t,s)=>m(e,await t,s,r)),Promise.resolve(t));function y(){return{join:f}}var g=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},w=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,s){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===s?-1:1:"asc"===s?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===s?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===s?e-t:t-e;throw new g(e,t)}function v(e,t){let s=Array.from(e);return 0===t.length?s:s.sort(((e,s)=>{for(let r of t){let{field:t,direction:i}=r,a=e[t],n=s[t];try{if("asc"!==i&&"desc"!==i)throw new w(i);let e=b(a,n,i);if(0!==e)return e}catch(e){throw e instanceof g||e instanceof w?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function _(){return{sort:v}}function $(e){let{resolve:t}=h(e);function s(e,r){let i={};return r.include?.length&&function(e,t,r){for(let i of t)if("string"!=typeof i){for(let[t,a]of Object.entries(i))if(Object.prototype.hasOwnProperty.call(e,t)){let i=s(e[t],a);r[t]=i}}else{let t=i;r[t]=e[t]}}(e,r.include,i),r.exclude?.length&&function(e,t,r){0===Object.keys(r).length&&Object.assign(r,e);for(let e of t)if("string"!=typeof e)for(let[t,i]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(r,t))continue;let e=r[t];e&&"object"==typeof e?r[t]=s(e,i):delete r[t]}else delete r[e]}(e,r.exclude,i),r.computed?.length&&function(e,s,r){for(let i of s)r[i.alias]=t(e,i)}(e,r.computed,i),i}return{project:s}}async function*k(e,t,s=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:s,limit:r}=t,i=0,a=r,n=[];for await(let t of e)a<=0&&(yield n,n=[],a=r),i<s?i++:(n.push(t),a--);n.length>0&&(yield n)}(e,t):yield*async function*(e,t,s){let{cursor:r,limit:i,direction:a}=t,n=i,o=void 0===r,c=[];if("forward"===a)for await(let t of e)n<=0&&(yield c,c=[],n=i),o?(c.push(t),n--):o=s(t)===r;else{let t=[];for await(let s of e)t.push(s);for(let e=t.length-1;e>=0;e--){let a=t[e];o?(c.push(a),n--,n<=0&&(yield c,c=[],n=i)):o=s(a)===r}}c.length>0&&(yield c)}(e,t,s)}function E(){return{paginate:k}}}}),y=l({"node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,s;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?s:(t=!0,s=e.apply(this,arguments))}}}}),g=l({"node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),w=l({"node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,s){var r;return function(){if(!t)return e.apply(this,arguments);var i=this,a=arguments,n=s&&!r;return clearTimeout(r),r=setTimeout((function(){if(r=null,!n)return e.apply(i,a)}),t),n?e.apply(this,arguments):void 0}}}}),b=l({"node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function s(e){if(0===e.length)return".";let t=i(e);return t=t.reduce(a,[]),r(...t)}function r(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function i(e){if(0===e.length)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 a(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new 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:r,normalize:s,split:i,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let i of e)t=i.startsWith("/")?i:s(r(t,i));return t}}}}),v=l({"node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function s(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var r=s("EEXIST"),i=s("ENOENT"),a=s("ENOTDIR"),n=s("ENOTEMPTY"),o=s("ETIMEDOUT"),c=s("EISDIR");t.exports={EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,ETIMEDOUT:o,EISDIR:c}}}),_=l({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var s=b(),{EEXIST:r,ENOENT:i,ENOTDIR:a,ENOTEMPTY:n,EISDIR:o}=v();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){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):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[s,r]of e)0!==s&&(t+=this._countInodes(r));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[s,r]of e)0!==s&&(t=Math.max(t,this._maxInode(r)));return t}print(e=this._root.get("/")){let t="";const s=(e,r)=>{for(let[i,a]of e){if(0===i)continue;let e=a.get(0),n=e.mode.toString(8);t+=`${"\t".repeat(r)}${i}\t${n}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",s(a,r+1))}};return s(e,0),t}parse(e){let t=0;function s(e){const s=++t,r=1===e.length?"dir":"file";let[i,a,n]=e;return i=parseInt(i,8),a=a?parseInt(a):0,n=n?parseInt(n):Date.now(),new Map([[0,{mode:i,type:r,size:a,mtimeMs:n,ino:s}]])}let r=e.trim().split("\n"),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("\t"),n=s(i);if(t<=a[a.length-1].indent)for(;t<=a[a.length-1].indent;)a.pop();a.push({indent:t,node:n}),a[a.length-2].node.set(r,n)}return i}_lookup(e,t=!0){let r=this._root,a="/",n=s.split(e);for(let o=0;o<n.length;++o){let c=n[o];if(r=r.get(c),!r)throw new i(e);if(t||o<n.length-1){const e=r.get(0);if("symlink"===e.type){let t=s.resolve(a,e.target);r=this._lookup(t)}a=a?s.join(a,c):c}}return r}mkdir(e,{mode:t}){if("/"===e)throw new r;let i=this._lookup(s.dirname(e)),a=s.basename(e);if(i.has(a))throw new r;let n=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};n.set(0,o),i.set(a,n)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;if(t.size>1)throw new n;let r=this._lookup(s.dirname(e)),i=s.basename(e);r.delete(i)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new a;return[...t.keys()].filter((e=>"string"==typeof e))}writeStat(e,t,{mode:r}){let i,a;try{a=this.stat(e)}catch(e){}if(void 0!==a){if("dir"===a.type)throw new o;null==r&&(r=a.mode),i=a.ino}null==r&&(r=438),null==i&&(i=this.autoinc());let n=this._lookup(s.dirname(e)),c=s.basename(e),h={mode:r,type:"file",size:t,mtimeMs:Date.now(),ino:i},l=new Map;return l.set(0,h),n.set(c,l),h}unlink(e){let t=this._lookup(s.dirname(e)),r=s.basename(e);t.delete(r)}rename(e,t){let r=s.basename(t),i=this._lookup(e);this._lookup(s.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);null===i&&(i=e.mode),r=e.ino}catch(e){}null==i&&(i=40960),null==r&&(r=this.autoinc());let a=this._lookup(s.dirname(t)),n=s.basename(t),o={mode:i,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:r},c=new Map;return c.set(0,o),a.set(n,c),o}_du(e){let t=0;for(const[s,r]of e.entries())t+=0===s?r.size:this._du(r);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),$={};function k(){return r||(r=new s),r}function E(e,t=k()){let s;return t._withIDBStore("readwrite",(t=>{s=t.get(e)})).then((()=>s.result))}function S(e,t,s=k()){return s._withIDBStore("readwrite",(s=>{s.put(t,e)}))}function I(e,t,s=k()){return s._withIDBStore("readwrite",(s=>{const r=s.get(e);r.onsuccess=()=>{s.put(t(r.result),e)}}))}function O(e,t=k()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function A(e=k()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function N(e=k()){const 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 x(e=k()){return e._close()}((e,t)=>{for(var s in t)a(e,s,{get:t[s],enumerable:!0})})($,{Store:()=>s,clear:()=>A,close:()=>x,del:()=>O,get:()=>E,keys:()=>N,set:()=>S,update:()=>I});var j,C,T=(j={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){s=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise(((e,t)=>{const s=indexedDB.open(this._dbName);s.onerror=()=>t(s.error),s.onsuccess=()=>e(s.result),s.onupgradeneeded=()=>{s.result.createObjectStore(this._storeName)}})))}_withIDBStore(e,t){return this._init(),this._dbp.then((s=>new Promise(((r,i)=>{const a=s.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}))}}}},function(){return j&&(C=(0,j[o(j)[0]])(j=0)),C}),M=l({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var s=(T(),p($));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new s.Store(this._database,this._storename)}saveSuperblock(e){return s.set("!root",e,this._store)}loadSuperblock(){return s.get("!root",this._store)}readFile(e){return s.get(e,this._store)}writeFile(e,t){return s.set(e,t,this._store)}unlink(e){return s.del(e,this._store)}wipe(){return s.clear(this._store)}close(){return s.close(this._store)}}}}),R=l({"node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(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){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),D=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var s=(T(),p($)),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 s.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await s.update("lock",(s=>{const r=Date.now()+e;return t=s&&s.holder===this._id,this._lock=t?{holder:this._id,expires:r}:s,this._lock}),this._store),t}async acquire({ttl:e=5e3}={}){let t,r,i;if(await s.update("lock",(s=>{const a=Date.now(),n=a+e;return r=s&&s.expires<a,t=void 0===s||r,i=s&&s.holder===this._id,this._lock=t?{holder:this._id,expires:n}:s,this._lock}),this._store),i)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:s}={}){for(;t--;){if(await this.acquire({ttl:s}))return!0;await r(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,r,i;if(await s.update("lock",(s=>(t=e||s&&s.holder===this._id,r=void 0===s,i=s&&s.holder!==this._id,this._lock=t?void 0:s,this._lock)),this._store),await s.close(this._store),!t&&!e){if(r)throw new Error("Mutex double-freed");if(i)throw new Error("Mutex lost ownership")}return t}}}}),P=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(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,s)=>{const r=new AbortController;setTimeout((()=>{r.abort(),s(new 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))}}}}),q=l({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:s,decode:r}=g(),i=w(),a=_(),{ENOENT:n,ENOTEMPTY:o,ETIMEDOUT:c}=v(),h=M(),l=R(),d=D(),u=P(),p=b();t.exports=class{constructor(){this.saveSuperblock=i((()=>{this.flush()}),500)}async init(e,{wipe:t,url:s,urlauto:r,fileDbName:i=e,db:n=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=n||new h(i,o),this._mutex=navigator.locks?new u(e):new d(c,p),this._cache=new a(e),this._opts={wipe:t,url:s},this._needsWipe=!!t,s&&(this._http=new l(s),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();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const 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,s){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(e){}}return this._cache.writeStat(e,t,s)}async readFile(e,t){const s="string"==typeof t?t:t&&t.encoding;if(s&&"utf8"!==s)throw new 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(;"symlink"===t.type;)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()),"utf8"===s?i=r(i):i.toString=()=>r(i)),!a)throw new n(e);return i}async writeFile(e,t,r){const{mode:i,encoding:a="utf8"}=r;if("string"==typeof t){if("utf8"!==a)throw new Error('Only "utf8" encoding is supported in writeFile');t=s(t)}const n=await this._cache.writeStat(e,t.byteLength,{mode:i});await this._idb.writeFile(n.ino,t)}async unlink(e,t){const s=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==s.type&&await this._idb.unlink(s.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:s=511}=t;this._cache.mkdir(e,{mode:s})}rmdir(e,t){if("/"===e)throw new o;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 s=await this._http.sizeFile(e);await this._writeStat(e,s,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),F=l({"node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(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"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),B=l({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var s=q(),r=F(),i=b();function a(e,t,...s){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=i.normalize(e),t,...s]}function n(e,t,s,...r){return void 0!==s&&"function"!=typeof s||(s={}),"string"==typeof s&&(s={encoding:s}),[e=i.normalize(e),t,s,...r]}function o(e,t,...s){return[i.normalize(e),i.normalize(t),...s]}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,n,!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,o,!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,o,!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 s,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(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,s){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),s&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(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,s){return await this._backend.writeFile(e,t,s),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){const s=await this._backend.stat(e,t);return new r(s)}async lstat(e,t){const s=await this._backend.lstat(e,t);return new r(s)}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()}}}}),z=l({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var s=y(),r=B();function i(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=s(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,s){const[r,a]=i(t,s);this.promises.readFile(e,t).then(r).catch(a)}writeFile(e,t,s,r){const[a,n]=i(s,r);this.promises.writeFile(e,t,s).then(a).catch(n)}unlink(e,t,s){const[r,a]=i(t,s);this.promises.unlink(e,t).then(r).catch(a)}readdir(e,t,s){const[r,a]=i(t,s);this.promises.readdir(e,t).then(r).catch(a)}mkdir(e,t,s){const[r,a]=i(t,s);this.promises.mkdir(e,t).then(r).catch(a)}rmdir(e,t,s){const[r,a]=i(t,s);this.promises.rmdir(e,t).then(r).catch(a)}rename(e,t,s){const[r,a]=i(s);this.promises.rename(e,t).then(r).catch(a)}stat(e,t,s){const[r,a]=i(t,s);this.promises.stat(e).then(r).catch(a)}lstat(e,t,s){const[r,a]=i(t,s);this.promises.lstat(e).then(r).catch(a)}readlink(e,t,s){const[r,a]=i(t,s);this.promises.readlink(e).then(r).catch(a)}symlink(e,t,s){const[r,a]=i(s);this.promises.symlink(e,t).then(r).catch(a)}backFile(e,t,s){const[r,a]=i(t,s);this.promises.backFile(e,t).then(r).catch(a)}du(e,t){const[s,r]=i(t);this.promises.du(e).then(s).catch(r)}flush(e){const[t,s]=i(e);this.promises.flush().then(t).catch(s)}}}}),U=u(m()),L=class{eventBus;storage;config;initialized=!1;initializationCallbacks=[];constructor(e){this.config=e,this.storage=e.session?sessionStorage:localStorage,this.eventBus=this.initializeEventBus(),this.initialize(),e.session||this.setupStorageEventListener()}async initialize(){try{const e=this.storage.getItem(this.getStoreName());if(e){const t=JSON.parse(e);if(t.version!==this.config.version&&this.config.onUpgrade){const{state:e}=await this.config.onUpgrade({data:t.state,version:t.version,app:t.app});this.set("migration",e)}}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize WebStoragePersistence for ${this.config.storageKey}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}initializeEventBus(){return(0,U.createEventBus)({async:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${this.config.storageKey}:`,e),crossTab:"undefined"==typeof process||"test"!==process.env.NODE_ENV,channelName:`storage_${this.getStoreName()}`})}getStoreName(){return`_${this.config.app}_${this.config.storageKey}_`}setupStorageEventListener(){window.addEventListener("storage",(e=>{if(e.key===this.getStoreName()&&e.newValue)try{const t=JSON.parse(e.newValue);t&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"external",state:t.state,version:t.version,app:t.app}})}catch(e){console.error("Failed to parse storage event data:",e)}}))}set(e,t){try{const s={state:structuredClone(t),version:this.config.version,app:this.config.app},r=JSON.stringify(s);return this.storage.setItem(this.getStoreName(),r),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:e,state:t,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to persist state to web storage for ${this.config.storageKey}:`,e),!1}}_get(){try{const e=this.storage.getItem(this.getStoreName());if(!e)return null;return JSON.parse(e).state}catch(e){return console.error(`Failed to retrieve state from web storage for ${this.config.storageKey}:`,e),null}}async get(){return this.initialized||await new Promise((e=>{this._onInitialized(e)})),this._get()}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:s,instanceId:r,state:i})=>{s===this.config.storageKey&&r!==e&&t(i)}))}clear(){try{return this.storage.removeItem(this.getStoreName()),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"clear-initiator",state:null,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to clear persisted state for ${this.config.storageKey}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}},V=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},H=class extends V{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},J=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)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const s=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await s;let r;await Promise.race([s.then((()=>clearTimeout(r))),new Promise(((s,i)=>{r=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),i(new H("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},K=class{mutex=new J({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}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{const t=await e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{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){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new 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()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const 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()}isReady(){return this._done&&null===this.promise}running(){return null!==this.promise&&!this.isReady()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}currentExecution(){return this.promise}done(){return this._done}_awaitWithTimeout(e,t,s="Operation timed out"){if(null==t)return e;let r;return Promise.race([e.then((e=>(clearTimeout(r),e))),new Promise(((e,i)=>{r=setTimeout((()=>i(new H(s))),t)}))])}},W=class{_delay;_leading;_timer;_pendingFn;_pendingResolvers=[];_leadingFired=!1;constructor(e){this._delay=e?.delay??300,this._leading=e?.leading??!1}do(e){return new Promise((t=>{this._enqueue(e,t)}))}fire(e){this._enqueue(e,void 0)}_enqueue(e,t){if(this._pendingFn=e,t&&this._pendingResolvers.push(t),this._leading&&!this._leadingFired)return this._leadingFired=!0,this._fire(),clearTimeout(this._timer),void(this._timer=setTimeout((()=>{this._leadingFired=!1,void 0!==this._pendingFn&&this._fire()}),this._delay));clearTimeout(this._timer),this._timer=setTimeout((()=>{this._leadingFired=!1,this._fire()}),this._delay)}cancel(){clearTimeout(this._timer),this._timer=void 0,this._pendingFn=void 0,this._leadingFired=!1;const e=this._pendingResolvers.splice(0);for(const t of e)t({status:"cancelled"})}async flush(){return this._pendingFn?(clearTimeout(this._timer),this._timer=void 0,this._leadingFired=!1,this._fire()):null}pending(){return void 0!==this._pendingFn}async _fire(){const e=this._pendingFn,t=this._pendingResolvers.splice(0);let s;this._pendingFn=void 0;try{s={status:"ok",value:await e()}}catch(e){s={status:"error",error:e}}for(const e of t)e(s);return s}};function Y(e){const t=e??{},{deferred:s,batchSize:r,batchDelay:i,errorHandler:a,broadcast:n,channel:o}={deferred:null!=t.batch?.size,batchSize:t.batch?.size,batchDelay:t.batch?.delay||16,errorHandler:t.errorHandler||(e=>console.error("EventBus Error:",e)),broadcast:null!=t.broadcast?.channel&&t.broadcast.channel.length>0,channel:null!=t.broadcast?.channel&&t.broadcast.channel.length>0?t.broadcast?.channel:"event-bus-channel"},c=new Map;let h=[],l=0,d=0;const u=new Map,p=()=>{if(!n)return null;if("undefined"==typeof BroadcastChannel)return console.warn("EventBus: BroadcastChannel is not supported in this environment. Cross-tab notifications are disabled."),null;const e=new BroadcastChannel(o);return e.onmessage=e=>{const{name:t,payload:s}=e.data;y(t,s)},e};let m=p();const f=(e,t)=>{l++,d+=t,u.set(e,(u.get(e)??0)+1)},y=(e,t)=>{const s=c.get(e);if(s&&0!==s.size)for(const r of Array.from(s))try{r(t)}catch(s){const r=s instanceof Error?s:Object.assign(new Error(String(s)),{cause:s}),i=Object.assign(r,{eventName:e,payload:t});a(i)}},g=()=>{const e=h;h=[];for(const{name:t,payload:s}of e){const e=performance.now();y(t,s),f(t,performance.now()-e)}},w=new W({delay:i});return{subscribe:(e,t)=>{c.has(e)||c.set(e,new Set);const s=c.get(e);return s.add(t),()=>{s.delete(t),0===s.size&&c.delete(e)}},once:(e,t)=>{let s;const r=e=>{s(),t(e)};return s=(()=>{c.has(e)||c.set(e,new Set);const t=c.get(e);return t.add(r),()=>{t.delete(r),0===t.size&&c.delete(e)}})(),s},emit:({name:e,payload:t})=>{if(s)return h.push({name:e,payload:t}),h.length>=r?(w.cancel(),void g()):(w.fire((()=>g())),void m?.postMessage({name:e,payload:t}));const i=performance.now();y(e,t),f(e,performance.now()-i),m?.postMessage({name:e,payload:t})},metrics:()=>({totalEvents:l,activeSubscriptions:Array.from(c.values()).reduce(((e,t)=>e+t.size),0),eventCounts:u,averageEmitDuration:l>0?d/l:0}),clear:()=>{c.clear(),h=[],w.cancel(),l=0,d=0,u.clear(),m?.close(),m=p()}}}var G=class extends Error{type;schema;constructor(e,t,s,r){super(t,{cause:r}),this.type=e,this.schema=s,this.name="DatabaseError"}},X=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function Q(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce(((e,[s,r])=>(s.startsWith("$")?t[s]=r:e[s]=r,e)),{}),t]}function Z(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new G("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}var ee=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new K({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const s=indexedDB.open(this.config.database);s.onerror=()=>t(new Error(`Failed to open database: ${s.error?.message}`)),s.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},s.onsuccess=()=>e(s.result)}))}async upgradeDatabase(e,t){const s=e.version+1;return e.close(),new Promise(((e,r)=>{const i=indexedDB.open(this.config.database,s);i.onerror=()=>r(new Error(`Failed to upgrade database: ${i.error?.message}`)),i.onupgradeneeded=e=>{const s=e.target.result,r=e.target.transaction;t(s,r)},i.onsuccess=()=>e(i.result)}))}async ensureStore(e,t="$id",s=[]){(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)){const i=r.createObjectStore(e,{keyPath:t});for(const e of s){const t=1===e.fields.length?e.fields[0]:e.fields;i.createIndex(e.name,t,{unique:e.unique??!1})}}}))}async createStoreIndex(e,t){await this.upgrade(((s,r)=>{const i=r.objectStore(e);if(i.indexNames.contains(t.name))return;const a=1===t.fields.length?t.fields[0]:t.fields;i.createIndex(t.name,a,{unique:t.unique??!1})}))}async dropStoreIndex(e,t){await this.upgrade(((s,r)=>{const i=r.objectStore(e);i.indexNames.contains(t)&&i.deleteIndex(t)}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new G("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){const t=await this.getConnection();this.connectionInitializer.reset();const s=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(t,e)));if(s.error)throw new G("INTERNAL_ERROR",`Database upgrade failed for ${this.config.database}`,void 0,s.error);return s.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function te(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var se=class{constructor(e,t,s="$id",r=[]){this.connectionManager=e,this.collection=t,this.keyPath=s,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 s=>{const r=s.index(e);return this.requestToPromise(r.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async s=>{const r=s.index(e);return this.requestToPromise(r.getAll(te(t)))}))}async findByIndex(e,t){return this.withTx("readonly",(async s=>{const r=s.index(e),i=IDBKeyRange.only(t);return this.requestToPromise(r.getAll(i))}))}async put(e){return this.withTx("readwrite",(async t=>{const s=e[this.keyPath];if(void 0!==s){Z(await this.requestToPromise(t.get(s)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const s=Array.isArray(e)?e:[e],r=[];for(const e of s){const s=await this.requestToPromise(t.add(e));r.push(s)}return Array.isArray(e)?r:r[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const s of e)if("put"===s.type||"add"===s.type){const e=Array.isArray(s.data)?s.data:[s.data];for(const r of e)if("put"===s.type){const e=r[this.keyPath];if(void 0!==e){Z(await this.requestToPromise(t.get(e)),r)}await this.requestToPromise(t.put(r))}else await this.requestToPromise(t.add(r))}else{const e=Array.isArray(s.data)?s.data:[s.data];for(const s of e)await this.requestToPromise(t.delete(s))}}))}async delete(e){return this.withTx("readwrite",(async t=>{const s=Array.isArray(e)?e:[e];for(const e of s)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 G("INTERNAL_ERROR",`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);const s=t.objectStore(this.collection);for(const t of e)if("put"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e){const e=t[this.keyPath];if(void 0!==e){Z(await this.requestToPromise(s.get(e)),t)}await this.requestToPromise(s.put(t))}}else if("add"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(s.add(t))}else{const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(s.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",s){return this.withTx("readonly",(async r=>{const i="forward"===t?"next":"prev",a=r.openCursor(te(s),i);return new Promise(((t,s)=>{let r=null;a.onsuccess=async i=>{const a=i.target.result;if(!a)return t(r);try{const{value:s,done:i,offset:n}=await e(a.value,a.key,a);r=s,i?t(r):n&&n>0?a.advance(n):a.continue()}catch(e){s(e)}},a.onerror=()=>s(this.mapError(a.error))}))}))}mapError(e){if(e instanceof G)return e;const t=e?.message||"Unknown IndexedDB Error",s=e?.name||"";return"QuotaExceededError"===s?new G("INTERNAL_ERROR","Storage quota exceeded"):new G("VersionError"===s?"CONFLICT":"InvalidStateError"===s||"TransactionInactiveError"===s?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const s=await this.connectionManager.getConnection();return new Promise((async(r,i)=>{const a=s.transaction(this.collection,e),n=a.objectStore(this.collection);let o,c;a.oncomplete=()=>{c?i(c):r(o)},a.onerror=()=>i(this.mapError(a.error)),a.onabort=()=>i(this.mapError(a.error));try{const e=t(n,a);o=e instanceof Promise?await e:e}catch(e){c=e;try{a.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}},re=new Map,ie=e=>{let t=re.get(e.database);t||(t=new K({retry:!0,throws:!0}),re.set(e.database,t));try{const{value:s,error:r}=t.doSync((()=>new ee(e)));if(r)throw new G("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,r);return new se(s,e.collection,e.keyPath)}catch(e){if(e instanceof G)throw e;throw new G("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}};u(m()),u(m()),u(f()),u(z()),u(z());var ae=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ne(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(oe).join("/"):"/"+e.split(".").map(oe).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(ce)}function oe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ce(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var he=new Map;function le(e,t){let s=e;for(let e of t){if(null===s||"object"!=typeof s)throw new ae(`Invalid path - parent not found at ${e}`);if(Array.isArray(s)){let t="-"===e?s.length:parseInt(e);if(isNaN(t)||t<0||t>s.length)throw new ae(`Invalid array index: ${e}`);s=s[t]}else{if(!s.hasOwnProperty(e))throw new ae(`Property ${e} not found`);s=s[e]}}return s}function de(e,t){let s=he.get(t)||ne(t);if(he.set(t,s),0===s.length)return e;let r=le(e,s.slice(0,-1)),i=s[s.length-1];if(Array.isArray(r)){let e=parseInt(i);if(isNaN(e)||e<0||e>=r.length)throw new ae(`Invalid array index: ${i}`);return r[e]}return r[i]}function ue(e,t,s){let r=he.get(t)||ne(t);he.set(t,r);let i=le(e,r.slice(0,-1)),a=r[r.length-1];return Array.isArray(i)?i.splice(0,i.length,...i.filter((e=>e!==s))):i[a]===s&&delete i[a],e}function pe(e,t,s){let r=he.get(t)||ne(t);if(he.set(t,r),0===r.length)return s;let i=r.slice(0,-1),a=r[r.length-1],n=le(e,i);if(Array.isArray(n))if("-"===a)n.push(s);else{let e=parseInt(a);if(e<0||e>n.length)throw new ae(`Invalid array index: ${a}`);n.splice(e,0,s)}else n[a]=s;return e}function me(e,t){let s=he.get(t)||ne(t);if(he.set(t,s),0===s.length)return;let r=le(e,s.slice(0,-1)),i=s[s.length-1];if(Array.isArray(r)){let e=parseInt(i);r.splice(e,1)}else delete r[i];return e}function fe(e,t){let s=[];switch(e.type){case"addField":s.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":s.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach((([e,r])=>{"object"!=typeof r||null===r||Array.isArray(r),s.push({op:"replace",path:`${t}/${e}`,value:r})}));break}case"deprecateField":s.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||s.push({op:"add",path:"/indexes",value:[]}),s.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let r=t.indexes?.findIndex((t=>t.name===e.name));void 0!==r&&r>=0&&s.push({op:"remove",path:`/indexes/${r}`});break}case"modifyIndex":{let r=t.indexes?.findIndex((t=>t.name===e.name));void 0!==r&&r>=0&&Object.entries(e.changes).forEach((([e,t])=>{s.push({op:"replace",path:`/indexes/${r}/${e}`,value:t})}));break}case"addConstraint":t.constraints||s.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach((e=>{s.push({op:"add",path:"/constraints/-",value:e})})):s.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));void 0!==r&&r>=0&&s.push({op:"remove",path:`/constraints/${r}`});break}case"modifyConstraint":{let r=function(e,t){if(!e.constraints)return null;for(let s=0;s<e.constraints.length;s++){let r=e.constraints[s];if(r.name===t)return`/constraints/${s}`;if(ye(r)){let e=ge(r.rules,t);if(e)return`/constraints/${s}${e}`}}return null}(t,e.name);r&&Object.entries(e.changes).forEach((([e,t])=>{s.push({op:"replace",path:`${r}/${e}`,value:t})}));break}}return s}function ye(e){return e&&"operator"in e&&"rules"in e}function ge(e,t){for(let s=0;s<e.length;s++){let r=e[s];if("name"in r&&r.name===t)return`/rules/${s}`;if(ye(r)){let e=ge(r.rules,t);if(e)return`/rules/${s}${e}`}}return null}var we=new Map;function be(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function ve(e,t){let s=e=>({issues:e}),r=(e,t,s,r)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:s}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:s}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:s}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:s}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:s}];case"enum":return r?.values?r.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(r.values)}, got ${e}`,path:s}]:[{message:"Enum type requires 'values' definition",path:s}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:s}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:s}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:s}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:s}]:[];default:return[{message:`Unknown type '${t}'`,path:s}]}};function i(e,t,s,r,a){let n=[],o=e.rules.map(((e,o)=>{let c=[...r,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(a.has(h))return!0;a.add(h);let r=i(e,t,s,c,a);return n.push(...r),a.delete(h),0===r.length}{let r=s[e.predicate];if(!r)return n.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let i=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(we.has(i)){let t=we.get(i);return t||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${be(e.parameters)}`,path:c}),t}let a=r({data:t,field:e.field,arguments:e.parameters});return we.set(i,a),a||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${be(e.parameters)}`,path:c}),a}}));return(()=>{switch(e.operator){case"and":return o.every((e=>e));case"or":return o.some((e=>e));case"not":return!o.every((e=>e));case"nor":return!o.some((e=>e));case"xor":return 1===o.filter((e=>e)).length}})()||n.push({message:`Constraint group '${e.name}' failed`,path:r}),n}function a(e,t,s,n,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let a=n.length>0?e[n[n.length-1]]:e;return h.push(...r(a,t.type,n,{values:t.values})),t.constraints&&t.constraints.forEach(((e,t)=>{if("rules"in e)h.push(...i(e,{value:a},s,[...n,`constraints[${t}]`],c));else{let r=s[e.predicate];r?r({data:{value:a},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${be(e.parameters)}`,path:[...n,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...n,`constraints[${t}]`]})}})),h}let l={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let s=t.fields,r=s.find((e=>!e.when));r&&Object.assign(l,r.fields);let i=s.find((t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value));if(i)Object.assign(l,i.fields);else if(!r)return h.push({message:"No matching field set found for discriminated schema",path:n}),h}else l=t.fields;else l=t.fields;let d=new Set(Object.values(l).map((e=>e.name)));Object.entries(l).forEach((([t,l])=>{let d=[...n,l.name],u=Object.hasOwnProperty.call(e,l.name)?e[l.name]:void 0!==l.default?l.default:void 0;l.required&&null==u&&h.push({message:`Field '${l.name}' is required`,path:d});let p=l.schema||l.nestedSchema;if("object"===l.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=u&&"object"==typeof u&&!Array.isArray(u)?u:{};h.push(...a(t,e,s,d,o,c)),p.constraints?.forEach(((e,r)=>{if("rules"in e)h.push(...i(e,t,s,[...d,`constraints[${r}]`],c));else{let i=s[e.predicate];i?i({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${be(e.parameters)}`,path:[...d,`constraints[${r}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${r}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:d})}if("union"===l.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach(((r,n)=>{let h=o[r.id];if(h)if(c.has(r.id))t.push({message:`Circular reference detected at '${r.id}'`,path:[...d,n.toString()]});else{c.add(r.id);let n=u&&"object"==typeof u&&!Array.isArray(u)?u:{},l=a(n,h,s,d,o,new Set(c));0===l.length&&void 0!==u?(e=!0,r.constraints?.forEach(((r,a)=>{if("rules"in r){let o=i(r,n,s,[...d,`constraints[${a}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let i=s[r.predicate];i&&!i({data:n,field:void 0,arguments:r.parameters})&&(e=!1,t.push({message:r.errorMessage||`Constraint '${r.name}' failed`,path:[...d,`constraints[${a}]`]}))}}))):void 0===u&&t.push(...l.filter((e=>e.message.includes("is required")))),c.delete(r.id)}else t.push({message:`Nested schema '${r.id}' not found`,path:[...d,n.toString()]})})),e||void 0===u?void 0===u&&h.push(...t):(h.push({message:"Value does not match any union schema",path:d}),h.push(...t))}void 0!==u&&(h.push(...r(u,l.type,d,{values:l.values})),("array"===l.type||"set"===l.type)&&Array.isArray(u)&&(l.constraints?.forEach(((e,t)=>{let r=s[e.predicate];r&&!r({data:{[l.name]:u},field:l.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${l.name}'`,path:[...d,`constraints[${t}]`]})})),l.itemsType&&u.forEach(((e,t)=>h.push(...r(e,l.itemsType,[...d,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?u.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),h.push(...a(e,o[p.id],s,[...d,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:d}))),l.constraints?.forEach(((t,r)=>{if("rules"in t)h.push(...i(t,e,s,[...d,`constraints[${r}]`],c));else{let i=s[t.predicate];i?i({data:e,field:l.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${l.name}' with params ${be(t.parameters)}`,path:[...d,`constraints[${r}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${r}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...n,t]});return t.constraints?.forEach(((t,r)=>{if("rules"in t)h.push(...i(t,e,s,[...n,`constraints[${r}]`],c));else{let i=s[t.predicate];i?i({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${be(t.parameters)}`,path:[...n,`constraints[${r}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...n,`constraints[${r}]`]})}})),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:r=>{if("object"!=typeof r||null===r)return s([{message:"Input must be an object",path:[]}]);let i=r,n=a(i,e,t,[],e.nestedSchemas||{});return n.length>0?s(n):(e=>({value:e}))(i)},types:{input:{},output:{}}}}}var _e=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},$e=e=>({value:e}),ke=e=>({issues:e}),Ee=(e,t,s=!0)=>(void 0!==e||s)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],Se=(e,t)=>{let s=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&s.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${s.join(", ")}`,path:[t]}]},Ie=(e,t)=>{let s=["and","or","not","nor","xor"];return"string"==typeof e&&s.includes(e)?[]:[{message:`Must be one of ${s.join(", ")}`,path:[t]}]},Oe=(e,t,s=!1)=>(void 0!==e||s)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Ae=(e,t,s)=>{let r=[],i=["type","predicate","field","parameters","name","description","errorMessage"],a=e;return["predicate","name"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${s}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${s}.${e}`]})})),r.push(...Ee(e.name,`${s}.name`)),r.push(...Ee(e.predicate,`${s}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&r.push({message:"Field must be a string",path:[`${s}.field`]}),void 0!==e.parameters&&r.push(...(e.parameters,[])),r.push(...Ee(e.description,`${s}.description`,!1)),r.push(...Ee(e.errorMessage,`${s}.errorMessage`,!1)),r},Ne=(e,t,s)=>{let r=[],i=["name","operator","rules"],a=i,n=e;return i.forEach((e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${s}.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${s}.${e}`]})})),r.push(...Ee(e.name,`${s}.name`)),r.push(...Ie(e.operator,`${s}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,i)=>{"rules"in e?r.push(...Ne(e,t,`${s}.rules[${i}]`)):r.push(...Ae(e,0,`${s}.rules[${i}]`))})):r.push({message:"Rules must be a non-empty array",path:[`${s}.rules`]}),r},xe=(e,t,s)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[s]}];let r=[];return e.forEach(((e,i)=>{"rules"in e?r.push(...Ne(e,t,`${s}[${i}]`)):r.push(...Ae(e,0,`${s}[${i}]`))})),r},je=(e,t)=>{let s=[],r=["operator","field","value","conditions"],i=e;return["operator","field"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ie(e.operator,`${t}.operator`)),s.push(...Ee(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,r)=>s.push(...je(e,`${t}.conditions[${r}]`)))):s.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),s},Ce=(e,t)=>{let s=[],r=["fields","type","unique","partial","description","order","name"],i=e;return["fields","type","name"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.name,`${t}.name`)),s.push(...((e,t)=>{let s=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&s.includes(e)?[]:[{message:`Must be one of ${s.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every((e=>"string"==typeof e)))&&s.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),s.push(...Oe(e.unique,`${t}.unique`,!1)),e.partial&&s.push(...je(e.partial,`${t}.partial`)),s.push(...Ee(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&s.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),s},Te=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let s=[];return e.forEach(((e,r)=>s.push(...Ce(e,`${t}[${r}]`)))),s},Me=(e,t,s,r,i)=>{let a=[];return void 0===e?[]:("union"===s&&Array.isArray(e)?(0===e.length&&a.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach(((e,s)=>{let i=`${t}[${s}]`;a.push(...Ee(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(...xe(e.constraints,"dynamic",`${i}.constraints`)),e.indexes&&a.push(...Te(e.indexes,`${i}.indexes`))}))):"object"!==s&&("array"!==s||"object"!==i)||Array.isArray(e)?a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(a.push(...Ee(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(...xe(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&a.push(...Te(e.indexes,`${t}.indexes`))),a)},Re=(e,t,s)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[s]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[s]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[s]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[s]}];break;case"enum":if(!Array.isArray(e)||!e.every((e=>"string"==typeof e||"number"==typeof e)))return[{message:"Default must be an array of strings or numbers",path:[s]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[s]}];break;case"union":case"dynamic":return[]}return[]},De=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],Pe=(e,t,s)=>{let r=[],i=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],a=e;if(["name","type"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Ee(e.name,`${t}.name`)),r.push(...Se(e.type,`${t}.type`)),r.push(...Oe(e.required,`${t}.required`,!1)),e.constraints&&r.push(...xe(e.constraints,e.type,`${t}.constraints`)),r.push(...Re(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every((e=>"string"==typeof e||"number"==typeof e)))&&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`]})),void 0!==e.schema&&r.push(...Me(e.schema,`${t}.schema`,e.type,s,e.itemsType)),e.itemsType&&r.push(...Se(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"],n=e.nestedSchema;i.forEach((e=>{void 0===n[e]&&r.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})})),Object.keys(n).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})})),r.push(...Ee(e.nestedSchema.id,`${t}.nestedSchema.id`)),s.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(...xe(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&r.push(...Te(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(r.push(...Oe(e.deprecated,`${t}.deprecated`,!1)),e.reference){r.push({message:"reference is deprecated",path:[`${t}.reference`]});let s=["schema","field"],i=["schema","field"],a=e.reference;s.forEach((e=>{void 0===a[e]&&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(...Ee(e.reference.schema,`${t}.reference.schema`)),r.push(...Ee(e.reference.field,`${t}.reference.field`))}return r.push(...Ee(e.description,`${t}.description`,!1)),r.push(...Oe(e.unique,`${t}.unique`,!1)),e.hint&&r.push(...De(e.hint,`${t}.hint`)),r},qe=(e,t,s)=>{let r=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let i=["name","type","default","schema","itemsType","constraints","description","metadata"],a=e;["name","type"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Ee(e.name,`${t}.name`)),r.push(...Se(e.type,`${t}.type`)),r.push(...Re(e.default,e.type,`${t}.default`)),e.schema&&r.push(...Me(e.schema,`${t}.schema`,e.type,s,e.itemsType)),e.itemsType&&r.push(...Se(e.itemsType,`${t}.itemsType`)),e.constraints&&r.push(...xe(e.constraints,e.type,`${t}.constraints`)),r.push(...Ee(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&r.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let i=["name","description","concrete","fields","indexes","constraints","metadata"],a=e;["name"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Ee(e.name,`${t}.name`)),r.push(...Oe(a.concrete,`${t}.concrete`,!1)),a.concrete&&Array.isArray(a.fields)&&r.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(a.fields)?(0===a.fields.length&&r.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),a.fields.forEach(((e,i)=>{let a=`${t}.fields[${i}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?r.push({message:"Fields must be a non-empty object",path:[`${a}.fields`]}):Object.entries(t).forEach((([e,t])=>{r.push(...Pe(t,`${a}.fields.${e}`,s))})),void 0!==e.when&&("object"!=typeof e.when||null===e.when?r.push({message:"When must be an object",path:[`${a}.when`]}):r.push(...Ee(e.when.field,`${a}.when.field`)))}else r.push({message:"Each variant must have a 'fields' property",path:[a]})}))):void 0!==a.fields&&("object"!=typeof a.fields||null===a.fields?r.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(a.fields).forEach((([e,i])=>{r.push(...Pe(i,`${t}.fields.${e}`,s))}))),r.push(...Ee(e.description,`${t}.description`,!1)),e.indexes&&r.push(...Te(e.indexes,`${t}.indexes`)),e.constraints&&r.push(...xe(a.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&r.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return r},Fe=(e,t)=>{let s=[];switch(e.type||s.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let r=["type","id","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&s.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=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`)),s.push(...Pe(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let r=["type","id"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`));break}case"modifyField":{let r=["type","id","changes","nestedSchemaChanges"],i=e;if(["type","id","changes"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`)),"object"!=typeof e.changes&&s.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)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})})),s.push(...Ee(i.id,`${t}.nestedSchemaChanges.id`,!1)),i.constraints&&s.push(...xe(i.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),i.indexes&&s.push(...Te(i.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let r=["type","definition"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ce(e.definition,`${t}.definition`));break}case"removeIndex":{let r=["type","name"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.name,`${t}.name`));break}case"modifyIndex":{let r=["type","name","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.name,`${t}.name`)),"object"!=typeof e.changes&&s.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let r=["type","constraint"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"rules"in e.constraint?s.push(...Ne(e.constraint,"dynamic",`${t}.constraint`)):s.push(...Ae(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let r=["type","name"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.name,`${t}.name`));break}case"modifyConstraint":{let r=["type","name","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.name,`${t}.name`)),"object"!=typeof e.changes&&s.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=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`)),s.push(...qe(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let r=["type","id"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`));break}case"modifyNestedSchema":{let r=["type","id","changes"],i=r,a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`)),"object"!=typeof e.changes&&s.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:s.push({message:"Unknown schema change type",path:[`${t}.type`]})}return s},Be=(e,t)=>{let s=[],r=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],i=[...r,"rollback","dependencies"],a=e;r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...Ee(e.id,`${t}.id`)),s.push(...Ee(e.schemaVersion,`${t}.schemaVersion`)),s.push(...Ee(e.description,`${t}.description`));let n=["pending","applied","failed"];return n.includes(e.status)||s.push({message:`Status must be one of ${n.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach(((e,r)=>{s.push(...Fe(e,`${t}.changes[${r}]`))})):s.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach(((e,r)=>s.push(...Fe(e,`${t}.rollback[${r}]`)))):s.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?s.push(...Ee(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?s.push(...((e,t)=>{let s=[],r=["forward","backward"],i=r,a=e;return r.forEach((e=>{void 0===a[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"function"!=typeof e.forward&&s.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&s.push({message:"Backward must be a function",path:[`${t}.backward`]}),s})(e.transform,`${t}.transform`)):s.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),s.push(...Ee(e.createdAt,`${t}.createdAt`)),s.push(...Ee(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(s.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every((e=>"string"==typeof e)))&&s.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),s},ze={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return ke([{message:"Schema must be an object",path:[]}]);let t=e,s=[],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],i=t;if(["name","version","fields"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[e]})})),Object.keys(i).forEach((e=>{r.includes(e)||s.push({message:`Unknown property ${e}`,path:[e]})})),s.push(...Ee(t.name,"name")),s.push(...Ee(t.version,"version")),"object"!=typeof t.fields||null===t.fields)s.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])=>{s.push(...Pe(r,`fields.${t}`,e))}))}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)s.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach((([t,r])=>s.push(...qe(r,`nestedSchemas.${t}`,e))))}return s.push(...Ee(t.description,"description",!1)),t.indexes&&s.push(...Te(t.indexes,"indexes")),t.constraints&&s.push(...xe(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&s.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(s.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every((e=>"string"==typeof e)))&&s.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach(((e,t)=>s.push(...Be(e,`migrations[${t}]`)))):s.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&s.push({message:"Mock must be a function",path:["mock"]}),t.hint&&s.push(...De(t.hint,"hint")),s.length>0?ke(s):$e(t)},types:{input:{},output:{}}},Ue={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return ke([{message:"Migration must be an object",path:[]}]);let t=e,s=Be(t,"");return s.length>0?ke(s):$e(t)},types:{input:{},output:{}}},Le={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return ke([{message:"SchemaChanges must be an array",path:[]}]);let t=e,s=[];return t.forEach(((e,t)=>s.push(...Fe(e,`[${t}]`)))),s.length>0?ke(s):$e(t)},types:{input:[],output:[]}};function Ve(e){try{return!ze.validate(e).issues}catch(e){throw new _e("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function He(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function Je(e,t,s){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,s=new Set,r=new Set,i=new Set;for(let a of e)switch(a.type){case"addField":if(s.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);r.add(a.id);break;case"removeField":if(r.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);s.add(a.id);break;case"modifyField":if(s.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);t.add(a.id);break;case"deprecateField":if(s.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(t.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);i.add(a.id)}})(t),function(e){let t=new Set,s=new Set,r=new Set;for(let i of e)switch(i.type){case"addConstraint":let e=i.constraint.name;if(s.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);r.add(e);break;case"removeConstraint":if(r.has(i.name))throw new Error(`Cannot remove newly added constraint: ${i.name}`);if(t.has(i.name))throw new Error(`Cannot remove modified constraint: ${i.name}`);s.add(i.name);break;case"modifyConstraint":if(s.has(i.name))throw new Error(`Cannot modify removed constraint: ${i.name}`);if(r.has(i.name))throw new Error(`Cannot modify newly added constraint: ${i.name}`);t.add(i.name)}}(t);let r=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new 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)}}(e),i="patch";for(let e of t){let t=He(e);if("major"===t){i="major";break}"minor"===t&&"patch"===i&&(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 Ke(e,t){let s=e=>e.split(".").map((e=>parseInt(e,10)||0)),[r,i,a]=s(e),[n,o,c]=s(t);return r-n||i-o||a-c}var We,Ye=class extends Error{constructor(e,t,s,r){super(e),this.code=t,this.migrationId=s,this.cause=r,this.name="MigrationError"}},Ge=((We=Ge||{}).INVALID_SCHEMA="INVALID_SCHEMA",We.INVALID_MIGRATION="INVALID_MIGRATION",We.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",We.TIMEOUT="TIMEOUT",We.MEMORY_LIMIT="MEMORY_LIMIT",We.CONCURRENT_OPERATION="CONCURRENT_OPERATION",We.TRANSFORM_ERROR="TRANSFORM_ERROR",We.VERSION_NOT_FOUND="VERSION_NOT_FOUND",We.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",We.STREAM_ERROR="STREAM_ERROR",We.ROLLBACK_ERROR="ROLLBACK_ERROR",We.MISSING_TRANSFORM="MISSING_TRANSFORM",We),Xe=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,s){try{if(!Ve(e))throw new Ye("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!Ue.validate(e).issues}catch(e){throw new _e("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new Ye("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>Ke(e.schemaVersion,t.schemaVersion)))}s&&(this.history=s.sort(((e,t)=>Ke(e.version,t.version))))}catch(e){throw e instanceof Ye?e:new Ye("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map((e=>e.toString(16).padStart(2,"0"))).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new Ye("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new Ye("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new Ye("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!Le.validate(e).issues}catch(e){throw new _e("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new Ye("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,s,r){if(this.isProcessing)throw new Ye("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let i={...this.currentSchema},a=this.getRelevantMigrations(s,r);return{newSchema:a.reduce(((e,t)=>{let r="forward"===s?t.changes:t.rollback||[];return this.applySchemaChanges(e,r,t.id)}),i),dataPreview:await e.processMigrationList(t,s,a)}}catch(e){throw e instanceof Ye?e:new Ye("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter((s=>{let r="forward"===e?"pending":"applied",i=!t||Ke(s.schemaVersion,t)>=0;return s.status===r&&i})).sort(((t,s)=>"forward"===e?t.id.localeCompare(s.id):s.id.localeCompare(t.id)))}applySchemaChanges(e,t,s){try{let r=Je(e.version,t);return t.map((t=>{try{return fe(t,e)}catch(e){throw new Ye("Invalid schema change","INVALID_SCHEMA",s,e)}})).reduce(((e,t)=>{try{return function(e,t){let s=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":s=pe(s,e.path,e.value);break;case"remove":s=me(s,e.path);break;case"removeValue":s=ue(s,e.path,e.value);break;case"replace":s=pe(me(s,e.path),e.path,e.value);break;case"copy":{let t=de(s,e.from);s=pe(s,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=de(s,e.from);s=pe(s,e.path,t),s=me(s,e.from);break}case"test":{let t=de(s,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ae("Test operation failed");break}default:throw new ae(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ae&&(t.operation=e),t}return s}(e,t)}catch(e){throw new Ye("Failed to apply patch","INVALID_SCHEMA",s,e)}}),{...e,version:r})}catch(e){throw e instanceof Ye?e:new Ye("Schema update failed","INVALID_SCHEMA",s,e)}}async prepareMigration(){let e=this.migrations.filter((e=>"pending"===e.status));return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new Ye("Concurrent operation","CONCURRENT_OPERATION");let s=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let r=await e.processMigrationList(t,"forward",s);return this.markMigrationsApplied(s),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 Ye("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 Ye("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter((e=>"applied"===e.status)).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,s){if(this.isProcessing)throw new Ye("Concurrent operation","CONCURRENT_OPERATION");try{let r=this.history.findIndex((e=>e.version===t));if(-1===r)throw new Error(`Version ${t} not found in history`);let i=this.migrations.filter((e=>e.schemaVersion===t&&"applied"===e.status)).sort(((e,t)=>t.id.localeCompare(e.id))),a=this.history.length-r;if(a<0)return s;for(let e=0;e<a;e++)this.transformSchema("backward");let n=await e.processMigrationList(s,"backward",i);return this.migrations=this.migrations.map((e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e)),n}finally{this.isProcessing=!1}}static async processMigrationList(e,t,s){return(await Promise.all(s.map((async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new Ye(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}})))).filter((e=>!!e.transform)).reduce(((e,{migration:t,transform:s})=>e.pipeThrough(new TransformStream({async transform(e,r){try{let t=await s(e);r.enqueue(t)}catch(e){r.error(new Ye(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}}))),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?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 s=await fetch(e);if(!s.ok)throw new Ye(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await s.text();if(typeof window<"u"){let e=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:s}=await import("vm"),i={module:{exports:{}},console:console};return s(r,i,e),i.module.exports[t]}}catch(t){throw new Ye(`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 Ye(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter((e=>"pending"===e.status)).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 Ye?e:new Ye("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=e);var Qe=u(f()),Ze=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let s=-1;const r=i=>{if(i<=s)throw new Error("next() called multiple times");s=i;const 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){const s=this;return new Proxy(e,{get(e,r,i){const a=Reflect.get(e,r,i);return"function"==typeof a?function(...i){const n={...t,operation:r.toString(),args:i};return s.execute(n,(()=>a.apply(e,i)))}:a}})}},et=async(e,t)=>{const s=Date.now();try{const r=await t();return tt(e,s,r,null),r}catch(t){throw tt(e,s,void 0,t),t}};function tt(e,t,s,r){if(!e.eventBus)return;const 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(s)?"array":typeof s,size:Array.isArray(s)?s.length:void 0},error:r?{message:r.message,name:r.name,stack:r.stack}:null}}})}var{match:st}=(0,Qe.createMatcher)({});async function rt(e){const{collection:s,initial:r,validator:i,store:a,bus:n,lockManager:o}=e,[c,h]=Q(r),{value:l,issues:d}=i?await i["~standard"].validate(c):{value:r,issues:void 0};if(d)throw console.warn({issues:d}),new G("INVALID_DATA",`Invalid data for ${s}`);const u={current:Object.assign(l,h),deleted:!1};void 0===u.current.$id&&(u.current=Object.assign(u.current,{$id:t(),$created:(new Date).toJSON(),$version:1}));const p={save:async e=>{const t=await o.acquire();try{const{$id:t,$version:r}=u.current;if(!t)throw new Error("Document ID missing.");const i=await a.getById(t);if(i&&i.$version!==r)throw new G("CONFLICT",`Version mismatch on ${s}/${t}`);return u.current.$version=(r||0)+1,u.current.$updated=(new Date).toJSON(),e?await e.addOp(a,"put",u.current):await a.put(u.current),n.emit({name:"document:write",payload:{type:"document:write",data:u.current,timestamp:Date.now()}}),!0}finally{t()}},update:async(e,t)=>{const[r,a]=Q(Object.assign({},u.current,e)),{value:o,issues:c}=i?await i["~standard"].validate(r):{value:r,issues:void 0};if(c)throw new G("INVALID_DATA",`Invalid update for ${s}`);u.current=Object.assign(o,a);const h=await p.save(t);return h&&n.emit({name:"document:update",payload:{type:"document:update",data:u.current,timestamp:Date.now()}}),h},delete:async e=>{const t=await o.acquire();try{const{$id:t,$version:r}=u.current;if(!t)throw new Error("Document ID missing.");const i=await a.getById(t);if(i&&i.$version!==r)throw new G("CONFLICT",`Version mismatch on delete ${s}/${t}`);return e?await e.addOp(a,"delete",t):await a.delete(t),n.emit({name:"document:delete",payload:{type:"document:delete",data:u.current,timestamp:Date.now()}}),u.deleted=!0,!0}finally{t()}},read:async()=>{const e=u.current.$id,t=await a.getById(e);if(!t)throw new Error("Document not found.");return u.current={...t},n.emit({name:"document:read",payload:{type:"document:read",data:u.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=Q(e);return t})(u.current),subscribe:n.subscribe};return new Proxy({},{get(e,t){if(["update","delete","subscribe","read","state","save"].includes(t)){const e=p[t];return(...t)=>{if(u.deleted)throw new G("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(u.deleted)throw new G("INVALID_OPERATION","Document has been deleted");return Reflect.get(u.current,t)}})}function it(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}function at(e){return"function"==typeof e._getIDBConnection}var nt=class{id;staged=[];done=!1;constructor(){this.id=t()}async addOp(e,t,s){if(this.done)throw new G("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");this.staged.push({store:e,op:{type:t,data:s}})}async commit(){if(this.done)throw new G("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");if(this.done=!0,0===this.staged.length)return;const e=new Map,t=new Map;for(const{store:s,op:r}of this.staged)at(s)?(e.has(s)||e.set(s,[]),e.get(s).push(r)):(t.has(s)||t.set(s,[]),t.get(s).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){const t=Array.from(e.keys()).map((e=>e.name())),s=e.keys().next().value,r=await s._getIDBConnection();await new Promise(((s,i)=>{const a=r.transaction(t,"readwrite");a.oncomplete=()=>s(),a.onerror=()=>i(a.error??new Error("IDB transaction error")),a.onabort=()=>i(a.error??new Error("IDB transaction aborted")),(async()=>{try{for(const[t,s]of e)await t.executeInTransaction(s,a)}catch(e){try{a.abort()}catch(e){}i(e)}})()}))}async commitMemory(e){const t=[];try{for(const[s,r]of e){const e=s._snapshotMemory();t.push({store:s,snapshot:e}),await s.executeInTransaction(r,null)}}catch(e){for(const{store:e,snapshot:s}of t)try{e._rollbackMemory(s)}catch(e){}throw e}}completed(){return this.done}};function ot(e,t){return e instanceof G?e:e instanceof Error?new G("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new G("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}async function ct(e,s){const r=Y(),i=new Map,a=new Ze;a.use(((e=3,t=100)=>async(s,r)=>{let i=0;for(;i<e;)try{return await r()}catch(s){if(!(s instanceof G&&"TRANSIENT_ERROR"===s.type))throw s;{if(i++,i>=e)throw s;const r=t*Math.pow(2,i)+50*Math.random();await new Promise((e=>setTimeout(e,r)))}}})()),e.enableTelemetry&&a.use(et);const n=new Map,o=s({...e,collection:"schemas",keyPath:"name"},[]);async function c(t,r=[]){let i=n.get(t);return i||(i=s({...e,collection:t,keyPath:"$id"},r),n.set(t,i)),await i.open(),i}async function h(s){if(i.has(s))return i.get(s);const n=await o.getById(s);if(!n)throw new G("SCHEMA_NOT_FOUND",`Collection '${s}' does not exist`);const h=await c(s,n.indexes??[]),l=ve(n,e.predicates||{}),d=await async function({collection:e,validator:s,bus:r,store:i,pipeline:a,validate:n}){const o=new X,c={collection:e,validator:n?s:void 0,store:i,bus:r,pipeline:a,lockManager:o,valid:!0},h={async validate(e){const t=s["~standard"].validate(e);return t instanceof Promise?await t:t},create:async(a,o)=>{const[h,l]=Q(a),{value:d,issues:u}=n?await s["~standard"].validate(h):{value:h,issues:void 0};if(u)throw new G("INVALID_DATA",`Invalid data for collection '${e}'`);const p=Object.assign(d,l,{$id:t(),$created:(new Date).toJSON(),$version:1});o?await o.addOp(i,"add",p):await i.add(p),r.emit({name:"document:create",payload:{type:"document:create",data:p,timestamp:Date.now()}});const m=await rt({...c,initial:p});return r.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),m},find:async t=>{let s;const a=it(t);if(a)try{const e=t.value;s=(await i.findByIndex(a,e))[0]}catch{s=void 0}if(void 0===s&&(s=await i.cursor((async e=>e&&st(e,t)?{value:e,done:!0}:{value:null,done:!1}))??void 0),!s)return null;const n=await rt({...c,initial:s});return r.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),n},filter:async t=>{let s=[];const a=it(t);if(a)try{const e=t.value;s=await i.findByIndex(a,e)}catch{s=[]}0===s.length&&await i.cursor((async e=>(e&&st(e,t)&&s.push(e),{value:null,done:!1})));const n=await Promise.all(s.map((e=>rt({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),n},list:async t=>{const s={total:await i.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return 0===s.total?{next:async()=>({value:[],done:!0})}:{async next(){const a="offset"===t.type?await async function(e,t){const{offset:s,limit:r}=t,i=[];let a=0,n=!1;for(;!(n||(await e((async e=>a<s?(a++,{value:e,done:!1,offset:1}):(i.push(e),a++,a>=s+r?(n=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),i.length>=r)););return i}(i.cursor.bind(i),{...t,offset:s.offset}):await async function(e,t){const{limit:s,direction:r}=t,i=[];let a=!1;for(;!a;)await e((async e=>(i.push(e),i.length>=s?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),r);return i}(i.cursor.bind(i),{...t});s.offset+=s.limit,s.count+=a.length;const n=await Promise.all(a.map((e=>rt({...c,initial:e}))));return r.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:n,done:s.count>=s.total}}}}},l={...a.wrap(h,{collection:e,eventBus:r}),subscribe:r.subscribe,invalidate:()=>c.valid=!1};return new Proxy(l,{get(t,s,r){const i=Reflect.get(t,s,r);return"function"==typeof i?(...r)=>{if(!c.valid&&"invalidate"!==s)throw new G("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return i.apply(t,r)}:i}})}({collection:s,bus:r,validator:l,validate:Boolean(e.validate),store:h,pipeline:a});return r.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:s},timestamp:Date.now()}}),i.set(s,d),i.get(s)}async function l(e){return await o.put(e),r.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await o.open();const d={collection:h,createCollection:async e=>{if(await o.getById(e.name))throw new G("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!Ve(e))throw new G("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await o.put(e);const t=h(e.name);return r.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await o.getById(e);if(!t)throw new G("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const s=await c(e,t.indexes??[]);return await s.clear(),n.delete(e),await o.delete(e),i.delete(e),r.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:l,migrateCollection:async(e,t,s=100)=>{const r=i.get(e);r&&(r.invalidate(),i.delete(e));const a=await o.getById(e);if(!a)throw new G("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const n=await c(e,a.indexes??[]),d=new Xe(a);await d.add(t);const u=(await d.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema,p=new Set((a.indexes??[]).map((e=>e.name))),m=u.indexes??[],f=new Set(m.map((e=>e.name))),y=m.filter((e=>!p.has(e.name))),g=(a.indexes??[]).filter((e=>!f.has(e.name)));await l(u);try{const t=function(e,t,s){let r,i=!1;return new ReadableStream({async pull(a){if(i)return void a.close();let n=0;const o=void 0!==r?{lower:r,lowerOpen:!0}:void 0;try{await t.cursor((async(e,t)=>(a.enqueue(e),r=t,n++,n>=s?{done:!0,value:e}:{done:!1,value:e})),"forward",o),n<s&&(i=!0)}catch(t){a.error(ot(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,n,s),r=await d.migrate(t);await async function(e,t,s,r){const i=t.getReader();let a=[];try{for(;;){const{value:e,done:t}=await i.read();if(t)break;if(!e)continue;const{$version:n}=e;e.$version=(n||0)+1,e.$updated=(new Date).toJSON(),a.push(e),a.length>=r&&(await s.batch([{type:"put",data:a}]),a=[])}a.length>0&&await s.batch([{type:"put",data:a}])}catch(t){throw ot(t,e)}finally{i.releaseLock()}}(e,r,n,s)}catch(t){throw ot(t,e)}for(const e of y)await n.createIndex(e);for(const e of g)await n.dropIndex(e.name);return await h(e)}},u=a.wrap(d,{eventBus:r}),p={...u,transaction:async e=>{const t=new nt;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:r.subscribe,close:()=>{n.clear(),r.clear()},clear:async()=>{await o.clear(),await Promise.all(n.values().map((e=>e.clear())))},ensureCollection:async e=>{try{await u.createCollection(e)}catch(e){if(e instanceof G&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await p.ensureCollection(t)}};return p}var ht=u(f()),lt=class e{static dbInstances=new Map;static collectionInstances=new Map;static eventBusMap=new Map;static defaultModelName="stores";static getDatabase(t){const{database:s,enableTelemetry:r=!1,collection:i=e.defaultModelName}=t;if(!e.dbInstances.has(s)){const t=ct({database:s,enableTelemetry:r},ie).then((async e=>{try{await e.createCollection({name:i,version:"1.0.0",nestedSchemas:{},fields:{store:{name:"store",type:"string",required:!0},data:{name:"data",type:"object",required:!0},version:{name:"version",type:"string",required:!0},app:{name:"app",type:"string",required:!0}}})}catch(e){if(e instanceof G&&"SCHEMA_ALREADY_EXISTS"!==e.type)throw e}return e}));e.dbInstances.set(s,t)}return e.dbInstances.get(s)}static getEventBus(t,s){const r=`${t}_store_${s}`;return e.eventBusMap.has(r)||e.eventBusMap.set(r,Y({batch:{size:5,delay:16},errorHandler:e=>console.error(`Event bus error for ${t}:${s}:`,e),broadcast:{channel:r}})),e.eventBusMap.get(r)}static getCollection(t){const{database:s,collection:r=e.defaultModelName}=t,i=`${s}:${r}`;if(!e.collectionInstances.has(i)){const s=e.getDatabase(t).then((e=>e.collection(r)));e.collectionInstances.set(i,s)}return e.collectionInstances.get(i)}static async closeDatabase(t){const s=e.dbInstances.get(t);if(s){(await s).close(),e.dbInstances.delete(t);const r=[];e.collectionInstances.forEach(((e,s)=>{s.startsWith(`${t}:`)&&r.push(s)})),r.forEach((t=>e.collectionInstances.delete(t)));const i=[];e.eventBusMap.forEach(((e,s)=>{s.startsWith(`${t}_store_`)&&(e.clear(),i.push(s))})),i.forEach((t=>e.eventBusMap.delete(t)))}}static async closeAll(){const t=Array.from(e.dbInstances.keys()).map((t=>e.closeDatabase(t)));await Promise.all(t)}static getActiveDatabases(){return Array.from(e.dbInstances.keys())}},dt=class{collection=null;collectionPromise;config;eventBus;initialized=!1;initializationCallbacks=[];doc=null;getStoreName(){return`_${this.config.app}_${this.config.store}_`}constructor(e){this.config=e,this.collectionPromise=lt.getCollection(this.config),this.collectionPromise.then((e=>{this.collection=e,this.initialize()})).catch((e=>{console.error(`Failed to initialize collection for store ${this.getStoreName()}:`,e)})),this.eventBus=lt.getEventBus(this.config.database,this.getStoreName())}async initialize(){try{const e=await this._get();if(e&&e.version!==this.config.version&&this.config.onUpgrade){const{state:t}=await this.config.onUpgrade({data:e.data,version:e.version,app:e.app});await this.set("migration",t)}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize and upgrade store ${this.getStoreName()}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}async getCollection(){return this.collection?this.collection:this.collectionPromise}async set(e,t){try{const s=await this.getCollection(),r=await this._read(),i={store:this.getStoreName(),data:t,version:this.config.version,app:this.config.app};let a;return r?a=await r.update(i):(this.doc=await s.create(i),a=!0),a&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.getStoreName(),instanceId:e,state:t,version:this.config.version,app:this.config.app}}),a}catch(t){return console.error(`Failed to set state for store ${this.getStoreName()} in database ${this.config.database} by instance ${e}:`,t),!1}}async _read(){if(this.doc)return this.doc;const e=await this.getCollection(),t=(new ht.QueryBuilder).where({field:"store",operator:"eq",value:this.getStoreName()}).build(),s=await e.find(t.filters);return this.doc=s,this.doc}async _get(){try{const e=await this._read();return e?e.read().then((()=>e)):null}catch(e){return console.error(`Failed to get state for store ${this.getStoreName()} in database ${this.config.database}:`,e),null}}async get(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));const e=await this._get();return e?e.data:null}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:s,instanceId:r,state:i})=>{s===this.getStoreName()&&r!==e&&t(i)}))}async clear(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));try{const e=await this._read();return!e||!await e.delete()||(this.doc=null,!0)}catch(e){return console.error(`Failed to clear state for store ${this.getStoreName()} in database ${this.config.database}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}async close(){await lt.closeDatabase(this.config.database)}};export{dt as IndexedDBPersistence,L as WebStoragePersistence};
1
+ import{Buffer as e}from"buffer";import{v7 as t}from"uuid";var r,s,a=Object.create,i=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,c=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},d=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))h.call(e,a)||a===r||i(e,a,{get:()=>t[a],enumerable:!(s=n(t,a))||s.enumerable});return e},u=(e,t,r)=>(r=null!=e?a(c(e)):{},d(e&&e.__esModule?r:i(r,"default",{value:e,enumerable:!0}),e)),p=e=>d(i({},"__esModule",{value:!0}),e),m=l({"node_modules/@asaidimu/events/index.js"(e,t){var r,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of i(t))n.call(e,c)||c===r||s(e,c,{get:()=>t[c],enumerable:!(o=a(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,a=0;const i=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,a+=t,i.set(e,(i.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const s=performance.now();try{(n.get(t)||[]).forEach((e=>e(r)))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?n.set(e,Array.from(r)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(n.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),d(e),()=>{s.delete(r),0===s.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:s})=>{if(e.async)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():l(),void(o&&o.postMessage({name:t,payload:s}));const a=performance.now();try{(n.get(t)||[]).forEach((e=>e(s))),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-a)},getMetrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:i,averageEmitDuration:s>0?a/s:0}),clear:()=>{t.clear(),n.clear(),r=[],s=0,a=0,i.clear(),o&&(o.close(),o=null)}}}}}),f=l({"node_modules/@asaidimu/query/index.js"(e,t){var r,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})})(o,{QueryBuilder:()=>c,createJoiner:()=>y,createMatcher:()=>l,createPaginator:()=>E,createProjector:()=>_,createSorter:()=>$}),t.exports=(r=o,((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of i(t))!n.call(e,c)&&c!==r&&s(e,c,{get:()=>t[c],enumerable:!(o=a(t,c))||o.enumerable});return e})(s({},"__esModule",{value:!0}),r));var c=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,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},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,r){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:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,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 h(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?s(t,e):function(e){return"computed"===e?.type}(t)?s(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(a(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every((t=>a(e,t)))],["or",(e,t)=>t.some((t=>a(e,t)))],["not",(e,t)=>!t.every((t=>a(e,t)))],["nor",(e,t)=>!t.some((t=>a(e,t)))],["xor",(e,t)=>1===t.filter((t=>a(e,t))).length]]);function s(r,s){let a=r.arguments.map((e=>t(s,e)));if(e[r.function])return e[r.function](...a);throw new Error(`Function ${r.function} not found!`)}function a(s,a){if(function(e){return!!e&&void 0!==e.conditions}(a))return function(e,t){let{operator:s,conditions:a}=t,i=r.get(s);if(i)return i(e,a);throw new Error(`Unsupported logical operator: ${s}`)}(s,a);if(!a||!a.field)return!1;let{field:i,operator:n,value:o}=a,c=s[i],h=t(s,o),l=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)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(o)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[n]||l.get(n);if(d)return d(c,h);throw new Error(`Unsupported comparison operator: ${n}`)}return{resolve:t,evaluate:a}}function l(e){let{evaluate:t}=h(e),r=new WeakMap;function s(e,s){let a=r.get(e);a||(a=new Map,r.set(e,a));let i=JSON.stringify(s);if(a.has(i))return a.get(i);let n=t(e,s);return a.set(i,n),n}return{matcher:s,match:s}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},u=e=>e&&"field"in e&&"operator"in e&&"value"in e,p=(e,t)=>{if(e){if(u(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map((e=>p(e,t)))),r}return e}},m=async(e,t,r,s)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let a,i=e[r.relation];return r.query?.filters&&u(r.query.filters)&&(a=((e,t)=>{let r=new Map;return e.forEach((e=>{let s=e[t];r.has(s)||r.set(s,[]),r.get(s).push(e)})),r})(i,r.query.filters.field)),(await Promise.all(t.map((async e=>{let t,n=((e,t)=>{if(!e)return{};let r=p(e.filters,t);return{...e,filters:r}})(r.query,e);return t=n.filters&&u(n.filters)&&a?.has(n.filters.value)?a.get(n.filters.value)||[]:i.filter((e=>s.matcher(e,n.filters))),((e,t,r)=>{let s=r.alias||r.relation;return[{...e,[s]:t}]})(e,await[e=>n.sort?s.sorter(e,n.sort):e,e=>n.projection?s.projector(e,n.projection):e,async e=>n.pagination?await s.paginator(e,n.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),r)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},f=async(e,t,r,s)=>r.reduce((async(t,r)=>m(e,await t,r,s)),Promise.resolve(t));function y(){return{join:f}}var g=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},w=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new g(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort(((e,r)=>{for(let s of t){let{field:t,direction:a}=s,i=e[t],n=r[t];try{if("asc"!==a&&"desc"!==a)throw new w(a);let e=b(i,n,a);if(0!==e)return e}catch(e){throw e instanceof g||e instanceof w?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function $(){return{sort:v}}function _(e){let{resolve:t}=h(e);function r(e,s){let a={};return s.include?.length&&function(e,t,s){for(let a of t)if("string"!=typeof a){for(let[t,i]of Object.entries(a))if(Object.prototype.hasOwnProperty.call(e,t)){let a=r(e[t],i);s[t]=a}}else{let t=a;s[t]=e[t]}}(e,s.include,a),s.exclude?.length&&function(e,t,s){0===Object.keys(s).length&&Object.assign(s,e);for(let e of t)if("string"!=typeof e)for(let[t,a]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(s,t))continue;let e=s[t];e&&"object"==typeof e?s[t]=r(e,a):delete s[t]}else delete s[e]}(e,s.exclude,a),s.computed?.length&&function(e,r,s){for(let a of r)s[a.alias]=t(e,a)}(e,s.computed,a),a}return{project:r}}async function*k(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:s}=t,a=0,i=s,n=[];for await(let t of e)i<=0&&(yield n,n=[],i=s),a<r?a++:(n.push(t),i--);n.length>0&&(yield n)}(e,t):yield*async function*(e,t,r){let{cursor:s,limit:a,direction:i}=t,n=a,o=void 0===s,c=[];if("forward"===i)for await(let t of e)n<=0&&(yield c,c=[],n=a),o?(c.push(t),n--):o=r(t)===s;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let i=t[e];o?(c.push(i),n--,n<=0&&(yield c,c=[],n=a)):o=r(i)===s}}c.length>0&&(yield c)}(e,t,r)}function E(){return{paginate:k}}}}),y=l({"node_modules/just-once/index.js"(e,t){t.exports=function(e){var t,r;if("function"!=typeof e)throw new Error("expected a function but got "+e);return function(){return t?r:(t=!0,r=e.apply(this,arguments))}}}}),g=l({"node_modules/isomorphic-textencoder/main.js"(e,t){t.exports={encode:e=>new Uint8Array(Buffer.from(e,"utf8")),decode:e=>Buffer.from(e).toString("utf8")}}}),w=l({"node_modules/just-debounce-it/index.js"(e,t){t.exports=function(e,t,r){var s;return function(){if(!t)return e.apply(this,arguments);var a=this,i=arguments,n=r&&!s;return clearTimeout(s),s=setTimeout((function(){if(s=null,!n)return e.apply(a,i)}),t),n?e.apply(this,arguments):void 0}}}}),b=l({"node_modules/@isomorphic-git/lightning-fs/src/path.js"(e,t){function r(e){if(0===e.length)return".";let t=a(e);return t=t.reduce(i,[]),s(...t)}function s(...e){if(0===e.length)return"";let t=e.join("/");return t=t.replace(/\/{2,}/g,"/"),t}function a(e){if(0===e.length)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 i(e,t){if(0===e.length)return e.push(t),e;if("."===t)return e;if(".."===t){if(1===e.length){if("/"===e[0])throw new 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:s,normalize:r,split:a,basename:function(e){if("/"===e)throw new Error(`Cannot get basename of "${e}"`);const t=e.lastIndexOf("/");return-1===t?e:e.slice(t+1)},dirname:function(e){const t=e.lastIndexOf("/");if(-1===t)throw new Error(`Cannot get dirname of "${e}"`);return 0===t?"/":e.slice(0,t)},resolve:function(...e){let t="";for(let a of e)t=a.startsWith("/")?a:r(s(t,a));return t}}}}),v=l({"node_modules/@isomorphic-git/lightning-fs/src/errors.js"(e,t){function r(e){return class extends Error{constructor(...t){super(...t),this.code=e,this.message?this.message=e+": "+this.message:this.message=e}}}var s=r("EEXIST"),a=r("ENOENT"),i=r("ENOTDIR"),n=r("ENOTEMPTY"),o=r("ETIMEDOUT"),c=r("EISDIR");t.exports={EEXIST:s,ENOENT:a,ENOTDIR:i,ENOTEMPTY:n,ETIMEDOUT:o,EISDIR:c}}}),$=l({"node_modules/@isomorphic-git/lightning-fs/src/CacheFS.js"(e,t){var r=b(),{EEXIST:s,ENOENT:a,ENOTDIR:i,ENOTEMPTY:n,EISDIR:o}=v();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){this._root=null===e?new Map([["/",this._makeRoot()]]):"string"==typeof e?new Map([["/",this._makeRoot(this.parse(e))]]):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[r,s]of e)0!==r&&(t+=this._countInodes(s));return t}autoinc(){return this._maxInode(this._root.get("/"))+1}_maxInode(e){let t=e.get(0).ino;for(let[r,s]of e)0!==r&&(t=Math.max(t,this._maxInode(s)));return t}print(e=this._root.get("/")){let t="";const r=(e,s)=>{for(let[a,i]of e){if(0===a)continue;let e=i.get(0),n=e.mode.toString(8);t+=`${"\t".repeat(s)}${a}\t${n}`,"file"===e.type?t+=`\t${e.size}\t${e.mtimeMs}\n`:(t+="\n",r(i,s+1))}};return r(e,0),t}parse(e){let t=0;function r(e){const r=++t,s=1===e.length?"dir":"file";let[a,i,n]=e;return a=parseInt(a,8),i=i?parseInt(i):0,n=n?parseInt(n):Date.now(),new Map([[0,{mode:a,type:s,size:i,mtimeMs:n,ino:r}]])}let s=e.trim().split("\n"),a=this._makeRoot(),i=[{indent:-1,node:a},{indent:0,node:null}];for(let e of s){let t=e.match(/^\t*/)[0].length;e=e.slice(t);let[s,...a]=e.split("\t"),n=r(a);if(t<=i[i.length-1].indent)for(;t<=i[i.length-1].indent;)i.pop();i.push({indent:t,node:n}),i[i.length-2].node.set(s,n)}return a}_lookup(e,t=!0){let s=this._root,i="/",n=r.split(e);for(let o=0;o<n.length;++o){let c=n[o];if(s=s.get(c),!s)throw new a(e);if(t||o<n.length-1){const e=s.get(0);if("symlink"===e.type){let t=r.resolve(i,e.target);s=this._lookup(t)}i=i?r.join(i,c):c}}return s}mkdir(e,{mode:t}){if("/"===e)throw new s;let a=this._lookup(r.dirname(e)),i=r.basename(e);if(a.has(i))throw new s;let n=new Map,o={mode:t,type:"dir",size:0,mtimeMs:Date.now(),ino:this.autoinc()};n.set(0,o),a.set(i,n)}rmdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new i;if(t.size>1)throw new n;let s=this._lookup(r.dirname(e)),a=r.basename(e);s.delete(a)}readdir(e){let t=this._lookup(e);if("dir"!==t.get(0).type)throw new i;return[...t.keys()].filter((e=>"string"==typeof e))}writeStat(e,t,{mode:s}){let a,i;try{i=this.stat(e)}catch(e){}if(void 0!==i){if("dir"===i.type)throw new o;null==s&&(s=i.mode),a=i.ino}null==s&&(s=438),null==a&&(a=this.autoinc());let n=this._lookup(r.dirname(e)),c=r.basename(e),h={mode:s,type:"file",size:t,mtimeMs:Date.now(),ino:a},l=new Map;return l.set(0,h),n.set(c,l),h}unlink(e){let t=this._lookup(r.dirname(e)),s=r.basename(e);t.delete(s)}rename(e,t){let s=r.basename(t),a=this._lookup(e);this._lookup(r.dirname(t)).set(s,a),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 s,a;try{let e=this.stat(t);null===a&&(a=e.mode),s=e.ino}catch(e){}null==a&&(a=40960),null==s&&(s=this.autoinc());let i=this._lookup(r.dirname(t)),n=r.basename(t),o={mode:a,type:"symlink",target:e,size:0,mtimeMs:Date.now(),ino:s},c=new Map;return c.set(0,o),i.set(n,c),o}_du(e){let t=0;for(const[r,s]of e.entries())t+=0===r?s.size:this._du(s);return t}du(e){let t=this._lookup(e);return this._du(t)}}}}),_={};function k(){return s||(s=new r),s}function E(e,t=k()){let r;return t._withIDBStore("readwrite",(t=>{r=t.get(e)})).then((()=>r.result))}function S(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{r.put(t,e)}))}function I(e,t,r=k()){return r._withIDBStore("readwrite",(r=>{const s=r.get(e);s.onsuccess=()=>{r.put(t(s.result),e)}}))}function O(e,t=k()){return t._withIDBStore("readwrite",(t=>{t.delete(e)}))}function A(e=k()){return e._withIDBStore("readwrite",(e=>{e.clear()}))}function N(e=k()){const 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 x(e=k()){return e._close()}((e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})})(_,{Store:()=>r,clear:()=>A,close:()=>x,del:()=>O,get:()=>E,keys:()=>N,set:()=>S,update:()=>I});var j,C,T=(j={"node_modules/@isomorphic-git/idb-keyval/dist/idb-keyval.mjs"(){r=class{constructor(e="keyval-store",t="keyval"){this.storeName=t,this._dbName=e,this._storeName=t,this._init()}_init(){this._dbp||(this._dbp=new Promise(((e,t)=>{const r=indexedDB.open(this._dbName);r.onerror=()=>t(r.error),r.onsuccess=()=>e(r.result),r.onupgradeneeded=()=>{r.result.createObjectStore(this._storeName)}})))}_withIDBStore(e,t){return this._init(),this._dbp.then((r=>new Promise(((s,a)=>{const i=r.transaction(this.storeName,e);i.oncomplete=()=>s(),i.onabort=i.onerror=()=>a(i.error),t(i.objectStore(this.storeName))}))))}_close(){return this._init(),this._dbp.then((e=>{e.close(),this._dbp=void 0}))}}}},function(){return j&&(C=(0,j[o(j)[0]])(j=0)),C}),M=l({"node_modules/@isomorphic-git/lightning-fs/src/IdbBackend.js"(e,t){var r=(T(),p(_));t.exports=class{constructor(e,t){this._database=e,this._storename=t,this._store=new r.Store(this._database,this._storename)}saveSuperblock(e){return r.set("!root",e,this._store)}loadSuperblock(){return r.get("!root",this._store)}readFile(e){return r.get(e,this._store)}writeFile(e,t){return r.set(e,t,this._store)}unlink(e){return r.del(e,this._store)}wipe(){return r.clear(this._store)}close(){return r.close(this._store)}}}}),R=l({"node_modules/@isomorphic-git/lightning-fs/src/HttpBackend.js"(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){const t=await fetch(this._url+e);if(200===t.status)return t.arrayBuffer();throw new Error("ENOENT")}async sizeFile(e){const t=await fetch(this._url+e,{method:"HEAD"});if(200===t.status)return t.headers.get("content-length");throw new Error("ENOENT")}}}}),D=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex.js"(e,t){var r=(T(),p(_)),s=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 r.Store(this._database,this._storename),this._lock=null}async has({margin:e=2e3}={}){if(this._lock&&this._lock.holder===this._id){const t=Date.now();return this._lock.expires>t+e||await this.renew()}return!1}async renew({ttl:e=5e3}={}){let t;return await r.update("lock",(r=>{const s=Date.now()+e;return t=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:s}:r,this._lock}),this._store),t}async acquire({ttl:e=5e3}={}){let t,s,a;if(await r.update("lock",(r=>{const i=Date.now(),n=i+e;return s=r&&r.expires<i,t=void 0===r||s,a=r&&r.holder===this._id,this._lock=t?{holder:this._id,expires:n}:r,this._lock}),this._store),a)throw new Error("Mutex double-locked");return t}async wait({interval:e=100,limit:t=6e3,ttl:r}={}){for(;t--;){if(await this.acquire({ttl:r}))return!0;await s(e)}throw new Error("Mutex timeout")}async release({force:e=!1}={}){let t,s,a;if(await r.update("lock",(r=>(t=e||r&&r.holder===this._id,s=void 0===r,a=r&&r.holder!==this._id,this._lock=t?void 0:r,this._lock)),this._store),await r.close(this._store),!t&&!e){if(s)throw new Error("Mutex double-freed");if(a)throw new Error("Mutex lost ownership")}return t}}}}),P=l({"node_modules/@isomorphic-git/lightning-fs/src/Mutex2.js"(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,r)=>{const s=new AbortController;setTimeout((()=>{s.abort(),r(new Error("Mutex timeout"))}),e),navigator.locks.request(this._database+"_lock",{signal:s.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))}}}}),q=l({"node_modules/@isomorphic-git/lightning-fs/src/DefaultBackend.js"(e,t){var{encode:r,decode:s}=g(),a=w(),i=$(),{ENOENT:n,ENOTEMPTY:o,ETIMEDOUT:c}=v(),h=M(),l=R(),d=D(),u=P(),p=b();t.exports=class{constructor(){this.saveSuperblock=a((()=>{this.flush()}),500)}async init(e,{wipe:t,url:r,urlauto:s,fileDbName:a=e,db:n=null,fileStoreName:o=e+"_files",lockDbName:c=e+"_lock",lockStoreName:p=e+"_lock"}={}){this._name=e,this._idb=n||new h(a,o),this._mutex=navigator.locks?new u(e):new d(c,p),this._cache=new i(e),this._opts={wipe:t,url:r},this._needsWipe=!!t,r&&(this._http=new l(r),this._urlauto=!!s)}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();const e=await this._idb.loadSuperblock();if(e)this._cache.activate(e);else if(this._http){const 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,r){let s=p.split(p.dirname(e)),a=s.shift();for(let e of s){a=p.join(a,e);try{this._cache.mkdir(a,{mode:511})}catch(e){}}return this._cache.writeStat(e,t,r)}async readFile(e,t){const r="string"==typeof t?t:t&&t.encoding;if(r&&"utf8"!==r)throw new Error('Only "utf8" encoding is supported in readFile');let a=null,i=null;try{i=this._cache.stat(e),a=await this._idb.readFile(i.ino)}catch(e){if(!this._urlauto)throw e}if(!a&&this._http){let t=this._cache.lstat(e);for(;"symlink"===t.type;)e=p.resolve(p.dirname(e),t.target),t=this._cache.lstat(e);a=await this._http.readFile(e)}if(a&&(i&&i.size==a.byteLength||(i=await this._writeStat(e,a.byteLength,{mode:i?i.mode:438}),this.saveSuperblock()),"utf8"===r?a=s(a):a.toString=()=>s(a)),!i)throw new n(e);return a}async writeFile(e,t,s){const{mode:a,encoding:i="utf8"}=s;if("string"==typeof t){if("utf8"!==i)throw new Error('Only "utf8" encoding is supported in writeFile');t=r(t)}const n=await this._cache.writeStat(e,t.byteLength,{mode:a});await this._idb.writeFile(n.ino,t)}async unlink(e,t){const r=this._cache.lstat(e);this._cache.unlink(e),"symlink"!==r.type&&await this._idb.unlink(r.ino)}readdir(e,t){return this._cache.readdir(e)}mkdir(e,t){const{mode:r=511}=t;this._cache.mkdir(e,{mode:r})}rmdir(e,t){if("/"===e)throw new o;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 r=await this._http.sizeFile(e);await this._writeStat(e,r,t)}du(e){return this._cache.du(e)}flush(){return this._saveSuperblock()}}}}),F=l({"node_modules/@isomorphic-git/lightning-fs/src/Stat.js"(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"file"===this.type}isDirectory(){return"dir"===this.type}isSymbolicLink(){return"symlink"===this.type}}}}),B=l({"node_modules/@isomorphic-git/lightning-fs/src/PromisifiedFS.js"(e,t){var r=q(),s=F(),a=b();function i(e,t,...r){return void 0!==t&&"function"!=typeof t||(t={}),"string"==typeof t&&(t={encoding:t}),[e=a.normalize(e),t,...r]}function n(e,t,r,...s){return void 0!==r&&"function"!=typeof r||(r={}),"string"==typeof r&&(r={encoding:r}),[e=a.normalize(e),t,r,...s]}function o(e,t,...r){return[a.normalize(e),a.normalize(t),...r]}t.exports=class{constructor(e,t={}){this.init=this.init.bind(this),this.readFile=this._wrap(this.readFile,i,!1),this.writeFile=this._wrap(this.writeFile,n,!0),this.unlink=this._wrap(this.unlink,i,!0),this.readdir=this._wrap(this.readdir,i,!1),this.mkdir=this._wrap(this.mkdir,i,!0),this.rmdir=this._wrap(this.rmdir,i,!0),this.rename=this._wrap(this.rename,o,!0),this.stat=this._wrap(this.stat,i,!1),this.lstat=this._wrap(this.lstat,i,!1),this.readlink=this._wrap(this.readlink,i,!1),this.symlink=this._wrap(this.symlink,o,!0),this.backFile=this._wrap(this.backFile,i,!0),this.du=this._wrap(this.du,i,!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 r,this._backend.init&&await this._backend.init(e,t),this._initPromiseResolve&&(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,r){return async(...s)=>{s=t(...s);let a={name:e.name,args:s};this._operations.add(a);try{return await this._activate(),await e.apply(this,s)}finally{this._operations.delete(a),r&&this._backend.saveSuperblock(),0===this._operations.size&&(this._deactivationTimeout||clearTimeout(this._deactivationTimeout),this._deactivationTimeout=setTimeout(this._deactivate.bind(this),500))}}}async _activate(){this._initPromise||console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)),await this._initPromise,this._deactivationTimeout&&(clearTimeout(this._deactivationTimeout),this._deactivationTimeout=null),this._deactivationPromise&&await this._deactivationPromise,this._deactivationPromise=null,this._activationPromise||(this._activationPromise=this._backend.activate?this._backend.activate():Promise.resolve()),await this._activationPromise}async _deactivate(){return this._activationPromise&&await this._activationPromise,this._deactivationPromise||(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,r){return await this._backend.writeFile(e,t,r),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){const r=await this._backend.stat(e,t);return new s(r)}async lstat(e,t){const r=await this._backend.lstat(e,t);return new s(r)}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()}}}}),z=l({"node_modules/@isomorphic-git/lightning-fs/src/index.js"(e,t){var r=y(),s=B();function a(e,t){"function"==typeof e&&(t=e);return[(...e)=>t(null,...e),t=r(t)]}t.exports=class{constructor(...e){this.promises=new s(...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,r){const[s,i]=a(t,r);this.promises.readFile(e,t).then(s).catch(i)}writeFile(e,t,r,s){const[i,n]=a(r,s);this.promises.writeFile(e,t,r).then(i).catch(n)}unlink(e,t,r){const[s,i]=a(t,r);this.promises.unlink(e,t).then(s).catch(i)}readdir(e,t,r){const[s,i]=a(t,r);this.promises.readdir(e,t).then(s).catch(i)}mkdir(e,t,r){const[s,i]=a(t,r);this.promises.mkdir(e,t).then(s).catch(i)}rmdir(e,t,r){const[s,i]=a(t,r);this.promises.rmdir(e,t).then(s).catch(i)}rename(e,t,r){const[s,i]=a(r);this.promises.rename(e,t).then(s).catch(i)}stat(e,t,r){const[s,i]=a(t,r);this.promises.stat(e).then(s).catch(i)}lstat(e,t,r){const[s,i]=a(t,r);this.promises.lstat(e).then(s).catch(i)}readlink(e,t,r){const[s,i]=a(t,r);this.promises.readlink(e).then(s).catch(i)}symlink(e,t,r){const[s,i]=a(r);this.promises.symlink(e,t).then(s).catch(i)}backFile(e,t,r){const[s,i]=a(t,r);this.promises.backFile(e,t).then(s).catch(i)}du(e,t){const[r,s]=a(t);this.promises.du(e).then(r).catch(s)}flush(e){const[t,r]=a(e);this.promises.flush().then(t).catch(r)}}}}),U=u(m()),L=class{eventBus;storage;config;initialized=!1;initializationCallbacks=[];constructor(e){this.config=e,this.storage=e.session?sessionStorage:localStorage,this.eventBus=this.initializeEventBus(),this.initialize(),e.session||this.setupStorageEventListener()}async initialize(){try{const e=this.storage.getItem(this.getStoreName());if(e){const t=JSON.parse(e);if(t.version!==this.config.version&&this.config.onUpgrade){const{state:e}=await this.config.onUpgrade({data:t.state,version:t.version,app:t.app});this.set("migration",e)}}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize WebStoragePersistence for ${this.config.storageKey}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}initializeEventBus(){return(0,U.createEventBus)({async:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${this.config.storageKey}:`,e),crossTab:"undefined"==typeof process||"test"!==process.env.NODE_ENV,channelName:`storage_${this.getStoreName()}`})}getStoreName(){return`_${this.config.app}_${this.config.storageKey}_`}setupStorageEventListener(){window.addEventListener("storage",(e=>{if(e.key===this.getStoreName()&&e.newValue)try{const t=JSON.parse(e.newValue);t&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"external",state:t.state,version:t.version,app:t.app}})}catch(e){console.error("Failed to parse storage event data:",e)}}))}set(e,t){try{const r={state:structuredClone(t),version:this.config.version,app:this.config.app},s=JSON.stringify(r);return this.storage.setItem(this.getStoreName(),s),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:e,state:t,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to persist state to web storage for ${this.config.storageKey}:`,e),!1}}_get(){try{const e=this.storage.getItem(this.getStoreName());if(!e)return null;return JSON.parse(e).state}catch(e){return console.error(`Failed to retrieve state from web storage for ${this.config.storageKey}:`,e),null}}async get(){return this.initialized||await new Promise((e=>{this._onInitialized(e)})),this._get()}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:s,state:a})=>{r===this.config.storageKey&&s!==e&&t(a)}))}clear(){try{return this.storage.removeItem(this.getStoreName()),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.storageKey,instanceId:"clear-initiator",state:null,version:this.config.version,app:this.config.app}}),!0}catch(e){return console.error(`Failed to clear persisted state for ${this.config.storageKey}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}},V=(e={batch:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],s=0,a=0;const i=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{s++,a+=t,i.set(e,(i.get(e)||0)+1)},h=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const s=performance.now();try{(n.get(t)||[]).forEach((e=>e(r)))}catch(s){e.errorHandler({...s,eventName:t,payload:r})}c(t,performance.now()-s)}))},l=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(h,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?n.set(e,Array.from(r)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:r}=e.data;(n.get(t)||[]).forEach((e=>e(r)))}),{once:(e,r)=>{let s;const a=e=>{s(),r(e)};return s=(()=>{t.has(e)||t.set(e,new Set);const r=t.get(e);return r.add(a),()=>{r.delete(a),0===r.size&&t.delete(e)}})(),s},subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const s=t.get(e);return s.add(r),d(e),()=>{s.delete(r),0===s.size?(t.delete(e),n.delete(e)):d(e)}},emit:({name:t,payload:s})=>{if(e.batch)return r.push({name:t,payload:s}),r.length>=e.batchSize?h():l(),void(o&&o.postMessage({name:t,payload:s}));const a=performance.now();try{(n.get(t)||[]).forEach((e=>e(s))),o&&o.postMessage({name:t,payload:s})}catch(r){e.errorHandler({...r,eventName:t,payload:s})}c(t,performance.now()-a)},metrics:()=>({totalEvents:s,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:i,averageEmitDuration:s>0?a/s:0}),clear:()=>{t.clear(),n.clear(),r=[],s=0,a=0,i.clear(),o&&(o.close(),o=null)}}},H=class extends Error{type;schema;constructor(e,t,r,s){super(t,{cause:s}),this.type=e,this.schema=r,this.name="DatabaseError"}},J=class{queue=[];locked=!1;async acquire(){return this.locked?new Promise((e=>{this.queue.push((()=>e((()=>this.release()))))})):(this.locked=!0,()=>this.release())}release(){if(this.queue.length>0){const e=this.queue.shift();e&&e()}else this.locked=!1}};function K(e){if(null===e||"object"!=typeof e||Array.isArray(e))return[e,{}];const t={};return[Object.entries(e).reduce(((e,[r,s])=>(r.startsWith("$")?t[r]=s:e[r]=s,e)),{}),t]}function W(e,t){if(e&&void 0!==e.$version&&void 0!==t.$version&&t.$version<=e.$version)throw new H("CONFLICT",`OCC Conflict: Incoming version (${t.$version}) is not greater than existing version (${e.$version}).`)}var Y=class e extends Error{constructor(t,r){super(t,{cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},G=class extends Y{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},X=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)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await r;let s;await Promise.race([r.then((()=>clearTimeout(s))),new Promise(((r,a)=>{s=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),a(new G("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},Q=class{mutex=new X({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}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){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new 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()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const 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 null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new 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,r="Operation timed out"){if(null==t)return e;let s;return Promise.race([e.then((e=>(clearTimeout(s),e))),new Promise(((e,a)=>{s=setTimeout((()=>a(new G(r))),t)}))])}},Z=class{constructor(e){this.config=e,this.schemasStoreName=e.schemasStoreName||"schemas"}connectionInitializer=new Q({retry:!0,throws:!0});schemasStoreName;async openDatabase(){return new Promise(((e,t)=>{const r=indexedDB.open(this.config.database);r.onerror=()=>t(new Error(`Failed to open database: ${r.error?.message}`)),r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.schemasStoreName)||t.createObjectStore(this.schemasStoreName,{keyPath:"name"})},r.onsuccess=()=>e(r.result)}))}async upgradeDatabase(e,t){const r=e.version+1;return e.close(),new Promise(((e,s)=>{const a=indexedDB.open(this.config.database,r);a.onerror=()=>s(new Error(`Failed to upgrade database: ${a.error?.message}`)),a.onupgradeneeded=e=>{const r=e.target.result,s=e.target.transaction;t(r,s)},a.onsuccess=()=>e(a.result)}))}async ensureStore(e,t="$id",r=[]){(await this.getConnection()).objectStoreNames.contains(e)||await this.upgrade((s=>{if(s.objectStoreNames.contains(this.schemasStoreName)||s.createObjectStore(this.schemasStoreName,{keyPath:"name"}),!s.objectStoreNames.contains(e)){const a=s.createObjectStore(e,{keyPath:t});for(const e of r){const t=1===e.fields.length?e.fields[0]:e.fields;a.createIndex(e.name,t,{unique:e.unique??!1})}}}))}async createStoreIndex(e,t){await this.upgrade(((r,s)=>{const a=s.objectStore(e);if(a.indexNames.contains(t.name))return;const i=1===t.fields.length?t.fields[0]:t.fields;a.createIndex(t.name,i,{unique:t.unique??!1})}))}async dropStoreIndex(e,t){await this.upgrade(((r,s)=>{const a=s.objectStore(e);a.indexNames.contains(t)&&a.deleteIndex(t)}))}getConnection=async()=>{const e=await this.connectionInitializer.do((async()=>{const e=await this.openDatabase();return e.onclose=()=>this.connectionInitializer.reset(),e.onversionchange=()=>{e.close(),this.connectionInitializer.reset()},e}));if(e.error)throw new H("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){const t=await this.getConnection();this.connectionInitializer.reset();const r=await this.connectionInitializer.do((async()=>await this.upgradeDatabase(t,e)));if(r.error)throw new H("INTERNAL_ERROR",`Database upgrade failed for ${this.config.database}`,void 0,r.error);return r.value}close(){const e=this.connectionInitializer.peek();e.value&&e.value.close(),this.connectionInitializer.reset()}};function ee(e){if(e)return void 0!==e.lower&&void 0!==e.upper?IDBKeyRange.bound(e.lower,e.upper,e.lowerOpen,e.upperOpen):void 0!==e.lower?IDBKeyRange.lowerBound(e.lower,e.lowerOpen):void 0!==e.upper?IDBKeyRange.upperBound(e.upper,e.upperOpen):void 0}var te=class{constructor(e,t,r="$id",s=[]){this.connectionManager=e,this.collection=t,this.keyPath=r,this.indexes=s}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 r=>{const s=r.index(e);return this.requestToPromise(s.get(t))}))}async getByKeyRange(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e);return this.requestToPromise(s.getAll(ee(t)))}))}async findByIndex(e,t){return this.withTx("readonly",(async r=>{const s=r.index(e),a=IDBKeyRange.only(t);return this.requestToPromise(s.getAll(a))}))}async put(e){return this.withTx("readwrite",(async t=>{const r=e[this.keyPath];if(void 0!==r){W(await this.requestToPromise(t.get(r)),e)}return this.requestToPromise(t.put(e))}))}async add(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e],s=[];for(const e of r){const r=await this.requestToPromise(t.add(e));s.push(r)}return Array.isArray(e)?s:s[0]}))}async batch(e){return this.withTx("readwrite",(async t=>{for(const r of e)if("put"===r.type||"add"===r.type){const e=Array.isArray(r.data)?r.data:[r.data];for(const s of e)if("put"===r.type){const e=s[this.keyPath];if(void 0!==e){W(await this.requestToPromise(t.get(e)),s)}await this.requestToPromise(t.put(s))}else await this.requestToPromise(t.add(s))}else{const e=Array.isArray(r.data)?r.data:[r.data];for(const r of e)await this.requestToPromise(t.delete(r))}}))}async delete(e){return this.withTx("readwrite",(async t=>{const r=Array.isArray(e)?e:[e];for(const e of r)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 H("INTERNAL_ERROR",`executeInTransaction called on IndexedDBStore '${this.collection}' without a shared IDBTransaction`);const r=t.objectStore(this.collection);for(const t of e)if("put"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e){const e=t[this.keyPath];if(void 0!==e){W(await this.requestToPromise(r.get(e)),t)}await this.requestToPromise(r.put(t))}}else if("add"===t.type){const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(r.add(t))}else{const e=Array.isArray(t.data)?t.data:[t.data];for(const t of e)await this.requestToPromise(r.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",r){return this.withTx("readonly",(async s=>{const a="forward"===t?"next":"prev",i=s.openCursor(ee(r),a);return new Promise(((t,r)=>{let s=null;i.onsuccess=async a=>{const i=a.target.result;if(!i)return t(s);try{const{value:r,done:a,offset:n}=await e(i.value,i.key,i);s=r,a?t(s):n&&n>0?i.advance(n):i.continue()}catch(e){r(e)}},i.onerror=()=>r(this.mapError(i.error))}))}))}mapError(e){if(e instanceof H)return e;const t=e?.message||"Unknown IndexedDB Error",r=e?.name||"";return"QuotaExceededError"===r?new H("INTERNAL_ERROR","Storage quota exceeded"):new H("VersionError"===r?"CONFLICT":"InvalidStateError"===r||"TransactionInactiveError"===r?"TRANSIENT_ERROR":"INTERNAL_ERROR",t)}async withTx(e,t){const r=await this.connectionManager.getConnection();return new Promise((async(s,a)=>{const i=r.transaction(this.collection,e),n=i.objectStore(this.collection);let o,c;i.oncomplete=()=>{c?a(c):s(o)},i.onerror=()=>a(this.mapError(i.error)),i.onabort=()=>a(this.mapError(i.error));try{const e=t(n,i);o=e instanceof Promise?await e:e}catch(e){c=e;try{i.abort()}catch(e){}}}))}requestToPromise(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}},re=new Map,se=e=>{let t=re.get(e.database);t||(t=new Q({retry:!0,throws:!0}),re.set(e.database,t));try{const{value:r,error:s}=t.doSync((()=>new Z(e)));if(s)throw new H("CONNECTION_FAILED",`Failed to initialize connection for database: ${e.database}`,void 0,s);return new te(r,e.collection,e.keyPath)}catch(e){if(e instanceof H)throw e;throw new H("CONNECTION_FAILED",e instanceof Error?e.message:"An unexpected connection error occurred",void 0,e)}};u(m()),u(m()),u(f()),u(z()),u(z());var ae=class extends Error{constructor(e,t){super(e),this.operation=t,this.name="JsonPatchError"}};function ie(e){let t=function(e){return""===e||"/"===e?"":e.startsWith("/")?"/"+e.substring(1).split("/").map(ne).join("/"):"/"+e.split(".").map(ne).join("/")}(e);return""===t?[]:t.substring(1).split("/").map(oe)}function ne(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function oe(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var ce=new Map;function he(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)throw new ae(`Invalid path - parent not found at ${e}`);if(Array.isArray(r)){let t="-"===e?r.length:parseInt(e);if(isNaN(t)||t<0||t>r.length)throw new ae(`Invalid array index: ${e}`);r=r[t]}else{if(!r.hasOwnProperty(e))throw new ae(`Property ${e} not found`);r=r[e]}}return r}function le(e,t){let r=ce.get(t)||ie(t);if(ce.set(t,r),0===r.length)return e;let s=he(e,r.slice(0,-1)),a=r[r.length-1];if(Array.isArray(s)){let e=parseInt(a);if(isNaN(e)||e<0||e>=s.length)throw new ae(`Invalid array index: ${a}`);return s[e]}return s[a]}function de(e,t,r){let s=ce.get(t)||ie(t);ce.set(t,s);let a=he(e,s.slice(0,-1)),i=s[s.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter((e=>e!==r))):a[i]===r&&delete a[i],e}function ue(e,t,r){let s=ce.get(t)||ie(t);if(ce.set(t,s),0===s.length)return r;let a=s.slice(0,-1),i=s[s.length-1],n=he(e,a);if(Array.isArray(n))if("-"===i)n.push(r);else{let e=parseInt(i);if(e<0||e>n.length)throw new ae(`Invalid array index: ${i}`);n.splice(e,0,r)}else n[i]=r;return e}function pe(e,t){let r=ce.get(t)||ie(t);if(ce.set(t,r),0===r.length)return;let s=he(e,r.slice(0,-1)),a=r[r.length-1];if(Array.isArray(s)){let e=parseInt(a);s.splice(e,1)}else delete s[a];return e}function me(e,t){let r=[];switch(e.type){case"addField":r.push({op:"add",path:`/fields/${e.id}`,value:e.definition});break;case"removeField":r.push({op:"remove",path:`/fields/${e.id}`});break;case"modifyField":{let t=`/fields/${e.id}`;Object.entries(e.changes).forEach((([e,s])=>{"object"!=typeof s||null===s||Array.isArray(s),r.push({op:"replace",path:`${t}/${e}`,value:s})}));break}case"deprecateField":r.push({op:"add",path:`/fields/${e.id}/deprecated`,value:!0});break;case"addIndex":t.indexes||r.push({op:"add",path:"/indexes",value:[]}),r.push({op:"add",path:"/indexes/-",value:e.definition});break;case"removeIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/indexes/${s}`});break}case"modifyIndex":{let s=t.indexes?.findIndex((t=>t.name===e.name));void 0!==s&&s>=0&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`/indexes/${s}/${e}`,value:t})}));break}case"addConstraint":t.constraints||r.push({op:"add",path:"/constraints",value:[]}),Array.isArray(e.constraint)?e.constraint.forEach((e=>{r.push({op:"add",path:"/constraints/-",value:e})})):r.push({op:"add",path:"/constraints/-",value:e.constraint});break;case"removeConstraint":{let s=t.constraints?.findIndex((t=>Array.isArray(t)?t.some((t=>t.name===e.name)):t.name===e.name));void 0!==s&&s>=0&&r.push({op:"remove",path:`/constraints/${s}`});break}case"modifyConstraint":{let s=function(e,t){if(!e.constraints)return null;for(let r=0;r<e.constraints.length;r++){let s=e.constraints[r];if(s.name===t)return`/constraints/${r}`;if(fe(s)){let e=ye(s.rules,t);if(e)return`/constraints/${r}${e}`}}return null}(t,e.name);s&&Object.entries(e.changes).forEach((([e,t])=>{r.push({op:"replace",path:`${s}/${e}`,value:t})}));break}}return r}function fe(e){return e&&"operator"in e&&"rules"in e}function ye(e,t){for(let r=0;r<e.length;r++){let s=e[r];if("name"in s&&s.name===t)return`/rules/${r}`;if(fe(s)){let e=ye(s.rules,t);if(e)return`/rules/${r}${e}`}}return null}var ge=new Map;function we(e){return e instanceof RegExp?e.toString().slice(1,-1):JSON.stringify(e)}function be(e,t){let r=e=>({issues:e}),s=(e,t,r,s)=>{switch(t){case"string":return"string"!=typeof e?[{message:"Expected string, got "+typeof e,path:r}]:[];case"number":return"number"!=typeof e||isNaN(e)?[{message:"Expected number, got "+typeof e,path:r}]:[];case"boolean":return"boolean"!=typeof e?[{message:"Expected boolean, got "+typeof e,path:r}]:[];case"array":return Array.isArray(e)?[]:[{message:"Expected array, got "+typeof e,path:r}];case"set":return Array.isArray(e)&&new Set(e).size===e.length?[]:[{message:"Expected unique array, got "+typeof e,path:r}];case"enum":return s?.values?s.values.includes(e)?[]:[{message:`Expected one of ${JSON.stringify(s.values)}, got ${e}`,path:r}]:[{message:"Enum type requires 'values' definition",path:r}];case"object":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected object, got "+typeof e,path:r}]:[];case"record":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];case"union":return"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected union (object), got "+typeof e,path:r}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),"object"!=typeof e||null===e||Array.isArray(e)?[{message:"Expected record (object), got "+typeof e,path:r}]:[];default:return[{message:`Unknown type '${t}'`,path:r}]}};function a(e,t,r,s,i){let n=[],o=e.rules.map(((e,o)=>{let c=[...s,`rules[${o}]`],h=`${e.name}@${c.join(".")}`;if("rules"in e){if(i.has(h))return!0;i.add(h);let s=a(e,t,r,c,i);return n.push(...s),i.delete(h),0===s.length}{let s=r[e.predicate];if(!s)return n.push({message:`Predicate '${e.predicate}' not found`,path:c}),!1;let a=`${e.predicate}:${JSON.stringify(e.parameters)}:${JSON.stringify(t[e.field])}`;if(ge.has(a)){let t=ge.get(a);return t||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:c}),t}let i=s({data:t,field:e.field,arguments:e.parameters});return ge.set(a,i),i||n.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:c}),i}}));return(()=>{switch(e.operator){case"and":return o.every((e=>e));case"or":return o.some((e=>e));case"not":return!o.every((e=>e));case"nor":return!o.some((e=>e));case"xor":return 1===o.filter((e=>e)).length}})()||n.push({message:`Constraint group '${e.name}' failed`,path:s}),n}function i(e,t,r,n,o,c=new Set){let h=[];if("type"in t&&!("fields"in t)){let i=n.length>0?e[n[n.length-1]]:e;return h.push(...s(i,t.type,n,{values:t.values})),t.constraints&&t.constraints.forEach(((e,t)=>{if("rules"in e)h.push(...a(e,{value:i},r,[...n,`constraints[${t}]`],c));else{let s=r[e.predicate];s?s({data:{value:i},field:"value",arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:[...n,`constraints[${t}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...n,`constraints[${t}]`]})}})),h}let l={};if("concrete"in t)if(!0!==t.concrete&&Array.isArray(t.fields)){let r=t.fields,s=r.find((e=>!e.when));s&&Object.assign(l,s.fields);let a=r.find((t=>t.when&&void 0!==e[t.when.field]&&e[t.when.field]===t.when.value));if(a)Object.assign(l,a.fields);else if(!s)return h.push({message:"No matching field set found for discriminated schema",path:n}),h}else l=t.fields;else l=t.fields;let d=new Set(Object.values(l).map((e=>e.name)));Object.entries(l).forEach((([t,l])=>{let d=[...n,l.name],u=Object.hasOwnProperty.call(e,l.name)?e[l.name]:void 0!==l.default?l.default:void 0;l.required&&null==u&&h.push({message:`Field '${l.name}' is required`,path:d});let p=l.schema||l.nestedSchema;if("object"===l.type&&p&&!Array.isArray(p)){let e=o[p.id];if(e)if(c.has(p.id))h.push({message:`Circular reference detected at '${p.id}'`,path:d});else{c.add(p.id);let t=u&&"object"==typeof u&&!Array.isArray(u)?u:{};h.push(...i(t,e,r,d,o,c)),p.constraints?.forEach(((e,s)=>{if("rules"in e)h.push(...a(e,t,r,[...d,`constraints[${s}]`],c));else{let a=r[e.predicate];a?a({data:t,field:void 0,arguments:e.parameters})||h.push({message:e.errorMessage||`Constraint '${e.name}' failed with params ${we(e.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${e.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})),c.delete(p.id)}else h.push({message:`Nested schema '${p.id}' not found`,path:d})}if("union"===l.type&&p&&Array.isArray(p)){let e=!1,t=[];p.forEach(((s,n)=>{let h=o[s.id];if(h)if(c.has(s.id))t.push({message:`Circular reference detected at '${s.id}'`,path:[...d,n.toString()]});else{c.add(s.id);let n=u&&"object"==typeof u&&!Array.isArray(u)?u:{},l=i(n,h,r,d,o,new Set(c));0===l.length&&void 0!==u?(e=!0,s.constraints?.forEach(((s,i)=>{if("rules"in s){let o=a(s,n,r,[...d,`constraints[${i}]`],c);o.length>0&&(e=!1,t.push(...o))}else{let a=r[s.predicate];a&&!a({data:n,field:void 0,arguments:s.parameters})&&(e=!1,t.push({message:s.errorMessage||`Constraint '${s.name}' failed`,path:[...d,`constraints[${i}]`]}))}}))):void 0===u&&t.push(...l.filter((e=>e.message.includes("is required")))),c.delete(s.id)}else t.push({message:`Nested schema '${s.id}' not found`,path:[...d,n.toString()]})})),e||void 0===u?void 0===u&&h.push(...t):(h.push({message:"Value does not match any union schema",path:d}),h.push(...t))}void 0!==u&&(h.push(...s(u,l.type,d,{values:l.values})),("array"===l.type||"set"===l.type)&&Array.isArray(u)&&(l.constraints?.forEach(((e,t)=>{let s=r[e.predicate];s&&!s({data:{[l.name]:u},field:l.name,arguments:e.parameters})&&h.push({message:e.errorMessage||`Constraint '${e.name}' failed for field '${l.name}'`,path:[...d,`constraints[${t}]`]})})),l.itemsType&&u.forEach(((e,t)=>h.push(...s(e,l.itemsType,[...d,t.toString()])))),p&&!Array.isArray(p)&&(o[p.id]?u.forEach(((e,t)=>{"object"==typeof e&&null!==e&&(c.has(p.id)?h.push({message:`Circular reference detected at '${p.id}'`,path:[...d,t.toString()]}):(c.add(p.id),h.push(...i(e,o[p.id],r,[...d,t.toString()],o,c)),c.delete(p.id)))})):h.push({message:`Nested schema '${p.id}' not found`,path:d}))),l.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...a(t,e,r,[...d,`constraints[${s}]`],c));else{let a=r[t.predicate];a?a({data:e,field:l.name,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed for field '${l.name}' with params ${we(t.parameters)}`,path:[...d,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...d,`constraints[${s}]`]})}})))}));for(let t in e)Object.hasOwnProperty.call(e,t)&&!d.has(t)&&h.push({message:`Unexpected field '${t}'`,path:[...n,t]});return t.constraints?.forEach(((t,s)=>{if("rules"in t)h.push(...a(t,e,r,[...n,`constraints[${s}]`],c));else{let a=r[t.predicate];a?a({data:e,field:t.field,arguments:t.parameters})||h.push({message:t.errorMessage||`Constraint '${t.name}' failed with params ${we(t.parameters)}`,path:[...n,`constraints[${s}]`]}):h.push({message:`Predicate '${t.predicate}' not found`,path:[...n,`constraints[${s}]`]})}})),h}return"1.0.0"!==e.version&&console.warn(`Schema version '${e.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:s=>{if("object"!=typeof s||null===s)return r([{message:"Input must be an object",path:[]}]);let a=s,n=i(a,e,t,[],e.nestedSchemas||{});return n.length>0?r(n):(e=>({value:e}))(a)},types:{input:{},output:{}}}}}var ve=class extends Error{constructor(e,t){super(e),this.errors=t,this.name="SchemaValidationError"}},$e=e=>({value:e}),_e=e=>({issues:e}),ke=(e,t,r=!0)=>(void 0!==e||r)&&("string"!=typeof e||""===e.trim())?[{message:"Must be a non-empty string",path:[t]}]:[],Ee=(e,t)=>{let r=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return"string"==typeof e&&r.includes(e)?"dynamic"===e?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[t]}]:[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Se=(e,t)=>{let r=["and","or","not","nor","xor"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]},Ie=(e,t,r=!1)=>(void 0!==e||r)&&"boolean"!=typeof e?[{message:"Must be a boolean",path:[t]}]:[],Oe=(e,t,r)=>{let s=[],a=["type","predicate","field","parameters","name","description","errorMessage"],i=e;return["predicate","name"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(...ke(e.name,`${r}.name`)),s.push(...ke(e.predicate,`${r}.predicate`)),void 0!==e.field&&"string"!=typeof e.field&&s.push({message:"Field must be a string",path:[`${r}.field`]}),void 0!==e.parameters&&s.push(...(e.parameters,[])),s.push(...ke(e.description,`${r}.description`,!1)),s.push(...ke(e.errorMessage,`${r}.errorMessage`,!1)),s},Ae=(e,t,r)=>{let s=[],a=["name","operator","rules"],i=a,n=e;return a.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${r}.${e}`]})})),Object.keys(n).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${r}.${e}`]})})),s.push(...ke(e.name,`${r}.name`)),s.push(...Se(e.operator,`${r}.operator`)),Array.isArray(e.rules)&&0!==e.rules.length?e.rules.forEach(((e,a)=>{"rules"in e?s.push(...Ae(e,t,`${r}.rules[${a}]`)):s.push(...Oe(e,0,`${r}.rules[${a}]`))})):s.push({message:"Rules must be a non-empty array",path:[`${r}.rules`]}),s},Ne=(e,t,r)=>{if(!Array.isArray(e))return[{message:"Must be an array",path:[r]}];let s=[];return e.forEach(((e,a)=>{"rules"in e?s.push(...Ae(e,t,`${r}[${a}]`)):s.push(...Oe(e,0,`${r}[${a}]`))})),s},xe=(e,t)=>{let r=[],s=["operator","field","value","conditions"],a=e;return["operator","field"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...Se(e.operator,`${t}.operator`)),r.push(...ke(e.field,`${t}.field`)),void 0!==e.conditions&&(Array.isArray(e.conditions)?e.conditions.forEach(((e,s)=>r.push(...xe(e,`${t}.conditions[${s}]`)))):r.push({message:"Conditions must be an array",path:[`${t}.conditions`]})),r},je=(e,t)=>{let r=[],s=["fields","type","unique","partial","description","order","name"],a=e;return["fields","type","name"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`)),r.push(...((e,t)=>{let r=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return"string"==typeof e&&r.includes(e)?[]:[{message:`Must be one of ${r.join(", ")}`,path:[t]}]})(e.type,`${t}.type`)),(!Array.isArray(e.fields)||0===e.fields.length||!e.fields.every((e=>"string"==typeof e)))&&r.push({message:"Fields must be a non-empty array of strings",path:[`${t}.fields`]}),r.push(...Ie(e.unique,`${t}.unique`,!1)),e.partial&&r.push(...xe(e.partial,`${t}.partial`)),r.push(...ke(e.description,`${t}.description`,!1)),void 0!==e.order&&!["asc","desc"].includes(e.order)&&r.push({message:"Order must be 'asc' or 'desc'",path:[`${t}.order`]}),r},Ce=(e,t)=>{if(void 0===e)return[];if(!Array.isArray(e))return[{message:"Must be an array",path:[t]}];let r=[];return e.forEach(((e,s)=>r.push(...je(e,`${t}[${s}]`)))),r},Te=(e,t,r,s,a)=>{let i=[];return void 0===e?[]:("union"===r&&Array.isArray(e)?(0===e.length&&i.push({message:"Schema array must not be empty for union type",path:[t]}),e.forEach(((e,r)=>{let a=`${t}[${r}]`;i.push(...ke(e.id,`${a}.id`)),s.includes(e.id)||i.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${a}.id`]}),e.constraints&&i.push(...Ne(e.constraints,"dynamic",`${a}.constraints`)),e.indexes&&i.push(...Ce(e.indexes,`${a}.indexes`))}))):"object"!==r&&("array"!==r||"object"!==a)||Array.isArray(e)?i.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[t]}):(i.push(...ke(e.id,`${t}.id`)),s.includes(e.id)||i.push({message:`Schema ID '${e.id}' must match a nestedSchemas key`,path:[`${t}.id`]}),e.constraints&&i.push(...Ne(e.constraints,"dynamic",`${t}.constraints`)),e.indexes&&i.push(...Ce(e.indexes,`${t}.indexes`))),i)},Me=(e,t,r)=>{if(void 0===e)return[];switch(t){case"string":if("string"!=typeof e)return[{message:"Default must be a string",path:[r]}];break;case"number":if("number"!=typeof e)return[{message:"Default must be a number",path:[r]}];break;case"boolean":if("boolean"!=typeof e)return[{message:"Default must be a boolean",path:[r]}];break;case"array":case"set":if(!Array.isArray(e))return[{message:"Default must be an array",path:[r]}];break;case"enum":if(!Array.isArray(e)||!e.every((e=>"string"==typeof e||"number"==typeof e)))return[{message:"Default must be an array of strings or numbers",path:[r]}];break;case"object":case"record":if("object"!=typeof e||null===e)return[{message:"Default must be an object",path:[r]}];break;case"union":case"dynamic":return[]}return[]},Re=(e,t)=>void 0===e?[]:"object"!=typeof e||null===e?[{message:"Hint must be an object",path:[t]}]:"input"in e&&"object"!=typeof e.input?[{message:"Hint.input must be an object",path:[`${t}.input`]}]:[],De=(e,t,r)=>{let s=[],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],i=e;if(["name","type"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`)),s.push(...Ee(e.type,`${t}.type`)),s.push(...Ie(e.required,`${t}.required`,!1)),e.constraints&&s.push(...Ne(e.constraints,e.type,`${t}.constraints`)),s.push(...Me(e.default,e.type,`${t}.default`)),void 0!==e.values&&("enum"===e.type?(!Array.isArray(e.values)||0===e.values.length||!e.values.every((e=>"string"==typeof e||"number"==typeof e)))&&s.push({message:"Values must be a non-empty array of strings or numbers",path:[`${t}.values`]}):s.push({message:"Values is only valid for 'enum' type",path:[`${t}.values`]})),void 0!==e.schema&&s.push(...Te(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...Ee(e.itemsType,`${t}.itemsType`)),e.nestedSchema){s.push({message:"nestedSchema is deprecated; use schema instead",path:[`${t}.nestedSchema`]});let a=["id"],i=["id","constraints","indexes"],n=e.nestedSchema;a.forEach((e=>{void 0===n[e]&&s.push({message:`${e} is required`,path:[`${t}.nestedSchema.${e}`]})})),Object.keys(n).forEach((e=>{i.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchema.${e}`]})})),s.push(...ke(e.nestedSchema.id,`${t}.nestedSchema.id`)),r.includes(e.nestedSchema.id)||s.push({message:`nestedSchema.id '${e.nestedSchema.id}' must match a nestedSchemas key`,path:[`${t}.nestedSchema.id`]}),e.nestedSchema.constraints&&s.push(...Ne(e.nestedSchema.constraints,"dynamic",`${t}.nestedSchema.constraints`)),e.nestedSchema.indexes&&s.push(...Ce(e.nestedSchema.indexes,`${t}.nestedSchema.indexes`))}if(s.push(...Ie(e.deprecated,`${t}.deprecated`,!1)),e.reference){s.push({message:"reference is deprecated",path:[`${t}.reference`]});let r=["schema","field"],a=["schema","field"],i=e.reference;r.forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.reference.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.reference.${e}`]})})),s.push(...ke(e.reference.schema,`${t}.reference.schema`)),s.push(...ke(e.reference.field,`${t}.reference.field`))}return s.push(...ke(e.description,`${t}.description`,!1)),s.push(...Ie(e.unique,`${t}.unique`,!1)),e.hint&&s.push(...Re(e.hint,`${t}.hint`)),s},Pe=(e,t,r)=>{let s=[];if("type"in e&&["string","number","boolean","array","set","enum","record"].includes(e.type)){let a=["name","type","default","schema","itemsType","constraints","description","metadata"],i=e;["name","type"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`)),s.push(...Ee(e.type,`${t}.type`)),s.push(...Me(e.default,e.type,`${t}.default`)),e.schema&&s.push(...Te(e.schema,`${t}.schema`,e.type,r,e.itemsType)),e.itemsType&&s.push(...Ee(e.itemsType,`${t}.itemsType`)),e.constraints&&s.push(...Ne(e.constraints,e.type,`${t}.constraints`)),s.push(...ke(e.description,`${t}.description`,!1)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}else{let a=["name","description","concrete","fields","indexes","constraints","metadata"],i=e;["name"].forEach((e=>{void 0===i[e]&&s.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||s.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),s.push(...ke(e.name,`${t}.name`)),s.push(...Ie(i.concrete,`${t}.concrete`,!1)),i.concrete&&Array.isArray(i.fields)&&s.push({message:"Fields must be an object when concrete is true",path:[`${t}.fields`]}),Array.isArray(i.fields)?(0===i.fields.length&&s.push({message:"Fields array must not be empty",path:[`${t}.fields`]}),i.fields.forEach(((e,a)=>{let i=`${t}.fields[${a}]`;if("object"==typeof e&&null!==e&&"fields"in e){let t=e.fields;"object"!=typeof t||null===t?s.push({message:"Fields must be a non-empty object",path:[`${i}.fields`]}):Object.entries(t).forEach((([e,t])=>{s.push(...De(t,`${i}.fields.${e}`,r))})),void 0!==e.when&&("object"!=typeof e.when||null===e.when?s.push({message:"When must be an object",path:[`${i}.when`]}):s.push(...ke(e.when.field,`${i}.when.field`)))}else s.push({message:"Each variant must have a 'fields' property",path:[i]})}))):void 0!==i.fields&&("object"!=typeof i.fields||null===i.fields?s.push({message:"Fields must be a non-empty object",path:[`${t}.fields`]}):Object.entries(i.fields).forEach((([e,a])=>{s.push(...De(a,`${t}.fields.${e}`,r))}))),s.push(...ke(e.description,`${t}.description`,!1)),e.indexes&&s.push(...Ce(e.indexes,`${t}.indexes`)),e.constraints&&s.push(...Ne(i.constraints,"dynamic",`${t}.constraints`)),void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata)&&s.push({message:"Metadata must be an object",path:[`${t}.metadata`]})}return s},qe=(e,t)=>{let r=[];switch(e.type||r.push({message:"type is required",path:[`${t}.type`]}),e.type){case"modifyProperty":{let s=["type","id","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`)),(void 0===e.changes||"object"!=typeof e.changes)&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addField":{let s=["type","id","definition"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`)),r.push(...De(e.definition,`${t}.definition`,[]));break}case"removeField":case"deprecateField":{let s=["type","id"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`));break}case"modifyField":{let s=["type","id","changes","nestedSchemaChanges"],a=e;if(["type","id","changes"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]}),e.nestedSchemaChanges){let s=["id","constraints","indexes"],a=e.nestedSchemaChanges;Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.nestedSchemaChanges.${e}`]})})),r.push(...ke(a.id,`${t}.nestedSchemaChanges.id`,!1)),a.constraints&&r.push(...Ne(a.constraints,"dynamic",`${t}.nestedSchemaChanges.constraints`)),a.indexes&&r.push(...Ce(a.indexes,`${t}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let s=["type","definition"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...je(e.definition,`${t}.definition`));break}case"removeIndex":{let s=["type","name"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`));break}case"modifyIndex":{let s=["type","name","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addConstraint":{let s=["type","constraint"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"rules"in e.constraint?r.push(...Ae(e.constraint,"dynamic",`${t}.constraint`)):r.push(...Oe(e.constraint,0,`${t}.constraint`));break}case"removeConstraint":{let s=["type","name"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`));break}case"modifyConstraint":{let s=["type","name","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.name,`${t}.name`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}case"addNestedSchema":{let s=["type","id","definition"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`)),r.push(...Pe(e.definition,`${t}.definition`,[]));break}case"removeNestedSchema":{let s=["type","id"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`));break}case"modifyNestedSchema":{let s=["type","id","changes"],a=s,i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`)),"object"!=typeof e.changes&&r.push({message:"Changes must be an object",path:[`${t}.changes`]});break}default:r.push({message:"Unknown schema change type",path:[`${t}.type`]})}return r},Fe=(e,t)=>{let r=[],s=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...s,"rollback","dependencies"],i=e;s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),r.push(...ke(e.id,`${t}.id`)),r.push(...ke(e.schemaVersion,`${t}.schemaVersion`)),r.push(...ke(e.description,`${t}.description`));let n=["pending","applied","failed"];return n.includes(e.status)||r.push({message:`Status must be one of ${n.join(", ")}`,path:[`${t}.status`]}),Array.isArray(e.changes)&&0!==e.changes.length?e.changes.forEach(((e,s)=>{r.push(...qe(e,`${t}.changes[${s}]`))})):r.push({message:"Changes must be a non-empty array",path:[`${t}.changes`]}),void 0!==e.rollback&&(Array.isArray(e.rollback)?e.rollback.forEach(((e,s)=>r.push(...qe(e,`${t}.rollback[${s}]`)))):r.push({message:"Rollback must be an array",path:[`${t}.rollback`]})),"string"==typeof e.transform?r.push(...ke(e.transform,`${t}.transform`)):"object"==typeof e.transform&&null!==e.transform?r.push(...((e,t)=>{let r=[],s=["forward","backward"],a=s,i=e;return s.forEach((e=>{void 0===i[e]&&r.push({message:`${e} is required`,path:[`${t}.${e}`]})})),Object.keys(i).forEach((e=>{a.includes(e)||r.push({message:`Unknown property ${e}`,path:[`${t}.${e}`]})})),"function"!=typeof e.forward&&r.push({message:"Forward must be a function",path:[`${t}.forward`]}),"function"!=typeof e.backward&&r.push({message:"Backward must be a function",path:[`${t}.backward`]}),r})(e.transform,`${t}.transform`)):r.push({message:"Transform must be a string or object",path:[`${t}.transform`]}),r.push(...ke(e.createdAt,`${t}.createdAt`)),r.push(...ke(e.checksum,`${t}.checksum`)),void 0!==e.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${t}.dependencies`]}),(!Array.isArray(e.dependencies)||!e.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:[`${t}.dependencies`]})),r},Be={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return _e([{message:"Schema must be an object",path:[]}]);let t=e,r=[],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],a=t;if(["name","version","fields"].forEach((e=>{void 0===a[e]&&r.push({message:`${e} is required`,path:[e]})})),Object.keys(a).forEach((e=>{s.includes(e)||r.push({message:`Unknown property ${e}`,path:[e]})})),r.push(...ke(t.name,"name")),r.push(...ke(t.version,"version")),"object"!=typeof t.fields||null===t.fields)r.push({message:"Fields must be a non-empty object",path:["fields"]});else{let e=Object.keys(t.nestedSchemas||{});Object.entries(t.fields).forEach((([t,s])=>{r.push(...De(s,`fields.${t}`,e))}))}if(void 0!==t.nestedSchemas)if("object"!=typeof t.nestedSchemas||null===t.nestedSchemas)r.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let e=Object.keys(t.nestedSchemas);Object.entries(t.nestedSchemas).forEach((([t,s])=>r.push(...Pe(s,`nestedSchemas.${t}`,e))))}return r.push(...ke(t.description,"description",!1)),t.indexes&&r.push(...Ce(t.indexes,"indexes")),t.constraints&&r.push(...Ne(t.constraints,"dynamic","constraints")),void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata)&&r.push({message:"Metadata must be an object",path:["metadata"]}),void 0!==t.dependencies&&(r.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(t.dependencies)||!t.dependencies.every((e=>"string"==typeof e)))&&r.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),void 0!==t.migrations&&(Array.isArray(t.migrations)?t.migrations.forEach(((e,t)=>r.push(...Fe(e,`migrations[${t}]`)))):r.push({message:"Migrations must be an array",path:["migrations"]})),void 0!==t.mock&&"function"!=typeof t.mock&&r.push({message:"Mock must be a function",path:["mock"]}),t.hint&&r.push(...Re(t.hint,"hint")),r.length>0?_e(r):$e(t)},types:{input:{},output:{}}},ze={version:1,vendor:"@asaidimu/anansi",validate:e=>{if("object"!=typeof e||null===e)return _e([{message:"Migration must be an object",path:[]}]);let t=e,r=Fe(t,"");return r.length>0?_e(r):$e(t)},types:{input:{},output:{}}},Ue={version:1,vendor:"@asaidimu/anansi",validate:e=>{if(!Array.isArray(e))return _e([{message:"SchemaChanges must be an array",path:[]}]);let t=e,r=[];return t.forEach(((e,t)=>r.push(...qe(e,`[${t}]`)))),r.length>0?_e(r):$e(t)},types:{input:[],output:[]}};function Le(e){try{return!Be.validate(e).issues}catch(e){throw new ve("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}function Ve(e,t){switch(e.type){case"removeField":case"removeIndex":case"addConstraint":case"modifyConstraint":return"major";case"modifyField":return function(e){return!0===e.required||void 0!==e.type||void 0!==e.itemsType||void 0!==e.nestedSchema||void 0!==e.reference||!0===e.unique}(e.changes)?"major":e.changes.deprecated?"minor":"patch";case"modifyIndex":return void 0!==e.changes.unique||void 0!==e.changes.fields?"major":"minor";case"removeConstraint":case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(e)}`)}}function He(e,t,r){if(0===t.length)throw new Error("No changes provided");(function(e){let t=new Set,r=new Set,s=new Set,a=new Set;for(let i of e)switch(i.type){case"addField":if(r.has(i.id))throw new Error(`Cannot add previously removed field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot add already modified field: ${i.id}`);if(a.has(i.id))throw new Error(`Cannot add deprecated field: ${i.id}`);s.add(i.id);break;case"removeField":if(s.has(i.id))throw new Error(`Cannot remove newly added field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot remove modified field: ${i.id}`);if(a.has(i.id))throw new Error(`Cannot remove field that is being deprecated: ${i.id}`);r.add(i.id);break;case"modifyField":if(r.has(i.id))throw new Error(`Cannot modify removed field: ${i.id}`);if(s.has(i.id))throw new Error(`Cannot modify newly added field: ${i.id}`);if(a.has(i.id))throw new Error(`Cannot modify field that is being deprecated: ${i.id}`);t.add(i.id);break;case"deprecateField":if(r.has(i.id))throw new Error(`Cannot deprecate removed field: ${i.id}`);if(s.has(i.id))throw new Error(`Cannot deprecate newly added field: ${i.id}`);if(t.has(i.id))throw new Error(`Cannot deprecate modified field: ${i.id}`);a.add(i.id)}})(t),function(e){let t=new Set,r=new Set,s=new Set;for(let a of e)switch(a.type){case"addConstraint":let e=a.constraint.name;if(r.has(e))throw new Error(`Cannot add previously removed constraint: ${e}`);if(t.has(e))throw new Error(`Cannot add already modified constraint: ${e}`);s.add(e);break;case"removeConstraint":if(s.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(t.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);r.add(a.name);break;case"modifyConstraint":if(r.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(s.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);t.add(a.name)}}(t);let s=function(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!t)throw new 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)}}(e),a="patch";for(let e of t){let t=Ve(e);if("major"===t){a="major";break}"minor"===t&&"patch"===a&&(a="minor")}switch(a){case"major":return`${s.major+1}.0.0`;case"minor":return`${s.major}.${s.minor+1}.0`;case"patch":return`${s.major}.${s.minor}.${s.patch+1}`}}function Je(e,t){let r=e=>e.split(".").map((e=>parseInt(e,10)||0)),[s,a,i]=r(e),[n,o,c]=r(t);return s-n||a-o||i-c}var Ke,We=class extends Error{constructor(e,t,r,s){super(e),this.code=t,this.migrationId=r,this.cause=s,this.name="MigrationError"}},Ye=((Ke=Ye||{}).INVALID_SCHEMA="INVALID_SCHEMA",Ke.INVALID_MIGRATION="INVALID_MIGRATION",Ke.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",Ke.TIMEOUT="TIMEOUT",Ke.MEMORY_LIMIT="MEMORY_LIMIT",Ke.CONCURRENT_OPERATION="CONCURRENT_OPERATION",Ke.TRANSFORM_ERROR="TRANSFORM_ERROR",Ke.VERSION_NOT_FOUND="VERSION_NOT_FOUND",Ke.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",Ke.STREAM_ERROR="STREAM_ERROR",Ke.ROLLBACK_ERROR="ROLLBACK_ERROR",Ke.MISSING_TRANSFORM="MISSING_TRANSFORM",Ke),Ge=class e{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,r){try{if(!Le(e))throw new We("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every((e=>function(e){try{return!ze.validate(e).issues}catch(e){throw new ve("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}(e))))throw new We("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort(((e,t)=>Je(e.schemaVersion,t.schemaVersion)))}r&&(this.history=r.sort(((e,t)=>Je(e.version,t.version))))}catch(e){throw e instanceof We?e:new We("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,e)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await(async e=>{if(typeof window<"u"&&crypto.subtle){let t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("")}{let{createHash:t}=await import("crypto");return t("sha256").update(e).digest("hex")}})(t)}catch(t){throw new We("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new We("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach((e=>function(e){try{return!Ue.validate(e).issues}catch(e){throw new ve("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}(e)))}catch(e){throw new We("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,r,s){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},i=this.getRelevantMigrations(r,s);return{newSchema:i.reduce(((e,t)=>{let s="forward"===r?t.changes:t.rollback||[];return this.applySchemaChanges(e,s,t.id)}),a),dataPreview:await e.processMigrationList(t,r,i)}}catch(e){throw e instanceof We?e:new We("Dry run failed","INVALID_SCHEMA",void 0,e)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter((r=>{let s="forward"===e?"pending":"applied",a=!t||Je(r.schemaVersion,t)>=0;return r.status===s&&a})).sort(((t,r)=>"forward"===e?t.id.localeCompare(r.id):r.id.localeCompare(t.id)))}applySchemaChanges(e,t,r){try{let s=He(e.version,t);return t.map((t=>{try{return me(t,e)}catch(e){throw new We("Invalid schema change","INVALID_SCHEMA",r,e)}})).reduce(((e,t)=>{try{return function(e,t){let r=JSON.parse(JSON.stringify(e));for(let e of t)try{switch(e.op){case"add":r=ue(r,e.path,e.value);break;case"remove":r=pe(r,e.path);break;case"removeValue":r=de(r,e.path,e.value);break;case"replace":r=ue(pe(r,e.path),e.path,e.value);break;case"copy":{let t=le(r,e.from);r=ue(r,e.path,JSON.parse(JSON.stringify(t)));break}case"move":{let t=le(r,e.from);r=ue(r,e.path,t),r=pe(r,e.from);break}case"test":{let t=le(r,e.path);if(JSON.stringify(t)!==JSON.stringify(e.value))throw new ae("Test operation failed");break}default:throw new ae(`Unsupported operation: ${e.op}`)}}catch(t){throw t instanceof ae&&(t.operation=e),t}return r}(e,t)}catch(e){throw new We("Failed to apply patch","INVALID_SCHEMA",r,e)}}),{...e,version:s})}catch(e){throw e instanceof We?e:new We("Schema update failed","INVALID_SCHEMA",r,e)}}async prepareMigration(){let e=this.migrations.filter((e=>"pending"===e.status));return await this.validateMigrations(e),e}async migrate(t){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");let r=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let s=await e.processMigrationList(t,"forward",r);return this.markMigrationsApplied(r),s}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 We("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 We("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter((e=>"applied"===e.status)).slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(t,r){if(this.isProcessing)throw new We("Concurrent operation","CONCURRENT_OPERATION");try{let s=this.history.findIndex((e=>e.version===t));if(-1===s)throw new Error(`Version ${t} not found in history`);let a=this.migrations.filter((e=>e.schemaVersion===t&&"applied"===e.status)).sort(((e,t)=>t.id.localeCompare(e.id))),i=this.history.length-s;if(i<0)return r;for(let e=0;e<i;e++)this.transformSchema("backward");let n=await e.processMigrationList(r,"backward",a);return this.migrations=this.migrations.map((e=>e.schemaVersion===t&&"applied"===e.status?{...e,status:"pending"}:e)),n}finally{this.isProcessing=!1}}static async processMigrationList(e,t,r){return(await Promise.all(r.map((async e=>{try{return{migration:e,transform:await this.resolveTransform(e,t)}}catch(t){throw new We(`Failed to resolve transform for migration ${e.id}`,"TRANSFORM_ERROR",e.id,t)}})))).filter((e=>!!e.transform)).reduce(((e,{migration:t,transform:r})=>e.pipeThrough(new TransformStream({async transform(e,s){try{let t=await r(e);s.enqueue(t)}catch(e){s.error(new We(`Data transformation failed for migration ${t.id}`,"TRANSFORM_ERROR",t.id,e))}}}))),e)}static async resolveTransform(e,t){return e.transform?"string"==typeof e.transform?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 r=await fetch(e);if(!r.ok)throw new We(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await r.text();if(typeof window<"u"){let e=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(e))).default[t]}{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console:console};return r(s,a,e),a.module.exports[t]}}catch(t){throw new We(`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 We(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,t)}}transformSchema(e){try{if("backward"===e){let e=this.history.pop();if(!e)throw new Error("No previous version");return void(this.currentSchema=e)}let t=this.migrations.filter((e=>"pending"===e.status)).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 We?e:new We("Schema transformation failed","INVALID_SCHEMA",void 0,e)}}};typeof window<"u"&&(window.Buffer=e);var Xe=u(f()),Qe=class{middlewares=[];use(e){this.middlewares.push(e)}execute(e,t){let r=-1;const s=a=>{if(a<=r)throw new Error("next() called multiple times");r=a;const i=this.middlewares[a];if(a===this.middlewares.length)return t();try{return i(e,(()=>s(a+1)))}catch(e){return Promise.reject(e)}};return s(0)}wrap(e,t){const r=this;return new Proxy(e,{get(e,s,a){const i=Reflect.get(e,s,a);return"function"==typeof i?function(...a){const n={...t,operation:s.toString(),args:a};return r.execute(n,(()=>i.apply(e,a)))}:i}})}},Ze=async(e,t)=>{const r=Date.now();try{const s=await t();return et(e,r,s,null),s}catch(t){throw et(e,r,void 0,t),t}};function et(e,t,r,s){if(!e.eventBus)return;const a=Date.now()-t;e.eventBus.emit({name:"telemetry",payload:{type:"telemetry",method:e.operation,timestamp:Date.now(),metadata:{args:e.args,performance:{durationMs:a},source:{level:e.documentId?"document":e.collection?"collection":"database",collection:e.collection,document:e.documentId},result:s?void 0:{type:Array.isArray(r)?"array":typeof r,size:Array.isArray(r)?r.length:void 0},error:s?{message:s.message,name:s.name,stack:s.stack}:null}}})}var{match:tt}=(0,Xe.createMatcher)({});async function rt(e){const{collection:r,initial:s,validator:a,store:i,bus:n,lockManager:o}=e,[c,h]=K(s),{value:l,issues:d}=a?await a["~standard"].validate(c):{value:s,issues:void 0};if(d)throw console.warn({issues:d}),new H("INVALID_DATA",`Invalid data for ${r}`);const u={current:Object.assign(l,h),deleted:!1};void 0===u.current.$id&&(u.current=Object.assign(u.current,{$id:t(),$created:(new Date).toJSON(),$version:1}));const p={save:async e=>{const t=await o.acquire();try{const{$id:t,$version:s}=u.current;if(!t)throw new Error("Document ID missing.");const a=await i.getById(t);if(a&&a.$version!==s)throw new H("CONFLICT",`Version mismatch on ${r}/${t}`);return u.current.$version=(s||0)+1,u.current.$updated=(new Date).toJSON(),e?await e.addOp(i,"put",u.current):await i.put(u.current),n.emit({name:"document:write",payload:{type:"document:write",data:u.current,timestamp:Date.now()}}),!0}finally{t()}},update:async(e,t)=>{const[s,i]=K(Object.assign({},u.current,e)),{value:o,issues:c}=a?await a["~standard"].validate(s):{value:s,issues:void 0};if(c)throw new H("INVALID_DATA",`Invalid update for ${r}`);u.current=Object.assign(o,i);const h=await p.save(t);return h&&n.emit({name:"document:update",payload:{type:"document:update",data:u.current,timestamp:Date.now()}}),h},delete:async e=>{const t=await o.acquire();try{const{$id:t,$version:s}=u.current;if(!t)throw new Error("Document ID missing.");const a=await i.getById(t);if(a&&a.$version!==s)throw new H("CONFLICT",`Version mismatch on delete ${r}/${t}`);return e?await e.addOp(i,"delete",t):await i.delete(t),n.emit({name:"document:delete",payload:{type:"document:delete",data:u.current,timestamp:Date.now()}}),u.deleted=!0,!0}finally{t()}},read:async()=>{const e=u.current.$id,t=await i.getById(e);if(!t)throw new Error("Document not found.");return u.current={...t},n.emit({name:"document:read",payload:{type:"document:read",data:u.current,timestamp:Date.now()}}),!0},state:()=>(e=>{const[t]=K(e);return t})(u.current),subscribe:n.subscribe};return new Proxy({},{get(e,t){if(["update","delete","subscribe","read","state","save"].includes(t)){const e=p[t];return(...t)=>{if(u.deleted)throw new H("INVALID_OPERATION","Document has been deleted");return e(...t)}}if(u.deleted)throw new H("INVALID_OPERATION","Document has been deleted");return Reflect.get(u.current,t)}})}function st(e,t){if("field"in e&&"operator"in e&&"eq"===e.operator&&"value"in e){return e.field}return null}function at(e){return"function"==typeof e._getIDBConnection}var it=class{id;staged=[];done=!1;constructor(){this.id=t()}async addOp(e,t,r){if(this.done)throw new H("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");this.staged.push({store:e,op:{type:t,data:r}})}async commit(){if(this.done)throw new H("TRANSACTION_FAILED","TransactionContext has already been committed or rolled back.");if(this.done=!0,0===this.staged.length)return;const e=new Map,t=new Map;for(const{store:r,op:s}of this.staged)at(r)?(e.has(r)||e.set(r,[]),e.get(r).push(s)):(t.has(r)||t.set(r,[]),t.get(r).push(s));e.size>0&&await this.commitIDB(e),t.size>0&&await this.commitMemory(t)}rollback(){this.staged=[],this.done=!0}async commitIDB(e){const t=Array.from(e.keys()).map((e=>e.name())),r=e.keys().next().value,s=await r._getIDBConnection();await new Promise(((r,a)=>{const i=s.transaction(t,"readwrite");i.oncomplete=()=>r(),i.onerror=()=>a(i.error??new Error("IDB transaction error")),i.onabort=()=>a(i.error??new Error("IDB transaction aborted")),(async()=>{try{for(const[t,r]of e)await t.executeInTransaction(r,i)}catch(e){try{i.abort()}catch(e){}a(e)}})()}))}async commitMemory(e){const t=[];try{for(const[r,s]of e){const e=r._snapshotMemory();t.push({store:r,snapshot:e}),await r.executeInTransaction(s,null)}}catch(e){for(const{store:e,snapshot:r}of t)try{e._rollbackMemory(r)}catch(e){}throw e}}completed(){return this.done}};function nt(e,t){return e instanceof H?e:e instanceof Error?new H("INTERNAL_ERROR",`Store operation failed during migration of '${t}': ${e.message}`,void 0,e):new H("INTERNAL_ERROR",`An unexpected error occurred during migration of collection '${t}'`)}async function ot(e,r){const s=V(),a=new Map,i=new Qe;i.use(((e=3,t=100)=>async(r,s)=>{let a=0;for(;a<e;)try{return await s()}catch(r){if(!(r instanceof H&&"TRANSIENT_ERROR"===r.type))throw r;{if(a++,a>=e)throw r;const s=t*Math.pow(2,a)+50*Math.random();await new Promise((e=>setTimeout(e,s)))}}})()),e.enableTelemetry&&i.use(Ze);const n=new Map,o=r({...e,collection:"schemas",keyPath:"name"},[]);async function c(t,s=[]){let a=n.get(t);return a||(a=r({...e,collection:t,keyPath:"$id"},s),n.set(t,a)),await a.open(),a}async function h(r){if(a.has(r))return a.get(r);const n=await o.getById(r);if(!n)throw new H("SCHEMA_NOT_FOUND",`Collection '${r}' does not exist`);const h=await c(r,n.indexes??[]),l=be(n,e.predicates||{}),d=await async function({collection:e,validator:r,bus:s,store:a,pipeline:i,validate:n}){const o=new J,c={collection:e,validator:n?r:void 0,store:a,bus:s,pipeline:i,lockManager:o,valid:!0},h={async validate(e){const t=r["~standard"].validate(e);return t instanceof Promise?await t:t},create:async(i,o)=>{const[h,l]=K(i),{value:d,issues:u}=n?await r["~standard"].validate(h):{value:h,issues:void 0};if(u)throw new H("INVALID_DATA",`Invalid data for collection '${e}'`);const p=Object.assign(d,l,{$id:t(),$created:(new Date).toJSON(),$version:1});o?await o.addOp(a,"add",p):await a.add(p),s.emit({name:"document:create",payload:{type:"document:create",data:p,timestamp:Date.now()}});const m=await rt({...c,initial:p});return s.emit({name:"collection:read",payload:{type:"collection:read",model:e,timestamp:Date.now()}}),m},find:async t=>{let r;const i=st(t);if(i)try{const e=t.value;r=(await a.findByIndex(i,e))[0]}catch{r=void 0}if(void 0===r&&(r=await a.cursor((async e=>e&&tt(e,t)?{value:e,done:!0}:{value:null,done:!1}))??void 0),!r)return null;const n=await rt({...c,initial:r});return s.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:e,timestamp:Date.now()}}),n},filter:async t=>{let r=[];const i=st(t);if(i)try{const e=t.value;r=await a.findByIndex(i,e)}catch{r=[]}0===r.length&&await a.cursor((async e=>(e&&tt(e,t)&&r.push(e),{value:null,done:!1})));const n=await Promise.all(r.map((e=>rt({...c,initial:e}))));return s.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:e,timestamp:Date.now()}}),n},list:async t=>{const r={total:await a.count(),offset:"offset"===t.type?t.offset:0,limit:t.limit,count:0};return 0===r.total?{next:async()=>({value:[],done:!0})}:{async next(){const i="offset"===t.type?await async function(e,t){const{offset:r,limit:s}=t,a=[];let i=0,n=!1;for(;!(n||(await e((async e=>i<r?(i++,{value:e,done:!1,offset:1}):(a.push(e),i++,i>=r+s?(n=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),a.length>=s)););return a}(a.cursor.bind(a),{...t,offset:r.offset}):await async function(e,t){const{limit:r,direction:s}=t,a=[];let i=!1;for(;!i;)await e((async e=>(a.push(e),a.length>=r?(i=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),s);return a}(a.cursor.bind(a),{...t});r.offset+=r.limit,r.count+=i.length;const n=await Promise.all(i.map((e=>rt({...c,initial:e}))));return s.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:e,timestamp:Date.now()}}),{value:n,done:r.count>=r.total}}}}},l={...i.wrap(h,{collection:e,eventBus:s}),subscribe:s.subscribe,invalidate:()=>c.valid=!1};return new Proxy(l,{get(t,r,s){const a=Reflect.get(t,r,s);return"function"==typeof a?(...s)=>{if(!c.valid&&"invalidate"!==r)throw new H("INVALID_OPERATION",`Collection '${e}' has been invalidated and cannot be used.`);return a.apply(t,s)}:a}})}({collection:r,bus:s,validator:l,validate:Boolean(e.validate),store:h,pipeline:i});return s.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:r},timestamp:Date.now()}}),a.set(r,d),a.get(r)}async function l(e){return await o.put(e),s.emit({name:"collection:update",payload:{type:"collection:update",schema:e,timestamp:Date.now()}}),!0}await o.open();const d={collection:h,createCollection:async e=>{if(await o.getById(e.name))throw new H("SCHEMA_ALREADY_EXISTS",`Collection '${e.name}' already exists`);if(!Le(e))throw new H("INVALID_SCHEMA_DEFINITION","Invalid schema definition");await o.put(e);const t=h(e.name);return s.emit({name:"collection:create",payload:{type:"collection:create",schema:e,timestamp:Date.now()}}),t},deleteCollection:async e=>{const t=await o.getById(e);if(!t)throw new H("SCHEMA_NOT_FOUND",`Collection '${e}' does not exist`);const r=await c(e,t.indexes??[]);return await r.clear(),n.delete(e),await o.delete(e),a.delete(e),s.emit({name:"collection:delete",payload:{type:"collection:delete",schema:t,timestamp:Date.now()}}),!0},updateCollection:l,migrateCollection:async(e,t,r=100)=>{const s=a.get(e);s&&(s.invalidate(),a.delete(e));const i=await o.getById(e);if(!i)throw new H("SCHEMA_NOT_FOUND",`Schema for '${e}' not found`);const n=await c(e,i.indexes??[]),d=new Ge(i);await d.add(t);const u=(await d.dryRun(new ReadableStream({start(e){e.close()}}),"forward")).newSchema,p=new Set((i.indexes??[]).map((e=>e.name))),m=u.indexes??[],f=new Set(m.map((e=>e.name))),y=m.filter((e=>!p.has(e.name))),g=(i.indexes??[]).filter((e=>!f.has(e.name)));await l(u);try{const t=function(e,t,r){let s,a=!1;return new ReadableStream({async pull(i){if(a)return void i.close();let n=0;const o=void 0!==s?{lower:s,lowerOpen:!0}:void 0;try{await t.cursor((async(e,t)=>(i.enqueue(e),s=t,n++,n>=r?{done:!0,value:e}:{done:!1,value:e})),"forward",o),n<r&&(a=!0)}catch(t){i.error(nt(t,e))}},cancel(){console.warn(`[migrateCollection] Input stream for collection '${e}' cancelled.`)}})}(e,n,r),s=await d.migrate(t);await async function(e,t,r,s){const a=t.getReader();let i=[];try{for(;;){const{value:e,done:t}=await a.read();if(t)break;if(!e)continue;const{$version:n}=e;e.$version=(n||0)+1,e.$updated=(new Date).toJSON(),i.push(e),i.length>=s&&(await r.batch([{type:"put",data:i}]),i=[])}i.length>0&&await r.batch([{type:"put",data:i}])}catch(t){throw nt(t,e)}finally{a.releaseLock()}}(e,s,n,r)}catch(t){throw nt(t,e)}for(const e of y)await n.createIndex(e);for(const e of g)await n.dropIndex(e.name);return await h(e)}},u=i.wrap(d,{eventBus:s}),p={...u,transaction:async e=>{const t=new it;try{await e(t),t.completed()||await t.commit()}catch(e){throw t.completed()||t.rollback(),e}},subscribe:s.subscribe,close:()=>{n.clear(),s.clear()},clear:async()=>{await o.clear(),await Promise.all(n.values().map((e=>e.clear())))},ensureCollection:async e=>{try{await u.createCollection(e)}catch(e){if(e instanceof H&&"SCHEMA_ALREADY_EXISTS"===e.type)return;throw e}},setupCollections:async e=>{for(const t of e)await p.ensureCollection(t)}};return p}var ct=u(f()),ht=class e{static dbInstances=new Map;static collectionInstances=new Map;static eventBusMap=new Map;static defaultModelName="stores";static getDatabase(t){const{database:r,enableTelemetry:s=!1,collection:a=e.defaultModelName}=t;if(!e.dbInstances.has(r)){const t=ot({database:r,enableTelemetry:s},se).then((async e=>{try{await e.createCollection({name:a,version:"1.0.0",nestedSchemas:{},fields:{store:{name:"store",type:"string",required:!0},data:{name:"data",type:"object",required:!0},version:{name:"version",type:"string",required:!0},app:{name:"app",type:"string",required:!0}}})}catch(e){if(e instanceof H&&"SCHEMA_ALREADY_EXISTS"!==e.type)throw e}return e}));e.dbInstances.set(r,t)}return e.dbInstances.get(r)}static getEventBus(t,r){const s=`${t}_store_${r}`;return e.eventBusMap.has(s)||e.eventBusMap.set(s,V({batch:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${t}:${r}:`,e),crossTab:!0,channelName:s})),e.eventBusMap.get(s)}static getCollection(t){const{database:r,collection:s=e.defaultModelName}=t,a=`${r}:${s}`;if(!e.collectionInstances.has(a)){const r=e.getDatabase(t).then((e=>e.collection(s)));e.collectionInstances.set(a,r)}return e.collectionInstances.get(a)}static async closeDatabase(t){const r=e.dbInstances.get(t);if(r){(await r).close(),e.dbInstances.delete(t);const s=[];e.collectionInstances.forEach(((e,r)=>{r.startsWith(`${t}:`)&&s.push(r)})),s.forEach((t=>e.collectionInstances.delete(t)));const a=[];e.eventBusMap.forEach(((e,r)=>{r.startsWith(`${t}_store_`)&&(e.clear(),a.push(r))})),a.forEach((t=>e.eventBusMap.delete(t)))}}static async closeAll(){const t=Array.from(e.dbInstances.keys()).map((t=>e.closeDatabase(t)));await Promise.all(t)}static getActiveDatabases(){return Array.from(e.dbInstances.keys())}},lt=class{collection=null;collectionPromise;config;eventBus;initialized=!1;initializationCallbacks=[];doc=null;getStoreName(){return`_${this.config.app}_${this.config.store}_`}constructor(e){this.config=e,this.collectionPromise=ht.getCollection(this.config),this.collectionPromise.then((e=>{this.collection=e,this.initialize()})).catch((e=>{console.error(`Failed to initialize collection for store ${this.getStoreName()}:`,e)})),this.eventBus=ht.getEventBus(this.config.database,this.getStoreName())}async initialize(){try{const e=await this._get();if(e&&e.version!==this.config.version&&this.config.onUpgrade){const{state:t}=await this.config.onUpgrade({data:e.data,version:e.version,app:e.app});await this.set("migration",t)}this.initialized=!0,this.initializationCallbacks.forEach((e=>e())),this.initializationCallbacks=[]}catch(e){console.error(`Failed to initialize and upgrade store ${this.getStoreName()}:`,e)}}_onInitialized(e){this.initialized?e():this.initializationCallbacks.push(e)}async getCollection(){return this.collection?this.collection:this.collectionPromise}async set(e,t){try{const r=await this.getCollection(),s=await this._read(),a={store:this.getStoreName(),data:t,version:this.config.version,app:this.config.app};let i;return s?i=await s.update(a):(this.doc=await r.create(a),i=!0),i&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.getStoreName(),instanceId:e,state:t,version:this.config.version,app:this.config.app}}),i}catch(t){return console.error(`Failed to set state for store ${this.getStoreName()} in database ${this.config.database} by instance ${e}:`,t),!1}}async _read(){if(this.doc)return this.doc;const e=await this.getCollection(),t=(new ct.QueryBuilder).where({field:"store",operator:"eq",value:this.getStoreName()}).build(),r=await e.find(t.filters);return this.doc=r,this.doc}async _get(){try{const e=await this._read();return e?e.read().then((()=>e)):null}catch(e){return console.error(`Failed to get state for store ${this.getStoreName()} in database ${this.config.database}:`,e),null}}async get(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));const e=await this._get();return e?e.data:null}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:s,state:a})=>{r===this.getStoreName()&&s!==e&&t(a)}))}async clear(){this.initialized||await new Promise((e=>{this._onInitialized(e)}));try{const e=await this._read();return!e||!await e.delete()||(this.doc=null,!0)}catch(e){return console.error(`Failed to clear state for store ${this.getStoreName()} in database ${this.config.database}:`,e),!1}}stats(){return{version:this.config.version,id:this.config.app}}async close(){await ht.closeDatabase(this.config.database)}};export{lt as IndexedDBPersistence,L as WebStoragePersistence};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/utils-persistence",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "description": "Persistence utilities.",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",